Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ to docs, or any other relevant information.
- Spring Boot now provides singleton `NexusClient` beans for the root and configured non-root namespaces,
with namespace-specific data converters and `TemporalOptionsCustomizer<NexusClientOptions.Builder>`
customization. `NexusClientInterceptor` beans are automatically registered for the root client.
- **Experimental**: External storage in clients, activity workers, and Nexus workers can now read references that
were encoded with the configured payload codec and marked with `__temporal_external_storage_reference` metadata.
- **Experimental**: External storage in clients and in workflow, activity, and Nexus workers can now read references
that were encoded with the configured payload codec and marked with `__temporal_external_storage_reference` metadata.
- Added experimental Google Cloud Storage external payload storage through the optional
`temporal-payload-storage-gcsdriver` and `temporal-payload-storage-gcsdriver-gcssdk` modules.
Uploads skip objects that already exist and never overwrite them, buckets can be chosen per
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,47 @@ public static <T extends Message> T retrieve(
T message,
@Nullable PayloadCodec codec,
CancellationToken<CancellationException> cancellationToken) {
return retrieve(runner, message, codec, null, cancellationToken, null);
}

/**
* Decodes the references in {@code message} that were encoded with the payload codec, then
* retrieves every reference.
*
* @param codec the codec to decode the payloads of {@code message} with, or null if there is none
* @param codecVisitor chooses the codec for each message from the codec of the message that
* encloses it, or null to decode every payload with {@code codec}
*/
public static <T extends Message> T retrieve(
ExternalStorageRunner runner,
T message,
@Nullable PayloadCodec codec,
@Nullable MessageVisitor<PayloadCodec> codecVisitor,
CancellationToken<CancellationException> cancellationToken,
@Nullable StorageOperationMetrics metrics) {
Message.Builder builder = message.toBuilder();
if (!ExternalStorageRunner.getOrThrowIfCancelled(
ExternalStorageReferenceCodec.decode(builder, codec), cancellationToken)) {
ExternalStorageReferenceCodec.decode(builder, codec, codecVisitor), cancellationToken)) {
return message;
}
@SuppressWarnings("unchecked")
T decoded = (T) builder.build();
return runner.retrieve(decoded, cancellationToken);
return runner.retrieve(decoded, cancellationToken, metrics);
}

/**
* Decodes the references in {@code builder} that were encoded with the payload codec, leaving
* them plain for a later retrieve.
*
* @param codec the codec to decode the payloads of {@code builder} with, or null if there is none
* @return whether {@code builder} holds any reference
*/
public static boolean decodeReferences(
Message.Builder builder,
@Nullable PayloadCodec codec,
CancellationToken<CancellationException> cancellationToken) {
return ExternalStorageRunner.getOrThrowIfCancelled(
ExternalStorageReferenceCodec.decode(builder, codec), cancellationToken);
}

