From a50921374a72d636c30dbab24b1dd0235db1b871 Mon Sep 17 00:00:00 2001 From: Chris Constable Date: Thu, 19 Nov 2026 11:59:07 -0700 Subject: [PATCH] feat(payload-caching): add opt-in payload caching support for external storage. --- CHANGELOG.md | 3 + .../temporal/client/ActivityClientImpl.java | 3 +- .../client/ActivityClientOptions.java | 46 +++- .../io/temporal/client/NexusClientImpl.java | 4 +- .../temporal/client/NexusClientOptions.java | 31 ++- .../client/WorkflowClientInternalImpl.java | 3 +- .../client/WorkflowClientOptions.java | 53 +++- .../client/schedules/ScheduleClientImpl.java | 4 +- .../schedules/ScheduleClientOptions.java | 33 ++- .../ExternalStoragePayloadTransformer.java | 200 ++++++++++++-- .../storage/ExternalStorageRunner.java | 8 +- .../payload/storage/PayloadCacheKeys.java | 50 ++++ .../payload/storage/PayloadCacheMetrics.java | 84 ++++++ .../nexus/TemporalNexusClientImpl.java | 1 + .../nexus/TemporalOperationHandler.java | 1 + .../payload/storage/DisabledPayloadCache.java | 30 +++ .../payload/storage/InMemoryPayloadCache.java | 142 ++++++++++ .../payload/storage/PayloadCache.java | 35 +++ .../java/io/temporal/worker/MetricsType.java | 18 ++ .../main/java/io/temporal/worker/Worker.java | 15 +- .../client/PayloadCacheClientOptionsTest.java | 92 +++++++ .../client/WorkflowExecutionMetadataTest.java | 4 +- .../activity/HeartbeatContextImplTest.java | 4 +- ...yAndScheduleClientExternalStorageTest.java | 18 +- .../ClientDataConverterFactoryTest.java | 10 +- ...orkflowClientInvokerStorageTargetTest.java | 4 +- ...pletionClientFactoryStorageTargetTest.java | 4 +- ...anualActivityCompletionClientImplTest.java | 4 +- .../ExternalStorageDataConverterTest.java | 7 +- .../ExternalStoragePayloadCacheTest.java | 243 ++++++++++++++++++ ...ExternalStoragePayloadTransformerTest.java | 25 +- .../storage/ExternalStorageRunnerTest.java | 4 +- .../payload/storage/PayloadCacheKeysTest.java | 68 +++++ .../storage/PayloadCacheMetricsTest.java | 112 ++++++++ ...orkflowRunTaskHandlerTaskHandlerTests.java | 13 +- .../ServiceWorkflowHistoryIteratorTest.java | 4 +- .../TestEnvironmentPayloadCacheTest.java | 187 ++++++++++++++ .../internal/worker/NexusWorkerTest.java | 4 +- .../WorkflowWorkerPayloadCacheTest.java | 104 ++++++++ .../internal/worker/WorkflowWorkerTest.java | 7 +- .../storage/InMemoryPayloadCacheTest.java | 160 ++++++++++++ .../io/temporal/testing/WorkflowReplayer.java | 6 + 42 files changed, 1777 insertions(+), 71 deletions(-) create mode 100644 temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheKeys.java create mode 100644 temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheMetrics.java create mode 100644 temporal-sdk/src/main/java/io/temporal/payload/storage/DisabledPayloadCache.java create mode 100644 temporal-sdk/src/main/java/io/temporal/payload/storage/InMemoryPayloadCache.java create mode 100644 temporal-sdk/src/main/java/io/temporal/payload/storage/PayloadCache.java create mode 100644 temporal-sdk/src/test/java/io/temporal/client/PayloadCacheClientOptionsTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadCacheTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheKeysTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheMetricsTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/internal/testing/TestEnvironmentPayloadCacheTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerPayloadCacheTest.java create mode 100644 temporal-sdk/src/test/java/io/temporal/payload/storage/InMemoryPayloadCacheTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 806390cfae..834c948c97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,9 @@ to docs, or any other relevant information. - `@TemporalOperation` methods can return their output directly for synchronous completion. Existing methods returning `TemporalOperationResult`, including asynchronous results, remain supported. +- **Experimental**: Opt-in payload caching for External Storage is now available. To enable it, + call `setPayloadCache` on your client options with a cache (e.g. `InMemoryPayloadCache`) or + `PayloadCache.disabled()` to disable caching. ### Changed - Updated Cloud API bindings to v0.27.0, including opt-in user group memberships, projects, diff --git a/temporal-sdk/src/main/java/io/temporal/client/ActivityClientImpl.java b/temporal-sdk/src/main/java/io/temporal/client/ActivityClientImpl.java index 91803ecbf2..2d3c417655 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/ActivityClientImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/client/ActivityClientImpl.java @@ -39,7 +39,8 @@ class ActivityClientImpl implements ActivityClient, ActivityClientInternal { ExternalStorageRunner externalStorage = options.getExternalStorage() == null ? null - : ExternalStorageRunner.create(options.getExternalStorage(), options.getNamespace()); + : ExternalStorageRunner.create( + options.getExternalStorage(), options.getNamespace(), options.getPayloadCache()); DataConverter internalDataConverter = ClientDataConverterFactory.forClient(options.getDataConverter()); this.stubs = stubs; diff --git a/temporal-sdk/src/main/java/io/temporal/client/ActivityClientOptions.java b/temporal-sdk/src/main/java/io/temporal/client/ActivityClientOptions.java index 2a129a9954..2f9c5b5b79 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/ActivityClientOptions.java +++ b/temporal-sdk/src/main/java/io/temporal/client/ActivityClientOptions.java @@ -6,10 +6,12 @@ import io.temporal.common.converter.GlobalDataConverter; import io.temporal.common.interceptors.ActivityClientInterceptor; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.List; import java.util.Objects; +import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Options for {@link ActivityClient} configuration. */ @@ -50,6 +52,7 @@ public static final class Builder { private List contextPropagators; private List interceptors; private ExternalStorage externalStorage; + private PayloadCache payloadCache; private Builder() {} @@ -63,6 +66,7 @@ private Builder(ActivityClientOptions options) { contextPropagators = options.contextPropagators; interceptors = options.interceptors; externalStorage = options.externalStorage; + payloadCache = options.payloadCache; } /** Set the namespace this client will operate on. */ @@ -118,6 +122,18 @@ public Builder setExternalStorage(@Nullable ExternalStorage externalStorage) { return this; } + /** + * Cache for payloads that external storage uploads and downloads. Used only when external + * storage is set. Calls made through this client report no cache metrics. + * + *

Pass {@link PayloadCache#disabled()} to turn caching off explicitly. Defaults to off. + */ + @Experimental + public Builder setPayloadCache(@Nullable PayloadCache payloadCache) { + this.payloadCache = payloadCache; + return this; + } + public ActivityClientOptions build() { String name = identity == null ? ManagementFactory.getRuntimeMXBean().getName() : identity; return new ActivityClientOptions( @@ -126,7 +142,8 @@ public ActivityClientOptions build() { name, contextPropagators == null ? EMPTY_CONTEXT_PROPAGATORS : contextPropagators, interceptors == null ? EMPTY_INTERCEPTORS : interceptors, - externalStorage); + externalStorage, + payloadCache == null ? PayloadCache.disabled() : payloadCache); } } @@ -136,6 +153,7 @@ public ActivityClientOptions build() { private final List contextPropagators; private final List interceptors; private final @Nullable ExternalStorage externalStorage; + private final @Nonnull PayloadCache payloadCache; private ActivityClientOptions( String namespace, @@ -143,13 +161,15 @@ private ActivityClientOptions( String identity, List contextPropagators, List interceptors, - @Nullable ExternalStorage externalStorage) { + @Nullable ExternalStorage externalStorage, + @Nonnull PayloadCache payloadCache) { this.namespace = namespace; this.dataConverter = dataConverter; this.identity = identity; this.contextPropagators = contextPropagators; this.interceptors = interceptors; this.externalStorage = externalStorage; + this.payloadCache = payloadCache; } /** @@ -204,6 +224,15 @@ public ExternalStorage getExternalStorage() { return externalStorage; } + /** + * Cache for external storage payloads, or {@link PayloadCache#disabled()} when caching is off. + */ + @Experimental + @Nonnull + public PayloadCache getPayloadCache() { + return payloadCache; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -214,13 +243,20 @@ public boolean equals(Object o) { && Objects.equals(identity, that.identity) && Objects.equals(contextPropagators, that.contextPropagators) && Objects.equals(interceptors, that.interceptors) - && Objects.equals(externalStorage, that.externalStorage); + && Objects.equals(externalStorage, that.externalStorage) + && Objects.equals(payloadCache, that.payloadCache); } @Override public int hashCode() { return Objects.hash( - namespace, dataConverter, identity, contextPropagators, interceptors, externalStorage); + namespace, + dataConverter, + identity, + contextPropagators, + interceptors, + externalStorage, + payloadCache); } @Override @@ -240,6 +276,8 @@ public String toString() { + interceptors + ", externalStorage=" + externalStorage + + ", payloadCache=" + + payloadCache + '}'; } } diff --git a/temporal-sdk/src/main/java/io/temporal/client/NexusClientImpl.java b/temporal-sdk/src/main/java/io/temporal/client/NexusClientImpl.java index 6e27aa7dcb..a110fb0ab4 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/NexusClientImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/client/NexusClientImpl.java @@ -53,7 +53,9 @@ public static NexusClient newInstance(WorkflowServiceStubs service, NexusClientO : ClientDataConverterFactory.forClient( clientOptions.getDataConverter(), ExternalStorageRunner.create( - clientOptions.getExternalStorage(), clientOptions.getNamespace()))); + clientOptions.getExternalStorage(), + clientOptions.getNamespace(), + clientOptions.getPayloadCache()))); workflowServiceStubs = new NamespaceInjectWorkflowServiceStubs(workflowServiceStubs, options.getNamespace()); this.workflowServiceStubs = workflowServiceStubs; diff --git a/temporal-sdk/src/main/java/io/temporal/client/NexusClientOptions.java b/temporal-sdk/src/main/java/io/temporal/client/NexusClientOptions.java index ba4d5d67b0..32b7e70826 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/NexusClientOptions.java +++ b/temporal-sdk/src/main/java/io/temporal/client/NexusClientOptions.java @@ -6,9 +6,11 @@ import io.temporal.common.interceptors.NexusClientInterceptor; import io.temporal.internal.client.NexusClientResolvedOptions; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import java.lang.management.ManagementFactory; import java.util.Collections; import java.util.List; +import javax.annotation.Nonnull; import javax.annotation.Nullable; /** @@ -40,18 +42,21 @@ public class NexusClientOptions { private final DataConverter dataConverter; private final String identity; private final @Nullable ExternalStorage externalStorage; + private final @Nonnull PayloadCache payloadCache; private NexusClientOptions( String namespace, List interceptors, DataConverter dataConverter, String identity, - @Nullable ExternalStorage externalStorage) { + @Nullable ExternalStorage externalStorage, + @Nonnull PayloadCache payloadCache) { this.namespace = namespace; this.interceptors = interceptors; this.dataConverter = dataConverter; this.identity = identity; this.externalStorage = externalStorage; + this.payloadCache = payloadCache; } /** Get the namespace this client will operate on. */ @@ -78,6 +83,14 @@ public ExternalStorage getExternalStorage() { return externalStorage; } + /** + * Cache for external storage payloads, or {@link PayloadCache#disabled()} when caching is off. + */ + @Nonnull + public PayloadCache getPayloadCache() { + return payloadCache; + } + /** * Human-readable identity of this client. Stamped onto outgoing write requests (start, cancel, * terminate) so server-side history and audit trails can attribute the action to a caller. @@ -128,6 +141,7 @@ public static class Builder { private DataConverter dataConverter = GlobalDataConverter.get(); private String identity; private ExternalStorage externalStorage; + private PayloadCache payloadCache; private Builder() {} @@ -140,6 +154,7 @@ private Builder(NexusClientOptions options) { dataConverter = options.dataConverter; identity = options.identity; externalStorage = options.externalStorage; + payloadCache = options.payloadCache; } /** Set the namespace this client will operate on. */ @@ -188,6 +203,17 @@ public NexusClientOptions.Builder setExternalStorage( return this; } + /** + * Cache for payloads that external storage uploads and downloads. Used only when external + * storage is set. Calls made through this client report no cache metrics. + * + *

Pass {@link PayloadCache#disabled()} to turn caching off explicitly. Defaults to off. + */ + public NexusClientOptions.Builder setPayloadCache(@Nullable PayloadCache payloadCache) { + this.payloadCache = payloadCache; + return this; + } + public NexusClientOptions build() { String resolvedIdentity = identity == null ? ManagementFactory.getRuntimeMXBean().getName() : identity; @@ -196,7 +222,8 @@ public NexusClientOptions build() { interceptors, dataConverter, resolvedIdentity, - externalStorage); + externalStorage, + payloadCache == null ? PayloadCache.disabled() : payloadCache); } } } diff --git a/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientInternalImpl.java b/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientInternalImpl.java index 67708dfb04..51ef5cae53 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientInternalImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientInternalImpl.java @@ -120,7 +120,8 @@ public static WorkflowClient newInstance( ExternalStorageRunner externalStorageRunner = externalStorage == null ? null - : ExternalStorageRunner.create(externalStorage, options.getNamespace()); + : ExternalStorageRunner.create( + externalStorage, options.getNamespace(), options.getPayloadCache()); this.externalStorageRunner = externalStorageRunner; this.genericClient = new GenericWorkflowClientImpl(workflowServiceStubs, metricsScope); this.interceptors = options.getInterceptors(); diff --git a/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientOptions.java b/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientOptions.java index 0450786b3d..5654dbc7f3 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientOptions.java +++ b/temporal-sdk/src/main/java/io/temporal/client/WorkflowClientOptions.java @@ -8,12 +8,14 @@ import io.temporal.common.converter.GlobalDataConverter; import io.temporal.common.interceptors.WorkflowClientInterceptor; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; +import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Options for WorkflowClient configuration. */ @@ -56,6 +58,7 @@ public static final class Builder { private Duration workerHeartbeatInterval; private boolean disableWorkerEnvironmentInfo; private ExternalStorage externalStorage; + private PayloadCache payloadCache; private Builder() {} @@ -74,6 +77,7 @@ private Builder(WorkflowClientOptions options) { workerHeartbeatInterval = options.workerHeartbeatInterval; disableWorkerEnvironmentInfo = options.disableWorkerEnvironmentInfo; externalStorage = options.externalStorage; + payloadCache = options.payloadCache; } public Builder setNamespace(String namespace) { @@ -105,6 +109,22 @@ public Builder setExternalStorage(@Nullable ExternalStorage externalStorage) { return this; } + /** + * Cache for payloads that external storage uploads and downloads. Used only when external + * storage is set. + * + *

Workers built from this client share this cache and report its metrics for their own task + * handling. Calls made through this client report no cache metrics. That includes calls made + * from Activities and Nexus handlers through the client they are given. + * + *

Pass {@link PayloadCache#disabled()} to turn caching off explicitly. Defaults to off. + */ + @Experimental + public Builder setPayloadCache(@Nullable PayloadCache payloadCache) { + this.payloadCache = payloadCache; + return this; + } + /** * Interceptor used to intercept workflow client calls. * @@ -215,7 +235,8 @@ public WorkflowClientOptions build() { plugins == null ? EMPTY_PLUGINS : plugins, resolveHeartbeatInterval(workerHeartbeatInterval), disableWorkerEnvironmentInfo, - externalStorage); + externalStorage, + resolvePayloadCache(payloadCache)); } /** @@ -244,7 +265,12 @@ public WorkflowClientOptions validateAndBuildWithDefaults() { plugins == null ? EMPTY_PLUGINS : plugins, resolveHeartbeatInterval(workerHeartbeatInterval), disableWorkerEnvironmentInfo, - externalStorage); + externalStorage, + resolvePayloadCache(payloadCache)); + } + + private static PayloadCache resolvePayloadCache(@Nullable PayloadCache payloadCache) { + return payloadCache == null ? PayloadCache.disabled() : payloadCache; } private static Duration resolveHeartbeatInterval(Duration raw) { @@ -291,6 +317,8 @@ private static Duration resolveHeartbeatInterval(Duration raw) { private final @Nullable ExternalStorage externalStorage; + private final @Nonnull PayloadCache payloadCache; + private WorkflowClientOptions( String namespace, DataConverter dataConverter, @@ -302,7 +330,8 @@ private WorkflowClientOptions( WorkflowClientPlugin[] plugins, Duration workerHeartbeatInterval, boolean disableWorkerEnvironmentInfo, - @Nullable ExternalStorage externalStorage) { + @Nullable ExternalStorage externalStorage, + @Nonnull PayloadCache payloadCache) { this.namespace = namespace; this.dataConverter = dataConverter; this.interceptors = interceptors; @@ -314,6 +343,7 @@ private WorkflowClientOptions( this.workerHeartbeatInterval = workerHeartbeatInterval; this.disableWorkerEnvironmentInfo = disableWorkerEnvironmentInfo; this.externalStorage = externalStorage; + this.payloadCache = payloadCache; } /** @@ -336,6 +366,15 @@ public ExternalStorage getExternalStorage() { return externalStorage; } + /** + * Cache for external storage payloads, or {@link PayloadCache#disabled()} when caching is off. + */ + @Experimental + @Nonnull + public PayloadCache getPayloadCache() { + return payloadCache; + } + public WorkflowClientInterceptor[] getInterceptors() { return interceptors; } @@ -421,6 +460,8 @@ public String toString() { + disableWorkerEnvironmentInfo + ", externalStorage=" + externalStorage + + ", payloadCache=" + + payloadCache + '}'; } @@ -440,7 +481,8 @@ public boolean equals(Object o) { && com.google.common.base.Objects.equal( workerHeartbeatInterval, that.workerHeartbeatInterval) && disableWorkerEnvironmentInfo == that.disableWorkerEnvironmentInfo - && com.google.common.base.Objects.equal(externalStorage, that.externalStorage); + && com.google.common.base.Objects.equal(externalStorage, that.externalStorage) + && com.google.common.base.Objects.equal(payloadCache, that.payloadCache); } @Override @@ -456,6 +498,7 @@ public int hashCode() { Arrays.hashCode(plugins), workerHeartbeatInterval, disableWorkerEnvironmentInfo, - externalStorage); + externalStorage, + payloadCache); } } diff --git a/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientImpl.java b/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientImpl.java index ab737e7992..96ae215ee9 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientImpl.java @@ -94,7 +94,9 @@ public static ScheduleClient newInstance( options.getExternalStorage() == null ? null : ExternalStorageRunner.create( - options.getExternalStorage(), options.getNamespace())); + options.getExternalStorage(), + options.getNamespace(), + options.getPayloadCache())); } private static ScheduleClientPlugin[] extractScheduleClientPlugins( diff --git a/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientOptions.java b/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientOptions.java index 1dc7d95275..c8f2b225fc 100644 --- a/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientOptions.java +++ b/temporal-sdk/src/main/java/io/temporal/client/schedules/ScheduleClientOptions.java @@ -6,10 +6,12 @@ import io.temporal.common.converter.GlobalDataConverter; import io.temporal.common.interceptors.ScheduleClientInterceptor; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import java.lang.management.ManagementFactory; import java.util.Arrays; import java.util.Collections; import java.util.List; +import javax.annotation.Nonnull; import javax.annotation.Nullable; /** Options for ScheduleClient configuration. */ @@ -52,6 +54,7 @@ public static final class Builder { private List interceptors; private ScheduleClientPlugin[] plugins; private ExternalStorage externalStorage; + private PayloadCache payloadCache; private Builder() {} @@ -66,6 +69,7 @@ private Builder(ScheduleClientOptions options) { interceptors = options.interceptors; plugins = options.plugins; externalStorage = options.externalStorage; + payloadCache = options.payloadCache; } /** Set the namespace this client will operate on. */ @@ -132,6 +136,18 @@ public Builder setExternalStorage(@Nullable ExternalStorage externalStorage) { return this; } + /** + * Cache for payloads that external storage uploads and downloads. Used only when external + * storage is set. Calls made through this client report no cache metrics. + * + *

Pass {@link PayloadCache#disabled()} to turn caching off explicitly. Defaults to off. + */ + @Experimental + public Builder setPayloadCache(@Nullable PayloadCache payloadCache) { + this.payloadCache = payloadCache; + return this; + } + public ScheduleClientOptions build() { String name = identity == null ? ManagementFactory.getRuntimeMXBean().getName() : identity; return new ScheduleClientOptions( @@ -141,7 +157,8 @@ public ScheduleClientOptions build() { contextPropagators == null ? EMPTY_CONTEXT_PROPAGATORS : contextPropagators, interceptors == null ? EMPTY_INTERCEPTORS : interceptors, plugins == null ? EMPTY_PLUGINS : plugins, - externalStorage); + externalStorage, + payloadCache == null ? PayloadCache.disabled() : payloadCache); } } @@ -152,6 +169,7 @@ public ScheduleClientOptions build() { private final List interceptors; private final ScheduleClientPlugin[] plugins; private final @Nullable ExternalStorage externalStorage; + private final @Nonnull PayloadCache payloadCache; private ScheduleClientOptions( String namespace, @@ -160,7 +178,8 @@ private ScheduleClientOptions( List contextPropagators, List interceptors, ScheduleClientPlugin[] plugins, - @Nullable ExternalStorage externalStorage) { + @Nullable ExternalStorage externalStorage, + @Nonnull PayloadCache payloadCache) { this.namespace = namespace; this.dataConverter = dataConverter; this.identity = identity; @@ -168,6 +187,7 @@ private ScheduleClientOptions( this.interceptors = interceptors; this.plugins = plugins; this.externalStorage = externalStorage; + this.payloadCache = payloadCache; } /** @@ -231,4 +251,13 @@ public ScheduleClientPlugin[] getPlugins() { public ExternalStorage getExternalStorage() { return externalStorage; } + + /** + * Cache for external storage payloads, or {@link PayloadCache#disabled()} when caching is off. + */ + @Experimental + @Nonnull + public PayloadCache getPayloadCache() { + return payloadCache; + } } diff --git a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformer.java b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformer.java index d062dda90f..d7da2cfe3b 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformer.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformer.java @@ -5,6 +5,7 @@ import io.temporal.internal.common.ListUtils; import io.temporal.internal.concurrent.structured.TaskScope; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverClaim; import io.temporal.payload.storage.StorageDriverRetrieveContext; @@ -14,10 +15,12 @@ import io.temporal.payload.storage.StorageDriverTargetInfo; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -32,25 +35,41 @@ final class ExternalStoragePayloadTransformer { private final StorageDriverSelector selector; private final int payloadSizeThreshold; private final String namespace; + private final PayloadCache payloadCache; - static ExternalStoragePayloadTransformer fromOptions(ExternalStorage options, String namespace) { + /** + * @param payloadCache cache for stored and retrieved payloads, or {@link PayloadCache#disabled()} + * to turn caching off. + */ + static ExternalStoragePayloadTransformer fromOptions( + ExternalStorage options, String namespace, PayloadCache payloadCache) { Map driversByName = new LinkedHashMap<>(); for (StorageDriver driver : options.getDrivers()) { driversByName.put(driver.getName(), driver); } return new ExternalStoragePayloadTransformer( - driversByName, options.getDriverSelector(), options.getPayloadSizeThreshold(), namespace); + driversByName, + options.getDriverSelector(), + options.getPayloadSizeThreshold(), + namespace, + payloadCache); } private ExternalStoragePayloadTransformer( Map driversByName, StorageDriverSelector selector, int payloadSizeThreshold, - String namespace) { + String namespace, + PayloadCache payloadCache) { this.driversByName = driversByName; this.selector = selector; this.payloadSizeThreshold = payloadSizeThreshold; this.namespace = Objects.requireNonNull(namespace, "namespace"); + this.payloadCache = Objects.requireNonNull(payloadCache, "payloadCache"); + } + + private boolean isCachingEnabled() { + return payloadCache != PayloadCache.disabled(); } CompletableFuture> store( @@ -76,8 +95,12 @@ CompletableFuture> store( if (batches.isEmpty()) { return CompletableFuture.completedFuture(payloads); } - return runStoreDrivers(batches, target, cancellationToken, metrics) - .thenApply(referencePayloads -> applyPayloadReplacements(payloads, referencePayloads)); + String[] cacheKeys = new String[payloads.size()]; + return runStoreDrivers(batches, target, cancellationToken, metrics, cacheKeys) + .thenCompose( + referencePayloads -> + writeToCache(cacheKeys, payloads) + .thenApply(ignored -> applyPayloadReplacements(payloads, referencePayloads))); } private Map> buildStoreBatches( @@ -107,7 +130,8 @@ private CompletableFuture>> runStoreDrivers( Map> batches, @Nullable StorageDriverTargetInfo target, CancellationToken cancellationToken, - @Nullable StorageOperationMetrics metrics) { + @Nullable StorageOperationMetrics metrics, + String[] cacheKeys) { return withDriverScope( cancellationToken, scope -> { @@ -127,7 +151,7 @@ private CompletableFuture>> runStoreDrivers( startNanos, error == null ? batch.size() : 0, error == null ? serializedSizeOf(batch.values()) : 0)); - scope.attach(call).map(claims -> createReferencePayloads(batch, claims)); + scope.attach(call).map(claims -> createReferencePayloads(batch, claims, cacheKeys)); } return scope.awaitAll(ListUtils::flatten); }); @@ -159,8 +183,12 @@ private static CompletableFuture>> withDriverScope( }); } - private static List> createReferencePayloads( - Batch batch, List claims) { + /** + * Also records in {@code cacheKeys}, at each payload's original position, the key to cache that + * payload under when caching is enabled. + */ + private List> createReferencePayloads( + Batch batch, List claims, String[] cacheKeys) { if (claims == null || claims.size() != batch.size()) { throw new IllegalStateException( String.format( @@ -177,6 +205,10 @@ private static List> createReferencePayloads( batch.driver.getName(), batchIndex)); } IndexedValue indexedPayload = batch.get(batchIndex); + if (isCachingEnabled()) { + cacheKeys[indexedPayload.originalIndex] = + PayloadCacheKeys.forClaim(batch.driver.getName(), claim); + } replacements.add( new IndexedValue<>( indexedPayload.originalIndex, @@ -195,21 +227,50 @@ CompletableFuture> retrieve( List payloads, CancellationToken cancellationToken, @Nullable StorageOperationMetrics metrics) { - Map> batches; + List items; try { - batches = buildRetrieveBatches(payloads); + items = parseRetrieveItems(payloads); } catch (RuntimeException e) { return failedFuture(e); } - if (batches.isEmpty()) { + if (items.isEmpty()) { return CompletableFuture.completedFuture(payloads); } - return runRetrieveDrivers(batches, cancellationToken, metrics) - .thenApply(retrievedPayloads -> applyPayloadReplacements(payloads, retrievedPayloads)); + if (!isCachingEnabled()) { + return runRetrieveDrivers(buildRetrieveBatches(items), cancellationToken, metrics) + .thenApply(retrievedPayloads -> applyPayloadReplacements(payloads, retrievedPayloads)); + } + return readFromCache(items) + .thenCompose( + cachedPayloads -> { + List> hits = new ArrayList<>(); + List misses = new ArrayList<>(); + for (int i = 0; i < items.size(); i++) { + RetrieveItem item = items.get(i); + Optional cached = cachedPayloads.get(i); + if (cached.isPresent()) { + hits.add(new IndexedValue<>(item.originalIndex, cached.get())); + } else { + misses.add(item); + } + } + List withHits = applyPayloadReplacements(payloads, hits); + if (misses.isEmpty()) { + return CompletableFuture.completedFuture(withHits); + } + return runRetrieveDrivers(buildRetrieveBatches(misses), cancellationToken, metrics) + .thenCompose( + retrievedPayloads -> + writeToCache(misses, retrievedPayloads) + .thenApply( + ignored -> + applyPayloadReplacements(withHits, retrievedPayloads))); + }); } - private Map> buildRetrieveBatches(List payloads) { - Map> batches = new LinkedHashMap<>(); + /** Parses every reference in {@code payloads}, failing on an unregistered driver name. */ + private List parseRetrieveItems(List payloads) { + List items = new ArrayList<>(); for (int i = 0; i < payloads.size(); i++) { Payload payload = payloads.get(i); ExternalStorageReferences.ParsedReference reference = @@ -222,13 +283,96 @@ private Map> buildRetrieveBatches(List> buildRetrieveBatches( + List items) { + Map> batches = new LinkedHashMap<>(); + for (RetrieveItem item : items) { batches - .computeIfAbsent(reference.driverName, name -> new Batch<>(driver)) - .add(i, reference.claim); + .computeIfAbsent(item.driver.getName(), name -> new Batch<>(item.driver)) + .add(item.originalIndex, item.claim); } return batches; } + /** Completes with one lookup result per item, in order. A failed lookup is a miss. */ + private CompletableFuture>> readFromCache(List items) { + List>> lookups = new ArrayList<>(items.size()); + for (RetrieveItem item : items) { + lookups.add(getFromCache(item.cacheKey)); + } + return CompletableFuture.allOf(lookups.toArray(new CompletableFuture[0])) + .thenApply( + ignored -> { + List> results = new ArrayList<>(lookups.size()); + for (CompletableFuture> lookup : lookups) { + results.add(lookup.join()); + } + return results; + }); + } + + private CompletableFuture writeToCache(String[] cacheKeys, List payloads) { + List> writes = new ArrayList<>(); + for (int i = 0; i < cacheKeys.length; i++) { + if (cacheKeys[i] != null) { + writes.add(setInCache(cacheKeys[i], payloads.get(i))); + } + } + return CompletableFuture.allOf(writes.toArray(new CompletableFuture[0])); + } + + private CompletableFuture writeToCache( + List items, List> retrievedPayloads) { + Map cacheKeysByOriginalIndex = new HashMap<>(); + for (RetrieveItem item : items) { + cacheKeysByOriginalIndex.put(item.originalIndex, item.cacheKey); + } + List> writes = new ArrayList<>(retrievedPayloads.size()); + for (IndexedValue retrieved : retrievedPayloads) { + writes.add( + setInCache(cacheKeysByOriginalIndex.get(retrieved.originalIndex), retrieved.value)); + } + return CompletableFuture.allOf(writes.toArray(new CompletableFuture[0])); + } + + /** Never fails: a cache that throws or fails is treated as a miss. */ + private CompletableFuture> getFromCache(String cacheKey) { + CompletableFuture> lookup; + try { + lookup = payloadCache.get(cacheKey); + } catch (RuntimeException e) { + return CompletableFuture.completedFuture(Optional.empty()); + } + if (lookup == null) { + return CompletableFuture.completedFuture(Optional.empty()); + } + return lookup.handle( + (payload, error) -> error == null && payload != null ? payload : Optional.empty()); + } + + /** Never fails: a cache that throws or fails is ignored. */ + private CompletableFuture setInCache(String cacheKey, Payload payload) { + CompletableFuture write; + try { + write = payloadCache.set(cacheKey, payload); + } catch (RuntimeException e) { + return CompletableFuture.completedFuture(null); + } + if (write == null) { + return CompletableFuture.completedFuture(null); + } + return write.handle((accepted, error) -> null); + } + private CompletableFuture>> runRetrieveDrivers( Map> batches, CancellationToken cancellationToken, @@ -331,6 +475,26 @@ private static final class IndexedValue { } } + private static final class RetrieveItem { + final int originalIndex; + final StorageDriver driver; + final StorageDriverClaim claim; + + /** Null when caching is off. */ + final @Nullable String cacheKey; + + RetrieveItem( + int originalIndex, + StorageDriver driver, + StorageDriverClaim claim, + @Nullable String cacheKey) { + this.originalIndex = originalIndex; + this.driver = driver; + this.claim = claim; + this.cacheKey = cacheKey; + } + } + private static final class Batch { final StorageDriver driver; private final List> indexedValues = new ArrayList<>(); diff --git a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStorageRunner.java b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStorageRunner.java index c0c6f1e3d5..d4b561b590 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStorageRunner.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/ExternalStorageRunner.java @@ -9,6 +9,7 @@ import io.temporal.internal.payload.visitor.PayloadVisitorOptions; import io.temporal.internal.payload.visitor.PayloadVisitors; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverTargetInfo; import java.util.concurrent.CancellationException; @@ -30,10 +31,13 @@ public final class ExternalStorageRunner { /** * @param namespace namespace of the client or worker that will use this runner, exposed to * drivers and selectors on store. + * @param payloadCache cache for stored and retrieved payloads, or {@link PayloadCache#disabled()} + * to turn caching off. */ - public static ExternalStorageRunner create(ExternalStorage options, String namespace) { + public static ExternalStorageRunner create( + ExternalStorage options, String namespace, PayloadCache payloadCache) { return new ExternalStorageRunner( - ExternalStoragePayloadTransformer.fromOptions(options, namespace), + ExternalStoragePayloadTransformer.fromOptions(options, namespace, payloadCache), options.getMaxConcurrentPayloadVisits()); } diff --git a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheKeys.java b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheKeys.java new file mode 100644 index 0000000000..10af98eed2 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheKeys.java @@ -0,0 +1,50 @@ +package io.temporal.internal.payload.storage; + +import com.google.common.primitives.UnsignedBytes; +import io.temporal.payload.storage.StorageDriverClaim; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +/** + * Builds {@link io.temporal.payload.storage.PayloadCache} keys for external storage claims. The + * format is shared by all Temporal SDKs, so it must stay byte-for-byte identical across them. + */ +final class PayloadCacheKeys { + private static final String PREFIX = "v0/temporal/extstore/"; + + private static final Comparator UTF8_BYTE_ORDER = + UnsignedBytes.lexicographicalComparator(); + + /** + * Returns {@code PREFIX + lengthPrefixed(driverName)} followed by {@code lengthPrefixed(key) + + * lengthPrefixed(value)} for each claim entry, ordered by the UTF-8 bytes of the key. {@code + * lengthPrefixed(s)} is the UTF-8 byte length of {@code s}, a colon, and {@code s}. + */ + static String forClaim(String driverName, StorageDriverClaim claim) { + List> claimEntries = new ArrayList<>(claim.getClaimData().entrySet()); + // Other SDKs order by UTF-8 bytes. String.compareTo orders by UTF-16 units, which differs for + // characters outside the Basic Multilingual Plane. + claimEntries.sort( + (left, right) -> UTF8_BYTE_ORDER.compare(utf8(left.getKey()), utf8(right.getKey()))); + StringBuilder key = new StringBuilder(PREFIX); + appendLengthPrefixed(key, driverName); + for (Map.Entry claimEntry : claimEntries) { + appendLengthPrefixed(key, claimEntry.getKey()); + appendLengthPrefixed(key, claimEntry.getValue()); + } + return key.toString(); + } + + private static void appendLengthPrefixed(StringBuilder key, String value) { + key.append(utf8(value).length).append(':').append(value); + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private PayloadCacheKeys() {} +} diff --git a/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheMetrics.java b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheMetrics.java new file mode 100644 index 0000000000..7bdd00dbe8 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/internal/payload/storage/PayloadCacheMetrics.java @@ -0,0 +1,84 @@ +package io.temporal.internal.payload.storage; + +import com.uber.m3.tally.Counter; +import com.uber.m3.tally.Scope; +import com.uber.m3.util.ImmutableMap; +import io.temporal.api.common.v1.Payload; +import io.temporal.payload.storage.PayloadCache; +import io.temporal.worker.MetricsType; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import javax.annotation.Nonnull; + +/** Wraps a {@link PayloadCache} so that its outcomes are recorded as metrics. */ +public final class PayloadCacheMetrics implements PayloadCache { + static final String REJECTION_REASON_TAG = "reason"; + static final String REJECTION_REASON_DECLINED = "declined"; + static final String REJECTION_REASON_ERROR = "error"; + + /** + * Returns {@code cache} wrapped with metrics recorded to {@code scope}, or {@code cache} itself + * when it is {@link PayloadCache#disabled()}. + */ + public static PayloadCache wrap(PayloadCache cache, Scope scope) { + if (cache == PayloadCache.disabled()) { + return cache; + } + return new PayloadCacheMetrics(cache, scope); + } + + private final PayloadCache cache; + private final Counter hit; + private final Counter hitBytes; + private final Counter declined; + private final Counter error; + + private PayloadCacheMetrics(PayloadCache cache, Scope scope) { + this.cache = cache; + this.hit = scope.counter(MetricsType.PAYLOAD_CACHE_LOOKUP_HIT_COUNTER); + this.hitBytes = scope.counter(MetricsType.PAYLOAD_CACHE_LOOKUP_HIT_BYTES_COUNTER); + this.declined = + scope + .tagged(ImmutableMap.of(REJECTION_REASON_TAG, REJECTION_REASON_DECLINED)) + .counter(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER); + this.error = + scope + .tagged(ImmutableMap.of(REJECTION_REASON_TAG, REJECTION_REASON_ERROR)) + .counter(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER); + } + + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return cache + .get(key) + .thenApply( + payload -> { + if (payload.isPresent()) { + hit.inc(1); + hitBytes.inc(payload.get().getSerializedSize()); + } + return payload; + }); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + CompletableFuture result; + try { + result = cache.set(key, payload); + } catch (RuntimeException e) { + error.inc(1); + throw e; + } + return result.whenComplete( + (accepted, failure) -> { + if (failure != null) { + error.inc(1); + } else if (!Boolean.TRUE.equals(accepted)) { + declined.inc(1); + } + }); + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClientImpl.java b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClientImpl.java index 22c7eaffe3..af9b677808 100644 --- a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClientImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalNexusClientImpl.java @@ -1121,6 +1121,7 @@ private TemporalOperationResult startActivityImpl( .setDataConverter(client.getOptions().getDataConverter()) .setIdentity(client.getOptions().getIdentity()) .setExternalStorage(client.getOptions().getExternalStorage()) + .setPayloadCache(client.getOptions().getPayloadCache()) .build()); ActivityClientCallsInterceptor.StartActivityOutput out = ((ActivityClientInternal) activityClient).getInvoker().startActivity(input); diff --git a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperationHandler.java b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperationHandler.java index 4f99468216..f8ff3b1020 100644 --- a/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperationHandler.java +++ b/temporal-sdk/src/main/java/io/temporal/nexus/TemporalOperationHandler.java @@ -180,6 +180,7 @@ protected void cancelActivityExecution(CancelActivityExecutionInput input) { .setDataConverter(wc.getOptions().getDataConverter()) .setIdentity(wc.getOptions().getIdentity()) .setExternalStorage(wc.getOptions().getExternalStorage()) + .setPayloadCache(wc.getOptions().getPayloadCache()) .build()); ac.getHandle(input.getActivityId(), input.getRunId()).cancel(); } diff --git a/temporal-sdk/src/main/java/io/temporal/payload/storage/DisabledPayloadCache.java b/temporal-sdk/src/main/java/io/temporal/payload/storage/DisabledPayloadCache.java new file mode 100644 index 0000000000..1dd28d2226 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/payload/storage/DisabledPayloadCache.java @@ -0,0 +1,30 @@ +package io.temporal.payload.storage; + +import io.temporal.api.common.v1.Payload; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import javax.annotation.Nonnull; + +/** The value returned by {@link PayloadCache#disabled()}. */ +final class DisabledPayloadCache implements PayloadCache { + static final DisabledPayloadCache INSTANCE = new DisabledPayloadCache(); + + private DisabledPayloadCache() {} + + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + return CompletableFuture.completedFuture(false); + } + + @Override + public String toString() { + return "PayloadCache.disabled()"; + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/payload/storage/InMemoryPayloadCache.java b/temporal-sdk/src/main/java/io/temporal/payload/storage/InMemoryPayloadCache.java new file mode 100644 index 0000000000..0bde3af7dd --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/payload/storage/InMemoryPayloadCache.java @@ -0,0 +1,142 @@ +package io.temporal.payload.storage; + +import com.google.common.base.Preconditions; +import com.google.protobuf.InvalidProtocolBufferException; +import io.temporal.api.common.v1.Payload; +import io.temporal.common.Experimental; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import javax.annotation.Nonnull; +import javax.annotation.concurrent.ThreadSafe; + +/** + * In-memory {@link PayloadCache} that evicts the least recently used entries to stay within an + * entry count and a total byte size. An entry's size is the serialized size of its payload. + */ +@Experimental +@ThreadSafe +public final class InMemoryPayloadCache implements PayloadCache { + public static final long DEFAULT_MAX_TOTAL_BYTES = 64L * 1024 * 1024; + public static final int DEFAULT_MAX_ENTRIES = 10_000; + + public static Builder newBuilder() { + return new Builder(); + } + + private final long maxTotalBytes; + private final int maxEntries; + + /** Iterates from least to most recently used. Guarded by {@code this}. */ + private final Map entries = new LinkedHashMap<>(16, 0.75f, true); + + /** Guarded by {@code this}. */ + private long totalBytes; + + /** Creates a cache with the default limits. */ + public InMemoryPayloadCache() { + this(DEFAULT_MAX_TOTAL_BYTES, DEFAULT_MAX_ENTRIES); + } + + private InMemoryPayloadCache(long maxTotalBytes, int maxEntries) { + this.maxTotalBytes = maxTotalBytes; + this.maxEntries = maxEntries; + } + + public long getMaxTotalBytes() { + return maxTotalBytes; + } + + public int getMaxEntries() { + return maxEntries; + } + + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + Entry entry; + synchronized (this) { + entry = entries.get(key); + } + return CompletableFuture.completedFuture( + entry == null ? Optional.empty() : Optional.of(entry.payload)); + } + + /** + * Declines a payload larger than the total byte limit, and every payload when the entry limit is + * zero. Stores a copy of the payload that does not share memory with the caller's payload, so the + * cache never holds a larger buffer the payload was parsed from. + */ + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + int size = payload.getSerializedSize(); + if (size > maxTotalBytes || maxEntries == 0) { + return CompletableFuture.completedFuture(false); + } + Payload copy; + try { + copy = Payload.parseFrom(payload.toByteArray()); + } catch (InvalidProtocolBufferException e) { + CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally(e); + return failed; + } + synchronized (this) { + Entry existing = entries.remove(key); + if (existing != null) { + totalBytes -= existing.size; + } + Iterator leastRecentlyUsed = entries.values().iterator(); + while (leastRecentlyUsed.hasNext() + && (entries.size() >= maxEntries || totalBytes + size > maxTotalBytes)) { + totalBytes -= leastRecentlyUsed.next().size; + leastRecentlyUsed.remove(); + } + entries.put(key, new Entry(copy, size)); + totalBytes += size; + } + return CompletableFuture.completedFuture(true); + } + + private static final class Entry { + final Payload payload; + final int size; + + Entry(Payload payload, int size) { + this.payload = payload; + this.size = size; + } + } + + public static final class Builder { + private long maxTotalBytes = DEFAULT_MAX_TOTAL_BYTES; + private int maxEntries = DEFAULT_MAX_ENTRIES; + + private Builder() {} + + /** + * Total serialized size of all cached payloads, in bytes. Must not be negative. Defaults to 64 + * MiB. + */ + public Builder setMaxTotalBytes(long maxTotalBytes) { + this.maxTotalBytes = maxTotalBytes; + return this; + } + + /** Maximum number of cached payloads. Must not be negative. Defaults to 10,000. */ + public Builder setMaxEntries(int maxEntries) { + this.maxEntries = maxEntries; + return this; + } + + public InMemoryPayloadCache build() { + Preconditions.checkState( + maxTotalBytes >= 0, "maxTotalBytes must be greater than or equal to zero"); + Preconditions.checkState(maxEntries >= 0, "maxEntries must be greater than or equal to zero"); + return new InMemoryPayloadCache(maxTotalBytes, maxEntries); + } + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/payload/storage/PayloadCache.java b/temporal-sdk/src/main/java/io/temporal/payload/storage/PayloadCache.java new file mode 100644 index 0000000000..79181aac29 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/payload/storage/PayloadCache.java @@ -0,0 +1,35 @@ +package io.temporal.payload.storage; + +import io.temporal.api.common.v1.Payload; +import io.temporal.common.Experimental; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import javax.annotation.Nonnull; + +/** + * Cache for payloads that external storage uploads and downloads. Keys are opaque strings. + * + *

Implementations should not throw or complete exceptionally. The SDK treats a failed {@link + * #get} as a miss and ignores a failed {@link #set}. + * + * @see InMemoryPayloadCache + */ +@Experimental +public interface PayloadCache { + /** Completes with the payload stored under {@code key}, or empty on a miss. */ + @Nonnull + CompletableFuture> get(@Nonnull String key); + + /** Completes with whether the cache accepted {@code payload}. */ + @Nonnull + CompletableFuture set(@Nonnull String key, @Nonnull Payload payload); + + /** + * Value that explicitly turns payload caching off. Pass it where a {@code PayloadCache} option is + * accepted. The SDK never calls its methods. + */ + @Nonnull + static PayloadCache disabled() { + return DisabledPayloadCache.INSTANCE; + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/worker/MetricsType.java b/temporal-sdk/src/main/java/io/temporal/worker/MetricsType.java index c9bcc49550..a1d46ab46a 100644 --- a/temporal-sdk/src/main/java/io/temporal/worker/MetricsType.java +++ b/temporal-sdk/src/main/java/io/temporal/worker/MetricsType.java @@ -199,4 +199,22 @@ private MetricsType() {} TEMPORAL_METRICS_PREFIX + "resource_slots_mem_pid_output"; public static final String RESOURCE_CPU_PID = TEMPORAL_METRICS_PREFIX + "resource_slots_cpu_pid_output"; + + // + // Payload cache + // + // Tagged with namespace & task_queue + @Experimental + public static final String PAYLOAD_CACHE_LOOKUP_HIT_COUNTER = + TEMPORAL_METRICS_PREFIX + "payload_cache_lookup_hit"; + + // Tagged with namespace & task_queue + @Experimental + public static final String PAYLOAD_CACHE_LOOKUP_HIT_BYTES_COUNTER = + TEMPORAL_METRICS_PREFIX + "payload_cache_lookup_hit_bytes"; + + // Tagged with namespace, task_queue & reason (declined or error) + @Experimental + public static final String PAYLOAD_CACHE_REJECTION_COUNTER = + TEMPORAL_METRICS_PREFIX + "payload_cache_rejection"; } diff --git a/temporal-sdk/src/main/java/io/temporal/worker/Worker.java b/temporal-sdk/src/main/java/io/temporal/worker/Worker.java index a4ff04ca2d..f7c2416324 100644 --- a/temporal-sdk/src/main/java/io/temporal/worker/Worker.java +++ b/temporal-sdk/src/main/java/io/temporal/worker/Worker.java @@ -26,6 +26,7 @@ import io.temporal.internal.client.WorkflowClientInternal; import io.temporal.internal.logging.PrefixedMdc; import io.temporal.internal.payload.storage.ExternalStorageRunner; +import io.temporal.internal.payload.storage.PayloadCacheMetrics; import io.temporal.internal.sync.WorkflowInternal; import io.temporal.internal.sync.WorkflowThreadExecutor; import io.temporal.internal.worker.*; @@ -135,7 +136,6 @@ private static final class TaskSnapshot { .setDataConverter(clientInternal.getInternalDataConverter()) .build(); this.cache = cache; - ExternalStorageRunner externalStorageRunner = clientInternal.getExternalStorageRunner(); factoryOptions = WorkerFactoryOptions.newBuilder(factoryOptions).validateAndBuildWithDefaults(); String namespace = clientOptions.getNamespace(); this.namespace = namespace; @@ -144,6 +144,13 @@ private static final class TaskSnapshot { Map tags = new ImmutableMap.Builder(1).put(MetricsTag.TASK_QUEUE, taskQueue).build(); Scope taggedScope = metricsScope.tagged(tags); + ExternalStorageRunner externalStorageRunner = + clientOptions.getExternalStorage() == null + ? null + : ExternalStorageRunner.create( + clientOptions.getExternalStorage(), + namespace, + PayloadCacheMetrics.wrap(clientOptions.getPayloadCache(), taggedScope)); // Poller types the user left at their default are auto-enrolled into poller autoscaling at // start() when the namespace advertises the PollerAutoscalingAutoEnroll capability. Eligibility @@ -881,6 +888,8 @@ public String toString() { * This method shouldn't be a part of normal production usage. It's intended for testing and * debugging only. * + *

The replay uses the payload cache of this worker's client, if one is configured. + * * @param history workflow execution history to replay * @throws Exception if replay failed for any reason */ @@ -907,6 +916,8 @@ public void replayWorkflowExecution(io.temporal.internal.common.WorkflowExecutio * This method shouldn't be a part of normal production usage. It's intended for testing and * debugging only. * + *

The replay uses the payload cache of this worker's client, if one is configured. + * * @param history workflow execution history to replay * @throws Exception if replay failed for any reason */ @@ -939,6 +950,8 @@ public void replayWorkflowExecution(WorkflowExecutionHistory history) throws Exc * the workflow implementation type must be registered with this worker. There is no need to call * {@link #start()} to be able to call this method. * + *

The replay uses the payload cache of this worker's client, if one is configured. + * * @param jsonSerializedHistory workflow execution history in JSON format to replay * @throws Exception if replay failed for any reason */ diff --git a/temporal-sdk/src/test/java/io/temporal/client/PayloadCacheClientOptionsTest.java b/temporal-sdk/src/test/java/io/temporal/client/PayloadCacheClientOptionsTest.java new file mode 100644 index 0000000000..48518203bd --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/client/PayloadCacheClientOptionsTest.java @@ -0,0 +1,92 @@ +package io.temporal.client; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; + +import io.temporal.client.schedules.ScheduleClientOptions; +import io.temporal.payload.storage.InMemoryPayloadCache; +import io.temporal.payload.storage.PayloadCache; +import org.junit.Test; + +/** Each client options class resolves its payload cache once and keeps it through copies. */ +public class PayloadCacheClientOptionsTest { + private final PayloadCache cache = new InMemoryPayloadCache(); + + @Test + public void workflowClientOptions() { + assertSame( + PayloadCache.disabled(), WorkflowClientOptions.newBuilder().build().getPayloadCache()); + assertSame( + PayloadCache.disabled(), + WorkflowClientOptions.newBuilder().validateAndBuildWithDefaults().getPayloadCache()); + assertSame( + PayloadCache.disabled(), + WorkflowClientOptions.newBuilder() + .setPayloadCache(PayloadCache.disabled()) + .build() + .getPayloadCache()); + + WorkflowClientOptions withCache = + WorkflowClientOptions.newBuilder().setPayloadCache(cache).build(); + assertSame(cache, withCache.getPayloadCache()); + assertSame(cache, WorkflowClientOptions.newBuilder(withCache).build().getPayloadCache()); + assertSame( + cache, + WorkflowClientOptions.newBuilder(withCache) + .validateAndBuildWithDefaults() + .getPayloadCache()); + assertNotEquals(WorkflowClientOptions.newBuilder().build(), withCache); + } + + @Test + public void activityClientOptions() { + assertSame( + PayloadCache.disabled(), ActivityClientOptions.newBuilder().build().getPayloadCache()); + assertSame( + PayloadCache.disabled(), + ActivityClientOptions.newBuilder() + .setPayloadCache(PayloadCache.disabled()) + .build() + .getPayloadCache()); + + ActivityClientOptions withCache = + ActivityClientOptions.newBuilder().setPayloadCache(cache).build(); + assertSame(cache, withCache.getPayloadCache()); + assertSame(cache, ActivityClientOptions.newBuilder(withCache).build().getPayloadCache()); + assertSame(cache, withCache.toBuilder().build().getPayloadCache()); + assertNotEquals(ActivityClientOptions.newBuilder().build(), withCache); + } + + @Test + public void scheduleClientOptions() { + assertSame( + PayloadCache.disabled(), ScheduleClientOptions.newBuilder().build().getPayloadCache()); + assertSame( + PayloadCache.disabled(), + ScheduleClientOptions.newBuilder() + .setPayloadCache(PayloadCache.disabled()) + .build() + .getPayloadCache()); + + ScheduleClientOptions withCache = + ScheduleClientOptions.newBuilder().setPayloadCache(cache).build(); + assertSame(cache, withCache.getPayloadCache()); + assertSame(cache, ScheduleClientOptions.newBuilder(withCache).build().getPayloadCache()); + assertSame(cache, withCache.toBuilder().build().getPayloadCache()); + } + + @Test + public void nexusClientOptions() { + assertSame(PayloadCache.disabled(), NexusClientOptions.newBuilder().build().getPayloadCache()); + assertSame( + PayloadCache.disabled(), + NexusClientOptions.newBuilder() + .setPayloadCache(PayloadCache.disabled()) + .build() + .getPayloadCache()); + + NexusClientOptions withCache = NexusClientOptions.newBuilder().setPayloadCache(cache).build(); + assertSame(cache, withCache.getPayloadCache()); + assertSame(cache, NexusClientOptions.newBuilder(withCache).build().getPayloadCache()); + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/client/WorkflowExecutionMetadataTest.java b/temporal-sdk/src/test/java/io/temporal/client/WorkflowExecutionMetadataTest.java index 6ca81e7048..57b7131d6e 100644 --- a/temporal-sdk/src/test/java/io/temporal/client/WorkflowExecutionMetadataTest.java +++ b/temporal-sdk/src/test/java/io/temporal/client/WorkflowExecutionMetadataTest.java @@ -12,6 +12,7 @@ import io.temporal.internal.payload.storage.ExternalStorageDataConverter; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverClaim; import io.temporal.payload.storage.StorageDriverRetrieveContext; @@ -34,7 +35,8 @@ public void getMemoResolvesAnExternalStorageReference() { .setPayloadSizeThreshold(0) .build(); DataConverter converter = DefaultDataConverter.newDefaultInstance(); - ExternalStorageRunner storage = ExternalStorageRunner.create(config, "default"); + ExternalStorageRunner storage = + ExternalStorageRunner.create(config, "default", PayloadCache.disabled()); Payloads.Builder value = converter.toPayloads("big-memo").get().toBuilder(); storage.store(value, null, null, CancellationToken.none()); diff --git a/temporal-sdk/src/test/java/io/temporal/internal/activity/HeartbeatContextImplTest.java b/temporal-sdk/src/test/java/io/temporal/internal/activity/HeartbeatContextImplTest.java index 3e0a6493b5..040a93e5e1 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/activity/HeartbeatContextImplTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/activity/HeartbeatContextImplTest.java @@ -32,6 +32,7 @@ import io.temporal.internal.payload.limits.PayloadLimitViolationException; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverActivityInfo; import io.temporal.payload.storage.StorageDriverClaim; @@ -711,7 +712,8 @@ private HeartbeatContextImpl createHeartbeatContextWithStorage(StorageDriver dri ExternalStorageRunner runner = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(100).build(), - "default"); + "default", + PayloadCache.disabled()); return new HeartbeatContextImpl( service, "test-namespace", diff --git a/temporal-sdk/src/test/java/io/temporal/internal/client/ActivityAndScheduleClientExternalStorageTest.java b/temporal-sdk/src/test/java/io/temporal/internal/client/ActivityAndScheduleClientExternalStorageTest.java index 13611ccb0b..ffccddf3a8 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/client/ActivityAndScheduleClientExternalStorageTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/client/ActivityAndScheduleClientExternalStorageTest.java @@ -44,6 +44,7 @@ import io.temporal.internal.payload.storage.ExternalStorageNotConfiguredException; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverActivityInfo; import io.temporal.payload.storage.StorageDriverClaim; @@ -97,7 +98,7 @@ public void activityStartOffloadsInputAndHeaderWithTheActivityAsTarget() { NAMESPACE, "identity", CONVERTER, - ExternalStorageRunner.create(storage(driver), NAMESPACE)) + ExternalStorageRunner.create(storage(driver), NAMESPACE, PayloadCache.disabled())) .startActivity( new StartActivityInput( "MyActivityType", @@ -129,7 +130,8 @@ public void scheduleCreateOffloadsActionPayloadsWithTheScheduledWorkflowAsTarget ArgumentCaptor sent = ArgumentCaptor.forClass(CreateScheduleRequest.class); - scheduleInvoker(rpc, ExternalStorageRunner.create(storage(driver), NAMESPACE)) + scheduleInvoker( + rpc, ExternalStorageRunner.create(storage(driver), NAMESPACE, PayloadCache.disabled())) .createSchedule( new CreateScheduleInput( "sched-1", @@ -170,7 +172,8 @@ public void scheduleCreateOffloadsActionPayloadsWithTheScheduledWorkflowAsTarget @Test public void scheduleDescribeResolvesReferencesWhenStorageIsConfigured() { InMemoryDriver driver = new InMemoryDriver(); - ExternalStorageRunner runner = ExternalStorageRunner.create(storage(driver), NAMESPACE); + ExternalStorageRunner runner = + ExternalStorageRunner.create(storage(driver), NAMESPACE, PayloadCache.disabled()); GenericWorkflowClient rpc = mock(GenericWorkflowClient.class); when(rpc.describeSchedule(any())).thenReturn(describeResponseWithReferences(runner)); @@ -188,7 +191,8 @@ public void scheduleDescribeResolvesReferencesWhenStorageIsConfigured() { @Test public void scheduleDescribeRejectsReferencesWhenStorageIsNotConfigured() { ExternalStorageRunner runner = - ExternalStorageRunner.create(storage(new InMemoryDriver()), NAMESPACE); + ExternalStorageRunner.create( + storage(new InMemoryDriver()), NAMESPACE, PayloadCache.disabled()); GenericWorkflowClient rpc = mock(GenericWorkflowClient.class); when(rpc.describeSchedule(any())).thenReturn(describeResponseWithReferences(runner)); @@ -209,7 +213,8 @@ public void scheduleDescribeRejectsReferencesWhenStorageIsNotConfigured() { @Test public void scheduleUpdateSendsUnchangedPayloadsBackWithoutStoringThemAgain() { InMemoryDriver driver = new InMemoryDriver(); - ExternalStorageRunner runner = ExternalStorageRunner.create(storage(driver), NAMESPACE); + ExternalStorageRunner runner = + ExternalStorageRunner.create(storage(driver), NAMESPACE, PayloadCache.disabled()); Payloads stored = storedActionPayloads(runner); NewWorkflowExecutionInfo sent = @@ -226,7 +231,8 @@ public void scheduleUpdateSendsUnchangedPayloadsBackWithoutStoringThemAgain() { @Test public void scheduleUpdateStoresOnlyThePayloadsThatChanged() { InMemoryDriver driver = new InMemoryDriver(); - ExternalStorageRunner runner = ExternalStorageRunner.create(storage(driver), NAMESPACE); + ExternalStorageRunner runner = + ExternalStorageRunner.create(storage(driver), NAMESPACE, PayloadCache.disabled()); Payloads stored = storedActionPayloads(runner); NewWorkflowExecutionInfo sent = diff --git a/temporal-sdk/src/test/java/io/temporal/internal/client/ClientDataConverterFactoryTest.java b/temporal-sdk/src/test/java/io/temporal/internal/client/ClientDataConverterFactoryTest.java index ab9db6d5cc..81137d7a87 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/client/ClientDataConverterFactoryTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/client/ClientDataConverterFactoryTest.java @@ -12,6 +12,7 @@ import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.internal.payload.storage.TestStorageDriver; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriverWorkflowInfo; import org.junit.Test; @@ -22,7 +23,8 @@ public void offloadsSerializedTransferTypeAndReconstructsModel() { ExternalStorageRunner runner = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); DataConverter converter = ClientDataConverterFactory.forClient(DefaultDataConverter.newDefaultInstance(), runner); @@ -48,7 +50,8 @@ public void scopesWorkflowConverterWithoutChangingConversionOrder() { ExternalStorageRunner runner = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); DataConverter scoped = new ClientDataConverterFactory( "test-namespace", DefaultDataConverter.newDefaultInstance(), runner) @@ -74,7 +77,8 @@ public void unconfiguredWorkflowRejectsReferencesButOtherClientsRemainTransferOn ExternalStorageRunner runner = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); DataConverter configured = DefaultDataConverter.newDefaultInstance(); Payload reference = ClientDataConverterFactory.forClient(configured, runner) diff --git a/temporal-sdk/src/test/java/io/temporal/internal/client/RootWorkflowClientInvokerStorageTargetTest.java b/temporal-sdk/src/test/java/io/temporal/internal/client/RootWorkflowClientInvokerStorageTargetTest.java index 5906d34a8e..27b47d1f4e 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/client/RootWorkflowClientInvokerStorageTargetTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/client/RootWorkflowClientInvokerStorageTargetTest.java @@ -32,6 +32,7 @@ import io.temporal.internal.client.external.GenericWorkflowClient; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverClaim; import io.temporal.payload.storage.StorageDriverRetrieveContext; @@ -268,7 +269,8 @@ private static RootWorkflowClientInvoker invoker( new WorkerFactoryRegistry(), ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - NAMESPACE)); + NAMESPACE, + PayloadCache.disabled())); } private static final class CapturingDriver implements StorageDriver { diff --git a/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientFactoryStorageTargetTest.java b/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientFactoryStorageTargetTest.java index a59ac6267d..3b37593742 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientFactoryStorageTargetTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientFactoryStorageTargetTest.java @@ -14,6 +14,7 @@ import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.context.ActivitySerializationContext; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverActivityInfo; import io.temporal.payload.storage.StorageDriverClaim; @@ -58,7 +59,8 @@ public void setUp() { .setPayloadSizeThreshold(0) .setMaxConcurrentPayloadVisits(1) .build(), - NAMESPACE)); + NAMESPACE, + PayloadCache.disabled())); } @Test diff --git a/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientImplTest.java b/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientImplTest.java index 2fdaca68f4..d52ad3f541 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientImplTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/client/external/ManualActivityCompletionClientImplTest.java @@ -16,6 +16,7 @@ import io.temporal.failure.ApplicationFailure; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverActivityInfo; import io.temporal.payload.storage.StorageDriverClaim; @@ -46,7 +47,8 @@ public void setUp() { .setPayloadSizeThreshold(0) .setMaxConcurrentPayloadVisits(1) .build(), - "default"); + "default", + PayloadCache.disabled()); } @Test diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageDataConverterTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageDataConverterTest.java index 8322ac5c72..dad2b0e605 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageDataConverterTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageDataConverterTest.java @@ -17,6 +17,7 @@ import io.temporal.failure.ApplicationFailure; import io.temporal.payload.codec.PayloadCodec; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverWorkflowInfo; import java.lang.reflect.Type; @@ -203,7 +204,8 @@ private DataConverter resolving(StorageDriver driver, int threshold) { private static ExternalStorageRunner runner(StorageDriver driver, int threshold) { return ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(threshold).build(), - "default"); + "default", + PayloadCache.disabled()); } /** Obscures payload bytes so plaintext reaching a driver is detectable. */ @@ -244,7 +246,8 @@ private Payload storeAndTakeReference(String value) { .setDriver(TestStorageDriver.create()) .setPayloadSizeThreshold(0) .build(), - "default")); + "default", + PayloadCache.disabled())); return configured.toPayload(value).get(); } diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadCacheTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadCacheTest.java new file mode 100644 index 0000000000..3469646cd5 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadCacheTest.java @@ -0,0 +1,243 @@ +package io.temporal.internal.payload.storage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.protobuf.ByteString; +import io.temporal.api.common.v1.Payload; +import io.temporal.common.CancellationToken; +import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.InMemoryPayloadCache; +import io.temporal.payload.storage.PayloadCache; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nonnull; +import org.junit.Test; + +/** Tests how external storage uses a payload cache when storing and retrieving. */ +public class ExternalStoragePayloadCacheTest { + + @Test + public void storeFillsTheCacheSoRetrieveSkipsTheDriver() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + ExternalStoragePayloadTransformer transformer = transformer(driver, new InMemoryPayloadCache()); + List input = Arrays.asList(payload("a"), payload("b")); + + List stored = store(transformer, input); + List retrieved = retrieve(transformer, stored); + + assertEquals(input, retrieved); + assertEquals(0, driver.retrieves.get()); + } + + @Test + public void aMissDownloadsAndFillsTheCache() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + List input = Collections.singletonList(payload("a")); + List stored = store(transformer(driver, PayloadCache.disabled()), input); + ExternalStoragePayloadTransformer cached = transformer(driver, new InMemoryPayloadCache()); + + assertEquals(input, retrieve(cached, stored)); + assertEquals(input, retrieve(cached, stored)); + + assertEquals(1, driver.retrieves.get()); + } + + @Test + public void onlyMissesAreDownloaded() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + PayloadCache cache = new InMemoryPayloadCache(); + List cachedStored = store(transformer(driver, cache), singletonPayload("hit")); + List uncachedStored = + store(transformer(driver, PayloadCache.disabled()), singletonPayload("miss")); + List references = Arrays.asList(cachedStored.get(0), uncachedStored.get(0)); + + List retrieved = retrieve(transformer(driver, cache), references); + + assertEquals(Arrays.asList(payload("hit"), payload("miss")), retrieved); + assertEquals(Collections.singletonList(1), driver.retrieveBatchSizes); + assertEquals(Collections.singletonList("d1-1"), driver.retrievedKeys); + } + + @Test + public void aDisabledCacheIsNeverCalled() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + ExternalStoragePayloadTransformer transformer = transformer(driver, PayloadCache.disabled()); + + List stored = store(transformer, singletonPayload("a")); + retrieve(transformer, stored); + retrieve(transformer, stored); + + assertEquals(2, driver.retrieves.get()); + } + + @Test + public void aCacheThatThrowsNeverFailsTheOperation() throws Exception { + assertCacheFailuresAreIgnored(new ThrowingCache()); + } + + @Test + public void aCacheThatCompletesExceptionallyNeverFailsTheOperation() throws Exception { + assertCacheFailuresAreIgnored(new ExceptionallyCompletingCache()); + } + + @Test + public void aCacheThatReturnsNullFuturesNeverFailsTheOperation() throws Exception { + assertCacheFailuresAreIgnored(new NullReturningCache()); + } + + @Test + public void storeWaitsForTheCacheWriteToComplete() { + TestStorageDriver driver = TestStorageDriver.named("d1"); + PendingWriteCache cache = new PendingWriteCache(); + + CompletableFuture> store = + transformer(driver, cache).store(singletonPayload("a"), null, CancellationToken.none()); + + assertEquals(1, cache.writes.get()); + assertFalse(store.isDone()); + cache.pendingWrite.complete(true); + assertTrue(store.isDone()); + } + + @Test + public void retrieveWaitsForTheCacheWriteToComplete() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + List stored = + store(transformer(driver, PayloadCache.disabled()), singletonPayload("a")); + PendingWriteCache cache = new PendingWriteCache(); + + CompletableFuture> retrieve = + transformer(driver, cache).retrieve(stored, CancellationToken.none()); + + assertEquals(1, cache.writes.get()); + assertFalse(retrieve.isDone()); + cache.pendingWrite.complete(true); + assertEquals(singletonPayload("a"), retrieve.get()); + } + + @Test + public void anUnregisteredDriverFailsEvenWhenThePayloadIsCached() throws Exception { + PayloadCache cache = new InMemoryPayloadCache(); + List stored = + store(transformer(TestStorageDriver.named("d1"), cache), singletonPayload("a")); + + CompletableFuture> retrieve = + transformer(TestStorageDriver.named("other"), cache) + .retrieve(stored, CancellationToken.none()); + + ExecutionException error = assertThrows(ExecutionException.class, retrieve::get); + assertTrue(error.getCause() instanceof IllegalStateException); + } + + private static void assertCacheFailuresAreIgnored(PayloadCache cache) throws Exception { + TestStorageDriver driver = TestStorageDriver.named("d1"); + ExternalStoragePayloadTransformer transformer = transformer(driver, cache); + List input = singletonPayload("a"); + + List stored = store(transformer, input); + + assertEquals(input, retrieve(transformer, stored)); + assertEquals(1, driver.retrieves.get()); + } + + private static ExternalStoragePayloadTransformer transformer( + TestStorageDriver driver, PayloadCache cache) { + return ExternalStoragePayloadTransformer.fromOptions( + ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), + "default", + cache); + } + + private static List store( + ExternalStoragePayloadTransformer transformer, List payloads) throws Exception { + return transformer.store(payloads, null, CancellationToken.none()).get(); + } + + private static List retrieve( + ExternalStoragePayloadTransformer transformer, List payloads) throws Exception { + return transformer.retrieve(payloads, CancellationToken.none()).get(); + } + + private static List singletonPayload(String data) { + return Collections.singletonList(payload(data)); + } + + private static Payload payload(String data) { + return Payload.newBuilder().setData(ByteString.copyFromUtf8(data)).build(); + } + + private static final class ThrowingCache implements PayloadCache { + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + throw new IllegalStateException("cache unavailable"); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + throw new IllegalStateException("cache unavailable"); + } + } + + private static final class ExceptionallyCompletingCache implements PayloadCache { + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return failed(); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + return failed(); + } + + private static CompletableFuture failed() { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(new IllegalStateException("cache unavailable")); + return future; + } + } + + private static final class NullReturningCache implements PayloadCache { + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return null; + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + return null; + } + } + + /** Misses on every lookup and holds every write until {@link #pendingWrite} completes. */ + private static final class PendingWriteCache implements PayloadCache { + final CompletableFuture pendingWrite = new CompletableFuture<>(); + final AtomicInteger writes = new AtomicInteger(); + + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + writes.incrementAndGet(); + return pendingWrite; + } + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformerTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformerTest.java index 7d75ebe2ab..14f0ca8fc5 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformerTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStoragePayloadTransformerTest.java @@ -14,6 +14,7 @@ import io.temporal.common.CancellationToken; import io.temporal.internal.concurrent.structured.CancelSource; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverClaim; import io.temporal.payload.storage.StorageDriverRetrieveContext; @@ -141,7 +142,8 @@ public void selectorReturningNullKeepsInline() throws Exception { .setDriverSelector((context, payload) -> null) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); List stored = transformer @@ -168,7 +170,8 @@ public void multipleDriversBatchPerDriverAndPreserveOrder() throws Exception { .setDriverSelector(selector) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); List input = Arrays.asList(payload("1-a"), payload("2-b"), payload("1-c")); List stored = transformer.store(input, null, CancellationToken.none()).get(); @@ -194,7 +197,8 @@ public void selectorReceivesSelectContextCarryingTheTarget() throws Exception { .setDriverSelector(selector) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); StorageDriverTargetInfo target = new StorageDriverWorkflowInfo("ns", "wf-id", "run-id", "MyWorkflow"); @@ -233,7 +237,8 @@ public CompletableFuture> store( }) .setPayloadSizeThreshold(0) .build(), - "my-namespace"); + "my-namespace", + PayloadCache.disabled()); transformer .store(Collections.singletonList(payload("a")), null, CancellationToken.none()) @@ -333,7 +338,8 @@ public void selectorReturningUnregisteredDriverFails() { .setDriverSelector((context, payload) -> stranger) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); Throwable cause = causeOf( @@ -370,7 +376,8 @@ public CompletableFuture> store( byPrefix.get(payload.getData().toStringUtf8().substring(0, 1))) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); CompletableFuture> result = transformer.store( @@ -455,7 +462,8 @@ public void selectorObservesCallerCancellationToken() { }) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); transformer.store(Collections.singletonList(payload("a")), null, caller.token()); @@ -466,7 +474,8 @@ private static ExternalStoragePayloadTransformer transformer( StorageDriver driver, int threshold) { return ExternalStoragePayloadTransformer.fromOptions( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(threshold).build(), - "default"); + "default", + PayloadCache.disabled()); } private static Payload payload(String data) { diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageRunnerTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageRunnerTest.java index b064b76b50..3461dbf87c 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageRunnerTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/ExternalStorageRunnerTest.java @@ -25,6 +25,7 @@ import io.temporal.internal.concurrent.structured.CancelSource; import io.temporal.internal.payload.visitor.MessageVisitor; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverActivityInfo; import io.temporal.payload.storage.StorageDriverTargetInfo; @@ -281,7 +282,8 @@ private static ExternalStorageRunner transformer(StorageDriver driver, int thres .setDriver(driver) .setPayloadSizeThreshold(threshold) .build(), - "default"); + "default", + PayloadCache.disabled()); return new ExternalStorageRunner(payloadTransformer, 4); } diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheKeysTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheKeysTest.java new file mode 100644 index 0000000000..b7851794fb --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheKeysTest.java @@ -0,0 +1,68 @@ +package io.temporal.internal.payload.storage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import io.temporal.payload.storage.StorageDriverClaim; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.Test; + +public class PayloadCacheKeysTest { + + @Test + public void matchesTheDocumentedCrossSdkExample() { + Map claimData = new LinkedHashMap<>(); + claimData.put("bucket", "abc"); + claimData.put("key", "1"); + + assertEquals( + "v0/temporal/extstore/6:aws-s36:bucket3:abc3:key1:1", + PayloadCacheKeys.forClaim("aws-s3", new StorageDriverClaim(claimData))); + } + + /** + * U+FF61 sorts before U+1F600 by UTF-8 bytes (EF before F0) but after it by UTF-16 units (FF61 + * after D83D). The expected value was produced by the TypeScript SDK. + */ + @Test + public void ordersClaimKeysByUtf8BytesAndPrefixesUtf8Lengths() { + Map claimData = new HashMap<>(); + claimData.put("😀", "z"); + claimData.put("。", "y"); + claimData.put("a", "1"); + claimData.put("é", "x"); + + assertEquals( + "v0/temporal/extstore/2:s31:a1:12:é1:x3:。1:y4:😀1:z", + PayloadCacheKeys.forClaim("s3", new StorageDriverClaim(claimData))); + } + + @Test + public void doesNotDependOnClaimInsertionOrder() { + Map first = new LinkedHashMap<>(); + first.put("bucket", "abc"); + first.put("key", "1"); + Map reordered = new LinkedHashMap<>(); + reordered.put("key", "1"); + reordered.put("bucket", "abc"); + + assertEquals( + PayloadCacheKeys.forClaim("s3", new StorageDriverClaim(first)), + PayloadCacheKeys.forClaim("s3", new StorageDriverClaim(reordered))); + } + + @Test + public void lengthPrefixesKeepDifferentClaimsApart() { + Map joined = new HashMap<>(); + joined.put("a", "1:b1:2"); + Map separate = new HashMap<>(); + separate.put("a", "1"); + separate.put("b", "2"); + + assertNotEquals( + PayloadCacheKeys.forClaim("s3", new StorageDriverClaim(joined)), + PayloadCacheKeys.forClaim("s3", new StorageDriverClaim(separate))); + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheMetricsTest.java b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheMetricsTest.java new file mode 100644 index 0000000000..35eb2454d5 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/payload/storage/PayloadCacheMetricsTest.java @@ -0,0 +1,112 @@ +package io.temporal.internal.payload.storage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.ImmutableMap; +import com.google.protobuf.ByteString; +import com.uber.m3.tally.RootScopeBuilder; +import com.uber.m3.tally.Scope; +import io.temporal.api.common.v1.Payload; +import io.temporal.common.reporter.TestStatsReporter; +import io.temporal.payload.storage.InMemoryPayloadCache; +import io.temporal.payload.storage.PayloadCache; +import io.temporal.serviceclient.MetricsTag; +import io.temporal.worker.MetricsType; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import javax.annotation.Nonnull; +import org.junit.Test; + +public class PayloadCacheMetricsTest { + private static final Map TAGS = + ImmutableMap.of(MetricsTag.NAMESPACE, "ns", MetricsTag.TASK_QUEUE, "tq"); + + private final TestStatsReporter reporter = new TestStatsReporter(); + private final Scope rootScope = + new RootScopeBuilder().reporter(reporter).reportEvery(com.uber.m3.util.Duration.ofMillis(10)); + private final Scope scope = rootScope.tagged(TAGS); + + @Test + public void countsHitsAndHitBytes() throws Exception { + Payload payload = payload("hello"); + PayloadCache cache = PayloadCacheMetrics.wrap(new InMemoryPayloadCache(), scope); + cache.set("k", payload).join(); + + assertEquals(Optional.of(payload), cache.get("k").join()); + assertEquals(Optional.of(payload), cache.get("k").join()); + assertEquals(Optional.empty(), cache.get("missing").join()); + rootScope.close(); + + reporter.assertCounter(MetricsType.PAYLOAD_CACHE_LOOKUP_HIT_COUNTER, TAGS, 2); + reporter.assertCounter( + MetricsType.PAYLOAD_CACHE_LOOKUP_HIT_BYTES_COUNTER, TAGS, 2L * payload.getSerializedSize()); + } + + @Test + public void countsADeclinedWrite() throws Exception { + PayloadCache cache = + PayloadCacheMetrics.wrap(InMemoryPayloadCache.newBuilder().setMaxEntries(0).build(), scope); + + assertFalse(cache.set("k", payload("hello")).join()); + rootScope.close(); + + reporter.assertCounter(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER, withReason("declined"), 1); + reporter.assertNoMetric(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER, withReason("error")); + } + + @Test + public void countsAFailedWriteWithoutHidingTheFailure() throws Exception { + PayloadCache cache = PayloadCacheMetrics.wrap(new FailingCache(), scope); + + assertThrows(CompletionException.class, () -> cache.set("k", payload("hello")).join()); + rootScope.close(); + + reporter.assertCounter(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER, withReason("error"), 1); + } + + @Test + public void countsNothingForAnAcceptedWrite() throws Exception { + PayloadCache cache = PayloadCacheMetrics.wrap(new InMemoryPayloadCache(), scope); + + assertTrue(cache.set("k", payload("hello")).join()); + rootScope.close(); + + reporter.assertNoMetric(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER, withReason("declined")); + reporter.assertNoMetric(MetricsType.PAYLOAD_CACHE_REJECTION_COUNTER, withReason("error")); + } + + @Test + public void leavesADisabledCacheUnwrapped() { + assertSame(PayloadCache.disabled(), PayloadCacheMetrics.wrap(PayloadCache.disabled(), scope)); + } + + private static Map withReason(String reason) { + return ImmutableMap.builder().putAll(TAGS).put("reason", reason).build(); + } + + private static Payload payload(String data) { + return Payload.newBuilder().setData(ByteString.copyFromUtf8(data)).build(); + } + + private static final class FailingCache implements PayloadCache { + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + return CompletableFuture.completedFuture(Optional.empty()); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(new IllegalStateException("cache unavailable")); + return future; + } + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/replay/ReplayWorkflowRunTaskHandlerTaskHandlerTests.java b/temporal-sdk/src/test/java/io/temporal/internal/replay/ReplayWorkflowRunTaskHandlerTaskHandlerTests.java index 0a805f6308..04c08dc0fa 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/replay/ReplayWorkflowRunTaskHandlerTaskHandlerTests.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/replay/ReplayWorkflowRunTaskHandlerTaskHandlerTests.java @@ -37,6 +37,7 @@ import io.temporal.internal.worker.WorkflowRunLockManager; import io.temporal.internal.worker.WorkflowTaskHandler; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.serviceclient.Version; import io.temporal.serviceclient.WorkflowServiceStubs; import io.temporal.testUtils.HistoryUtils; @@ -227,7 +228,8 @@ public void resolvesExternalStorageReferencesInTheWorkflowTaskItself() throws Th ExternalStorageRunner externalStorage = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); PollWorkflowTaskQueueResponse fullTask = HistoryUtils.generateWorkflowTaskWithInitialHistory(); HistoryEvent startedEvent = fullTask.getHistory().getEvents(0); Payload input = Payload.newBuilder().setData(ByteString.copyFromUtf8("input")).build(); @@ -292,7 +294,8 @@ public void aCancelledDownloadIsNotReportedAsAWorkflowTaskFailure() throws Throw ExternalStorageRunner externalStorage = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); PollWorkflowTaskQueueResponse fullTask = HistoryUtils.generateWorkflowTaskWithInitialHistory(); HistoryEvent startedEvent = fullTask.getHistory().getEvents(0); Payload input = Payload.newBuilder().setData(ByteString.copyFromUtf8("input")).build(); @@ -343,7 +346,8 @@ public void aFailedDownloadIsReportedAsAWorkflowTaskFailure() throws Throwable { ExternalStorageRunner externalStorage = ExternalStorageRunner.create( ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build(), - "default"); + "default", + PayloadCache.disabled()); PollWorkflowTaskQueueResponse fullTask = HistoryUtils.generateWorkflowTaskWithInitialHistory(); HistoryEvent startedEvent = fullTask.getHistory().getEvents(0); Payload input = Payload.newBuilder().setData(ByteString.copyFromUtf8("input")).build(); @@ -394,7 +398,8 @@ public void resolvesExternalStorageReferencesInFetchedFullHistory() throws Throw .setDriver(TestStorageDriver.create()) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); PollWorkflowTaskQueueResponse fullTask = HistoryUtils.generateWorkflowTaskWithInitialHistory(); HistoryEvent startedEvent = fullTask.getHistory().getEvents(0); Payload input = Payload.newBuilder().setData(ByteString.copyFromUtf8("input")).build(); diff --git a/temporal-sdk/src/test/java/io/temporal/internal/replay/ServiceWorkflowHistoryIteratorTest.java b/temporal-sdk/src/test/java/io/temporal/internal/replay/ServiceWorkflowHistoryIteratorTest.java index 7af49c4d48..424720c8c4 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/replay/ServiceWorkflowHistoryIteratorTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/replay/ServiceWorkflowHistoryIteratorTest.java @@ -14,6 +14,7 @@ import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.internal.payload.storage.TestStorageDriver; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.testUtils.HistoryUtils; import java.nio.charset.Charset; import java.util.NoSuchElementException; @@ -167,7 +168,8 @@ private static ExternalStorageRunner inMemoryStorage() { .setDriver(TestStorageDriver.create()) .setPayloadSizeThreshold(0) .build(), - "default"); + "default", + PayloadCache.disabled()); } private static History historyWithInput(Payload payload) { diff --git a/temporal-sdk/src/test/java/io/temporal/internal/testing/TestEnvironmentPayloadCacheTest.java b/temporal-sdk/src/test/java/io/temporal/internal/testing/TestEnvironmentPayloadCacheTest.java new file mode 100644 index 0000000000..69a1046090 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/testing/TestEnvironmentPayloadCacheTest.java @@ -0,0 +1,187 @@ +package io.temporal.internal.testing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import io.temporal.activity.Activity; +import io.temporal.activity.ActivityInterface; +import io.temporal.api.common.v1.Payload; +import io.temporal.client.WorkflowClientOptions; +import io.temporal.client.WorkflowOptions; +import io.temporal.common.WorkflowExecutionHistory; +import io.temporal.internal.payload.storage.TestStorageDriver; +import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; +import io.temporal.testing.TestActivityEnvironment; +import io.temporal.testing.TestEnvironmentOptions; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.testing.WorkflowReplayer; +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nonnull; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.Timeout; + +/** + * Test environments use a payload cache set in their client options. The replayer's own environment + * has none. + */ +public class TestEnvironmentPayloadCacheTest { + private static final String TASK_QUEUE = "payload-cache"; + + public @Rule Timeout timeout = Timeout.seconds(30); + + private final TestStorageDriver driver = TestStorageDriver.named("env-cache"); + private final CountingCache cache = new CountingCache(); + + @Test + public void workflowEnvironmentClientsAndWorkersUseTheCache() { + try (TestWorkflowEnvironment testEnvironment = newWorkflowEnvironment()) { + runEchoWorkflow(testEnvironment, "wf-" + UUID.randomUUID()); + + assertTrue("payloads should have been offloaded", driver.stores.get() > 0); + assertTrue(cache.gets.get() > 0); + assertTrue(cache.sets.get() > 0); + } + } + + @Test + public void replayerUsesTheCacheOfThePassedEnvironment() throws Exception { + WorkflowExecutionHistory history; + try (TestWorkflowEnvironment testEnvironment = newWorkflowEnvironment()) { + String workflowId = "wf-" + UUID.randomUUID(); + runEchoWorkflow(testEnvironment, workflowId); + history = testEnvironment.getWorkflowClient().fetchHistory(workflowId); + } + int getsBeforeReplay = cache.gets.get(); + + try (TestWorkflowEnvironment replayEnvironment = newUnstartedWorkflowEnvironment()) { + WorkflowReplayer.replayWorkflowExecution(history, replayEnvironment, EchoWorkflowImpl.class); + } + + assertTrue(cache.gets.get() > getsBeforeReplay); + } + + /** + * {@link WorkflowReplayer} methods that take no environment or Worker replay on {@link + * TestWorkflowEnvironment#newInstance()}. + */ + @Test + public void theReplayersOwnEnvironmentHasNoCache() { + try (TestWorkflowEnvironment testEnvironment = TestWorkflowEnvironment.newInstance()) { + assertSame( + PayloadCache.disabled(), + testEnvironment.getWorkflowClient().getOptions().getPayloadCache()); + } + } + + @Test + public void activityEnvironmentUsesTheCache() { + TestActivityEnvironment testEnvironment = + TestActivityEnvironment.newInstance( + TestEnvironmentOptions.newBuilder() + .setWorkflowClientOptions(clientOptionsWithCache()) + .build()); + try { + testEnvironment.registerActivitiesImplementations(new HeartbeatActivityImpl()); + + assertEquals( + "input", + testEnvironment.newActivityStub(HeartbeatActivity.class).heartbeatAndEcho("input")); + + assertTrue("heartbeat details should have been offloaded", driver.stores.get() > 0); + assertTrue(cache.sets.get() > 0); + } finally { + testEnvironment.close(); + } + } + + private TestWorkflowEnvironment newWorkflowEnvironment() { + TestWorkflowEnvironment testEnvironment = newUnstartedWorkflowEnvironment(); + testEnvironment + .newWorker(TASK_QUEUE) + .registerWorkflowImplementationTypes(EchoWorkflowImpl.class); + testEnvironment.start(); + return testEnvironment; + } + + private TestWorkflowEnvironment newUnstartedWorkflowEnvironment() { + return TestWorkflowEnvironment.newInstance( + TestEnvironmentOptions.newBuilder() + .setWorkflowClientOptions(clientOptionsWithCache()) + .build()); + } + + private WorkflowClientOptions clientOptionsWithCache() { + return WorkflowClientOptions.newBuilder() + .setExternalStorage( + ExternalStorage.newBuilder().setDriver(driver).setPayloadSizeThreshold(0).build()) + .setPayloadCache(cache) + .build(); + } + + private static void runEchoWorkflow(TestWorkflowEnvironment testEnvironment, String workflowId) { + EchoWorkflow workflow = + testEnvironment + .getWorkflowClient() + .newWorkflowStub( + EchoWorkflow.class, + WorkflowOptions.newBuilder() + .setTaskQueue(TASK_QUEUE) + .setWorkflowId(workflowId) + .build()); + assertEquals("echo: hello", workflow.echo("hello")); + } + + @WorkflowInterface + public interface EchoWorkflow { + @WorkflowMethod + String echo(String input); + } + + public static class EchoWorkflowImpl implements EchoWorkflow { + @Override + public String echo(String input) { + return "echo: " + input; + } + } + + @ActivityInterface + public interface HeartbeatActivity { + String heartbeatAndEcho(String input); + } + + public static class HeartbeatActivityImpl implements HeartbeatActivity { + @Override + public String heartbeatAndEcho(String input) { + Activity.getExecutionContext().heartbeat("details"); + return input; + } + } + + /** Misses on every lookup, declines every write, and counts both. */ + private static final class CountingCache implements PayloadCache { + final AtomicInteger gets = new AtomicInteger(); + final AtomicInteger sets = new AtomicInteger(); + + @Nonnull + @Override + public CompletableFuture> get(@Nonnull String key) { + gets.incrementAndGet(); + return CompletableFuture.completedFuture(Optional.empty()); + } + + @Nonnull + @Override + public CompletableFuture set(@Nonnull String key, @Nonnull Payload payload) { + sets.incrementAndGet(); + return CompletableFuture.completedFuture(false); + } + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/worker/NexusWorkerTest.java b/temporal-sdk/src/test/java/io/temporal/internal/worker/NexusWorkerTest.java index 4425b85089..717f3b2223 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/worker/NexusWorkerTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/worker/NexusWorkerTest.java @@ -47,6 +47,7 @@ import io.temporal.internal.payload.limits.PayloadLimitViolationException; import io.temporal.internal.payload.storage.ExternalStorageRunner; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriver; import io.temporal.payload.storage.StorageDriverClaim; import io.temporal.payload.storage.StorageDriverRetrieveContext; @@ -420,7 +421,8 @@ private Fixture( .setDriver(driver) .setPayloadSizeThreshold(0) .build(), - "default")) + "default", + PayloadCache.disabled())) .build(), handler, DefaultDataConverter.newDefaultInstance(), diff --git a/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerPayloadCacheTest.java b/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerPayloadCacheTest.java new file mode 100644 index 0000000000..145c22026a --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerPayloadCacheTest.java @@ -0,0 +1,104 @@ +package io.temporal.internal.worker; + +import com.google.common.collect.ImmutableMap; +import com.uber.m3.tally.RootScopeBuilder; +import com.uber.m3.tally.Scope; +import io.temporal.client.WorkflowClient; +import io.temporal.client.WorkflowClientOptions; +import io.temporal.client.WorkflowOptions; +import io.temporal.common.reporter.TestStatsReporter; +import io.temporal.internal.payload.storage.TestStorageDriver; +import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.InMemoryPayloadCache; +import io.temporal.serviceclient.MetricsTag; +import io.temporal.testing.TestEnvironmentOptions; +import io.temporal.testing.TestWorkflowEnvironment; +import io.temporal.worker.MetricsType; +import io.temporal.worker.WorkerFactory; +import io.temporal.workflow.WorkflowInterface; +import io.temporal.workflow.WorkflowMethod; +import java.util.Map; +import java.util.UUID; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** e2e test of a Worker sharing its client's payload cache. */ +public class WorkflowWorkerPayloadCacheTest { + private static final String TASK_QUEUE = "payload-cache"; + + private final TestStorageDriver driver = TestStorageDriver.named("wf-cache"); + private final TestStatsReporter reporter = new TestStatsReporter(); + private final Scope metricsScope = + new RootScopeBuilder().reporter(reporter).reportEvery(com.uber.m3.util.Duration.ofMillis(10)); + + private TestWorkflowEnvironment testEnvironment; + private WorkflowClient client; + private WorkerFactory workerFactory; + + @Before + public void setUp() { + testEnvironment = + TestWorkflowEnvironment.newInstance( + TestEnvironmentOptions.newBuilder().setMetricsScope(metricsScope).build()); + client = + WorkflowClient.newInstance( + testEnvironment.getWorkflowServiceStubs(), + WorkflowClientOptions.newBuilder() + .setNamespace(testEnvironment.getNamespace()) + .setExternalStorage( + ExternalStorage.newBuilder() + .setDriver(driver) + .setPayloadSizeThreshold(0) + .build()) + .setPayloadCache(new InMemoryPayloadCache()) + .build()); + workerFactory = WorkerFactory.newInstance(client); + workerFactory.newWorker(TASK_QUEUE).registerWorkflowImplementationTypes(EchoWorkflowImpl.class); + workerFactory.start(); + } + + @After + public void tearDown() { + workerFactory.shutdownNow(); + testEnvironment.close(); + } + + @Test + public void workerReadsPayloadsTheClientStoredFromTheSharedCache() throws Exception { + EchoWorkflow workflow = + client.newWorkflowStub( + EchoWorkflow.class, + WorkflowOptions.newBuilder() + .setTaskQueue(TASK_QUEUE) + .setWorkflowId("extstore-cache-" + UUID.randomUUID()) + .build()); + + Assert.assertEquals("echo: hello", workflow.echo("hello")); + Assert.assertTrue("payloads should have been offloaded", driver.stores.get() > 0); + Assert.assertEquals("every retrieve should hit the cache", 0, driver.retrieves.get()); + + metricsScope.close(); + Map workerTags = + ImmutableMap.builder() + .putAll(MetricsTag.defaultTags(testEnvironment.getNamespace())) + .put(MetricsTag.TASK_QUEUE, TASK_QUEUE) + .buildKeepingLast(); + reporter.assertCounter( + MetricsType.PAYLOAD_CACHE_LOOKUP_HIT_COUNTER, workerTags, hits -> hits >= 1); + } + + @WorkflowInterface + public interface EchoWorkflow { + @WorkflowMethod + String echo(String input); + } + + public static class EchoWorkflowImpl implements EchoWorkflow { + @Override + public String echo(String input) { + return "echo: " + input; + } + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerTest.java b/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerTest.java index ec8145815e..7971d31d14 100644 --- a/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerTest.java +++ b/temporal-sdk/src/test/java/io/temporal/internal/worker/WorkflowWorkerTest.java @@ -57,6 +57,7 @@ import io.temporal.internal.replay.ReplayWorkflowFactory; import io.temporal.internal.replay.ReplayWorkflowTaskHandler; import io.temporal.payload.storage.ExternalStorage; +import io.temporal.payload.storage.PayloadCache; import io.temporal.payload.storage.StorageDriverTargetInfo; import io.temporal.payload.storage.StorageDriverWorkflowInfo; import io.temporal.serviceclient.MetricsTag; @@ -1015,7 +1016,8 @@ private void runOneTask( .setDriver(driver) .setPayloadSizeThreshold(0) .build(), - "default")) + "default", + PayloadCache.disabled())) .setStorageCancellation(storageCancellation) .build(), runLockManager, @@ -1127,7 +1129,8 @@ public void aStoreThatFailsWhileShuttingDownIsNotTreatedAsAProblem() throws Exce .setDriver(driver) .setPayloadSizeThreshold(0) .build(), - "default")) + "default", + PayloadCache.disabled())) .setStorageCancellation(storageCancellation.token()) .build(), runLockManager, diff --git a/temporal-sdk/src/test/java/io/temporal/payload/storage/InMemoryPayloadCacheTest.java b/temporal-sdk/src/test/java/io/temporal/payload/storage/InMemoryPayloadCacheTest.java new file mode 100644 index 0000000000..14b28c962b --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/payload/storage/InMemoryPayloadCacheTest.java @@ -0,0 +1,160 @@ +package io.temporal.payload.storage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.protobuf.ByteString; +import io.temporal.api.common.v1.Payload; +import java.util.Optional; +import org.junit.Test; + +public class InMemoryPayloadCacheTest { + + @Test + public void returnsAStoredPayload() { + InMemoryPayloadCache cache = new InMemoryPayloadCache(); + Payload payload = payloadOfSize(100); + + assertTrue(cache.set("k", payload).join()); + + assertEquals(Optional.of(payload), cache.get("k").join()); + } + + @Test + public void returnsEmptyOnAMiss() { + assertEquals(Optional.empty(), new InMemoryPayloadCache().get("missing").join()); + } + + @Test + public void storesACopyOfThePayload() { + InMemoryPayloadCache cache = new InMemoryPayloadCache(); + Payload payload = payloadOfSize(100); + + cache.set("k", payload).join(); + + assertNotSame(payload, cache.get("k").join().get()); + } + + @Test + public void usesDefaultLimits() { + InMemoryPayloadCache cache = new InMemoryPayloadCache(); + + assertEquals(64L * 1024 * 1024, cache.getMaxTotalBytes()); + assertEquals(10_000, cache.getMaxEntries()); + } + + @Test + public void declinesAPayloadLargerThanTheByteLimit() { + Payload payload = payloadOfSize(100); + InMemoryPayloadCache cache = + InMemoryPayloadCache.newBuilder().setMaxTotalBytes(payload.getSerializedSize() - 1).build(); + + assertFalse(cache.set("k", payload).join()); + assertEquals(Optional.empty(), cache.get("k").join()); + } + + @Test + public void acceptsAPayloadExactlyAtTheByteLimit() { + Payload payload = payloadOfSize(100); + InMemoryPayloadCache cache = + InMemoryPayloadCache.newBuilder().setMaxTotalBytes(payload.getSerializedSize()).build(); + + assertTrue(cache.set("k", payload).join()); + } + + @Test + public void declinesEveryPayloadWhenTheEntryLimitIsZero() { + InMemoryPayloadCache cache = InMemoryPayloadCache.newBuilder().setMaxEntries(0).build(); + + assertFalse(cache.set("k", payloadOfSize(1)).join()); + assertEquals(Optional.empty(), cache.get("k").join()); + } + + @Test + public void evictsTheLeastRecentlyUsedEntryToStayUnderTheByteLimit() { + Payload payload = payloadOfSize(100); + InMemoryPayloadCache cache = + InMemoryPayloadCache.newBuilder() + .setMaxTotalBytes(2L * payload.getSerializedSize()) + .build(); + + cache.set("a", payload).join(); + cache.set("b", payload).join(); + cache.set("c", payload).join(); + + assertEquals(Optional.empty(), cache.get("a").join()); + assertTrue(cache.get("b").join().isPresent()); + assertTrue(cache.get("c").join().isPresent()); + } + + @Test + public void evictsTheLeastRecentlyUsedEntryToStayUnderTheEntryLimit() { + InMemoryPayloadCache cache = InMemoryPayloadCache.newBuilder().setMaxEntries(2).build(); + + cache.set("a", payloadOfSize(1)).join(); + cache.set("b", payloadOfSize(1)).join(); + cache.set("c", payloadOfSize(1)).join(); + + assertEquals(Optional.empty(), cache.get("a").join()); + assertTrue(cache.get("b").join().isPresent()); + assertTrue(cache.get("c").join().isPresent()); + } + + @Test + public void getMakesAnEntryMostRecentlyUsed() { + InMemoryPayloadCache cache = InMemoryPayloadCache.newBuilder().setMaxEntries(2).build(); + + cache.set("a", payloadOfSize(1)).join(); + cache.set("b", payloadOfSize(1)).join(); + cache.get("a").join(); + cache.set("c", payloadOfSize(1)).join(); + + assertTrue(cache.get("a").join().isPresent()); + assertEquals(Optional.empty(), cache.get("b").join()); + } + + @Test + public void replacingAnEntryDoesNotCountItsOldSize() { + Payload payload = payloadOfSize(100); + InMemoryPayloadCache cache = + InMemoryPayloadCache.newBuilder() + .setMaxTotalBytes(2L * payload.getSerializedSize()) + .build(); + + cache.set("a", payload).join(); + cache.set("a", payload).join(); + cache.set("b", payload).join(); + + assertTrue(cache.get("a").join().isPresent()); + assertTrue(cache.get("b").join().isPresent()); + } + + @Test + public void boundsEmptyPayloadsByTheEntryLimit() { + InMemoryPayloadCache cache = InMemoryPayloadCache.newBuilder().setMaxEntries(1).build(); + Payload empty = Payload.getDefaultInstance(); + + cache.set("a", empty).join(); + cache.set("b", empty).join(); + + assertEquals(Optional.empty(), cache.get("a").join()); + assertTrue(cache.get("b").join().isPresent()); + } + + @Test + public void rejectsNegativeLimits() { + assertThrows( + IllegalStateException.class, + () -> InMemoryPayloadCache.newBuilder().setMaxTotalBytes(-1).build()); + assertThrows( + IllegalStateException.class, + () -> InMemoryPayloadCache.newBuilder().setMaxEntries(-1).build()); + } + + private static Payload payloadOfSize(int dataBytes) { + return Payload.newBuilder().setData(ByteString.copyFrom(new byte[dataBytes])).build(); + } +} diff --git a/temporal-testing/src/main/java/io/temporal/testing/WorkflowReplayer.java b/temporal-testing/src/main/java/io/temporal/testing/WorkflowReplayer.java index 31d461fd59..0db69f918f 100644 --- a/temporal-testing/src/main/java/io/temporal/testing/WorkflowReplayer.java +++ b/temporal-testing/src/main/java/io/temporal/testing/WorkflowReplayer.java @@ -28,6 +28,8 @@ public static void replayWorkflowExecutionFromResource( /** * Replays workflow from a resource that contains a json serialized history. * + *

The replay uses the payload cache of {@code worker}'s client, if one is configured. + * * @param resourceName name of the resource. * @param worker worker existing worker with the correct task queue and registered * implementations. @@ -147,6 +149,8 @@ public static void replayWorkflowExecution( /** * Replays workflow from a resource that contains a json serialized history. * + *

The replay uses the payload cache of {@code worker}'s client, if one is configured. + * * @param history object that contains the workflow ids and the events. * @param worker existing worker with registered workflow implementations. * @throws Exception if replay failed for any reason. @@ -184,6 +188,8 @@ public static ReplayResults replayWorkflowExecutions( /** * Replays workflows provided by an iterable using an already-initialized worker. * + *

The replay uses the payload cache of {@code worker}'s client, if one is configured. + * * @param histories The histories to be replayed * @param failFast If true, throws upon the first error encountered (if any) during replay. If * false, all histories will be replayed and the returned object contains information about