private ExternalStorageOperations() {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.google.protobuf.Message;
import io.temporal.api.common.v1.Payload;
import io.temporal.internal.payload.visitor.MessageVisitor;
import io.temporal.internal.payload.visitor.PayloadVisitorOptions;
import io.temporal.internal.payload.visitor.PayloadVisitors;
import io.temporal.payload.codec.PayloadCodec;
Expand Down Expand Up @@ -31,11 +32,24 @@ final class ExternalStorageReferenceCodec {
* @return whether the message holds any reference to retrieve
*/
static CompletableFuture<Boolean> decode(Message.Builder builder, @Nullable PayloadCodec codec) {
return decode(builder, codec, null);
}

/**
* Like {@link #decode(Message.Builder, PayloadCodec)}, with {@code codecVisitor} choosing the
* codec for each message from the codec of the message that encloses it.
*/
static CompletableFuture<Boolean> decode(
Message.Builder builder,
@Nullable PayloadCodec codec,
@Nullable MessageVisitor<PayloadCodec> codecVisitor) {
AtomicBoolean found = new AtomicBoolean();
PayloadVisitorOptions<Void> options =
PayloadVisitorOptions.<Void>newBuilder(
(context, payloads) ->
CompletableFuture.completedFuture(decode(payloads, codec, found)))
PayloadVisitorOptions<PayloadCodec> options =
PayloadVisitorOptions.<PayloadCodec>newBuilder(
(visitedCodec, payloads) ->
CompletableFuture.completedFuture(decode(payloads, visitedCodec, found)))
.setInitialContext(codec)
.setMessageVisitor(codecVisitor)
.setSkipSearchAttributes(true)
.build();
return PayloadVisitors.visit(builder, options).thenApply(v -> found.get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,8 +418,9 @@ private WorkflowRunTaskHandler createStatefulHandler(
.setNextPageToken(getHistoryResponse.getNextPageToken());
}
// Retrieved once the full history is fetched, so a partial history isn't retrieved and then
// replaced.
WorkflowRunStorage storage = new WorkflowRunStorage(options);
// replaced. A new run replays from the first event, so its storage sees the whole history in
// order.
WorkflowRunStorage storage = new WorkflowRunStorage(namespace, workflowTask, options);
storage.retrieveTask(workflowTask, downloadMetrics);
ReplayWorkflow workflow = workflowFactory.getWorkflow(workflowType, workflowExecution);
return new ReplayWorkflowRunTaskHandler(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
package io.temporal.internal.replay;

import com.google.common.base.Strings;
import io.temporal.api.history.v1.ActivityTaskScheduledEventAttributes;
import io.temporal.api.history.v1.HistoryEventOrBuilder;
import io.temporal.api.history.v1.NexusOperationScheduledEventAttributes;
import io.temporal.api.history.v1.StartChildWorkflowExecutionInitiatedEventAttributes;
import io.temporal.api.history.v1.WorkflowExecutionStartedEventAttributes;
import io.temporal.api.update.v1.Request;
import io.temporal.internal.nexus.PropagatedNexusSerializationContext;
import io.temporal.payload.context.ActivitySerializationContext;
import io.temporal.payload.context.NexusSerializationContext;
import io.temporal.payload.context.SerializationContext;
import io.temporal.payload.context.WorkflowSerializationContext;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.Nullable;

/**
* The serialization contexts that the payloads in one workflow run's history were encoded with,
* which are the contexts the workflow's own code decodes them with.
*
* <p>A result event refers to an event that may have arrived in an earlier workflow task or history
* page, so the contexts of those events are kept for as long as the run is cached. Events must be
* passed to {@link #eventContext} in history order. Not thread-safe: it is used by the thread
* handling the run's workflow task.
*/
final class WorkflowReferenceContexts {
private final String namespace;
private final String workflowId;
private final String workflowType;
private final WorkflowSerializationContext workflowContext;
private final Map<Long, Entry> byEventId = new HashMap<>();
private @Nullable String taskQueue;
private @Nullable NexusSerializationContext propagatedNexusContext;

WorkflowReferenceContexts(String namespace, String workflowId, String workflowType) {
this.namespace = namespace;
this.workflowId = workflowId;
this.workflowType = workflowType;
this.workflowContext = new WorkflowSerializationContext(namespace, workflowId);
}

/** The context of the workflow's input, signals, queries, updates and everything else. */
WorkflowSerializationContext workflowContext() {
return workflowContext;
}

/** The context of a local activity's input, result and failure. */
ActivitySerializationContext localActivityContext(@Nullable String activityType) {
return new ActivitySerializationContext(
namespace, workflowId, workflowType, activityType, taskQueue, true);
}

/**
* The context of a child workflow's header, which is scoped by the child's namespace, unlike the
* child's other payloads.
*/
WorkflowSerializationContext childHeaderContext(String childNamespace, String childWorkflowId) {
return new WorkflowSerializationContext(
Strings.isNullOrEmpty(childNamespace) ? namespace : childNamespace, childWorkflowId);
}

/** Returns the context of {@code event}'s payloads, recording what later events will need. */
SerializationContext eventContext(HistoryEventOrBuilder event) {
switch (event.getAttributesCase()) {
case WORKFLOW_EXECUTION_STARTED_EVENT_ATTRIBUTES:
WorkflowExecutionStartedEventAttributes started =
event.getWorkflowExecutionStartedEventAttributes();
taskQueue = started.getTaskQueue().getName();
propagatedNexusContext =
started.hasPropagatedNexusSerializationContext()
? PropagatedNexusSerializationContext.fromProto(
started.getPropagatedNexusSerializationContext())
: null;
return workflowContext;
case WORKFLOW_EXECUTION_COMPLETED_EVENT_ATTRIBUTES:
case WORKFLOW_EXECUTION_FAILED_EVENT_ATTRIBUTES:
// The result and the failure that closes the workflow go back to the Nexus caller.
return propagatedNexusContext != null ? propagatedNexusContext : workflowContext;
case ACTIVITY_TASK_SCHEDULED_EVENT_ATTRIBUTES:
ActivityTaskScheduledEventAttributes activity =
event.getActivityTaskScheduledEventAttributes();
return record(
event.getEventId(),
new ActivitySerializationContext(
namespace,
workflowId,
workflowType,
activity.getActivityType().getName(),
activity.getTaskQueue().getName(),
false));
case ACTIVITY_TASK_STARTED_EVENT_ATTRIBUTES:
return recorded(event.getActivityTaskStartedEventAttributes().getScheduledEventId());
case ACTIVITY_TASK_COMPLETED_EVENT_ATTRIBUTES:
return finished(
event, event.getActivityTaskCompletedEventAttributes().getScheduledEventId());
case ACTIVITY_TASK_FAILED_EVENT_ATTRIBUTES:
return finished(event, event.getActivityTaskFailedEventAttributes().getScheduledEventId());
case ACTIVITY_TASK_TIMED_OUT_EVENT_ATTRIBUTES:
return finished(
event, event.getActivityTaskTimedOutEventAttributes().getScheduledEventId());
case ACTIVITY_TASK_CANCELED_EVENT_ATTRIBUTES:
return finished(
event, event.getActivityTaskCanceledEventAttributes().getScheduledEventId());
case NEXUS_OPERATION_SCHEDULED_EVENT_ATTRIBUTES:
NexusOperationScheduledEventAttributes nexus =
event.getNexusOperationScheduledEventAttributes();
return record(
event.getEventId(),
new NexusSerializationContext(
nexus.getEndpoint(), nexus.getService(), nexus.getOperation()));
case NEXUS_OPERATION_CANCEL_REQUEST_FAILED_EVENT_ATTRIBUTES:
return recorded(
event.getNexusOperationCancelRequestFailedEventAttributes().getScheduledEventId());
case NEXUS_OPERATION_COMPLETED_EVENT_ATTRIBUTES:
return finished(
event, event.getNexusOperationCompletedEventAttributes().getScheduledEventId());
case NEXUS_OPERATION_FAILED_EVENT_ATTRIBUTES:
return finished(
event, event.getNexusOperationFailedEventAttributes().getScheduledEventId());
case NEXUS_OPERATION_CANCELED_EVENT_ATTRIBUTES:
return finished(
event, event.getNexusOperationCanceledEventAttributes().getScheduledEventId());
case NEXUS_OPERATION_TIMED_OUT_EVENT_ATTRIBUTES:
return finished(
event, event.getNexusOperationTimedOutEventAttributes().getScheduledEventId());
case START_CHILD_WORKFLOW_EXECUTION_INITIATED_EVENT_ATTRIBUTES:
StartChildWorkflowExecutionInitiatedEventAttributes child =
event.getStartChildWorkflowExecutionInitiatedEventAttributes();
return otherWorkflowContext(child.getWorkflowId());
case CHILD_WORKFLOW_EXECUTION_STARTED_EVENT_ATTRIBUTES:
// The header is the only payload.
return childHeaderContext(
event.getChildWorkflowExecutionStartedEventAttributes().getNamespace(),
event
.getChildWorkflowExecutionStartedEventAttributes()
.getWorkflowExecution()
.getWorkflowId());
case CHILD_WORKFLOW_EXECUTION_COMPLETED_EVENT_ATTRIBUTES:
return otherWorkflowContext(
event
.getChildWorkflowExecutionCompletedEventAttributes()
.getWorkflowExecution()
.getWorkflowId());
case CHILD_WORKFLOW_EXECUTION_FAILED_EVENT_ATTRIBUTES:
return otherWorkflowContext(
event
.getChildWorkflowExecutionFailedEventAttributes()
.getWorkflowExecution()
.getWorkflowId());
case CHILD_WORKFLOW_EXECUTION_CANCELED_EVENT_ATTRIBUTES:
return otherWorkflowContext(
event
.getChildWorkflowExecutionCanceledEventAttributes()
.getWorkflowExecution()
.getWorkflowId());
case SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED_EVENT_ATTRIBUTES:
return otherWorkflowContext(
event
.getSignalExternalWorkflowExecutionInitiatedEventAttributes()
.getWorkflowExecution()
.getWorkflowId());
case WORKFLOW_EXECUTION_UPDATE_ACCEPTED_EVENT_ATTRIBUTES:
NexusSerializationContext updateNexusContext =
updateNexusContext(
event.getWorkflowExecutionUpdateAcceptedEventAttributes().getAcceptedRequest());
if (updateNexusContext != null) {
record(event.getEventId(), updateNexusContext);
}
return workflowContext;
case WORKFLOW_EXECUTION_UPDATE_COMPLETED_EVENT_ATTRIBUTES:
return finished(
event, event.getWorkflowExecutionUpdateCompletedEventAttributes().getAcceptedEventId());
case WORKFLOW_EXECUTION_UPDATE_REJECTED_EVENT_ATTRIBUTES:
// The update's request itself is in the workflow context; see WorkflowRunStorage.
NexusSerializationContext rejectedNexusContext =
updateNexusContext(
event.getWorkflowExecutionUpdateRejectedEventAttributes().getRejectedRequest());
return rejectedNexusContext != null ? rejectedNexusContext : workflowContext;
default:
return workflowContext;
}
}

/**
* Forgets the events whose result event is at or before {@code previousStartedEventId}, since a
* later task never repeats the result. A full replay builds a new instance.
*/
void deleteFinished(long previousStartedEventId) {
Iterator<Entry> entries = byEventId.values().iterator();
while (entries.hasNext()) {
Entry entry = entries.next();
if (entry.resultEventId != 0 && entry.resultEventId <= previousStartedEventId) {
entries.remove();
}
}
}

int size() {
return byEventId.size();
}

private WorkflowSerializationContext otherWorkflowContext(String otherWorkflowId) {
// The workflow scopes another workflow's payloads by its own namespace, even across namespaces.
return new WorkflowSerializationContext(namespace, otherWorkflowId);
}

private SerializationContext record(long eventId, SerializationContext context) {
byEventId.put(eventId, new Entry(context));
return context;
}

private SerializationContext recorded(long eventId) {
Entry entry = byEventId.get(eventId);
return entry != null ? entry.context : workflowContext;
}

private SerializationContext finished(HistoryEventOrBuilder resultEvent, long eventId) {
Entry entry = byEventId.get(eventId);
if (entry == null) {
return workflowContext;
}
entry.resultEventId = resultEvent.getEventId();
return entry.context;
}

private static @Nullable NexusSerializationContext updateNexusContext(Request request) {
return request.hasPropagatedNexusSerializationContext()
? PropagatedNexusSerializationContext.fromProto(
request.getPropagatedNexusSerializationContext())
: null;
}

private static final class Entry {
final SerializationContext context;
// The ID of the event that finished the operation once it has been seen, or 0.
long resultEventId;

Entry(SerializationContext context) {
this.context = context;
}
}
}
Loading
Loading