diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b57c1935d..3199f80d52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,9 @@ to docs, or any other relevant information. - Experimental Event Groups associate related workflow commands so their history events can be viewed together. Create a group with `Workflow.newEventGroup` and attach it by calling `addEventGroups` on the command's options. +- Add workflow-side signal-with-start through generated System Nexus APIs, with typed method + references, options builders, and outbound interceptor hooks. Requires a server supporting the + system workflow service. Task queue defaults to the calling workflow's task queue at invocation. ### Changed - Updated Cloud API bindings to v0.27.0, including opt-in user group memberships, projects, diff --git a/temporal-sdk/build.gradle b/temporal-sdk/build.gradle index ed740afb88..d15e2c9e25 100644 --- a/temporal-sdk/build.gradle +++ b/temporal-sdk/build.gradle @@ -47,6 +47,7 @@ dependencies { // we need to compile the code with Java 21 and package it in a multi-release jar. // Similarly, Jackson 3 support requires Java 17+ and is compiled separately. sourceSets { + main.java.srcDir 'src/main/generated' java17 { java { srcDirs = ['src/main/java17'] @@ -338,3 +339,39 @@ tasks.named('check') { dependsOn(testing.suites.jackson3Tests) dependsOn(testing.suites.virtualThreadTests) } + +// Explicit regeneration keeps normal SDK builds independent of the Rust toolchain. +// Use -PnexgenBinary=/path/to/nexgen to test an unreleased generator. +def nexusGeneratedDir = layout.buildDirectory.dir('generated/nexus/workflow').get().asFile +def nexusCheckedInDir = file('src/main/generated/io/temporal/workflow') +def nexgenVersion = '0.2.12' +tasks.register('generateNexusSystemApi', Exec) { + dependsOn ':temporal-serviceclient:generateProto' + def binary = providers.gradleProperty('nexgenBinary').orElse('nexgen') + inputs.dir('src/main/nexus') + inputs.file(project(':temporal-serviceclient').layout.buildDirectory.file('generated/descriptors/temporal-api.desc')) + inputs.property('nexgenVersion', nexgenVersion) + outputs.dir(nexusGeneratedDir) + outputs.upToDateWhen { false } + commandLine binary.get(), 'java', file('src/main/nexus/workflow-service.wit'), + file('src/main/nexus/deps'), '--targets', 'workflow', '--system-nexus', '--format', + '--support-package', 'io.temporal.internal.nexus.system.TemporalModelConverters', + '--package-name', 'io.temporal.workflow', + '--descriptors', project(':temporal-serviceclient').layout.buildDirectory.file('generated/descriptors/temporal-api.desc').get().asFile, + '--output', nexusGeneratedDir + doFirst { + def versionOutput = new ByteArrayOutputStream() + project.exec { invocation -> + invocation.commandLine(binary.get(), '--version') + invocation.standardOutput = versionOutput + } + if (versionOutput.toString('UTF-8').trim() != "nexgen ${nexgenVersion}") { + throw new GradleException("System Nexus regeneration requires nexgen ${nexgenVersion} with the advanced feature.") + } + delete nexusGeneratedDir + } + doLast { project.sync { spec -> spec.from(nexusGeneratedDir); spec.into(nexusCheckedInDir) } } +} +tasks.matching { it.name == 'compileJava' || it.name.startsWith('spotless') }.configureEach { + mustRunAfter 'generateNexusSystemApi' +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowOptions.java b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowOptions.java new file mode 100644 index 0000000000..9871a0d64e --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowOptions.java @@ -0,0 +1,570 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +/** Options for the {@code signalWithStartWorkflow} operation. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +public final class SignalWithStartWorkflowOptions { + private final String workflowId; + private final String taskQueue; + private final java.time.Duration workflowExecutionTimeout; + private final java.time.Duration workflowRunTimeout; + private final java.time.Duration workflowTaskTimeout; + private final io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy; + private final io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy; + private final io.temporal.common.RetryOptions retryOptions; + private final String cronSchedule; + private final java.util.Map memo; + private final io.temporal.common.SearchAttributes typedSearchAttributes; + private final io.temporal.common.Priority priority; + private final io.temporal.common.VersioningOverride versioningOverride; + private final java.time.Duration startDelay; + private final String staticSummary; + private final String staticDetails; + + public static SignalWithStartWorkflowOptions getDefaultInstance() { + return SignalWithStartWorkflowOptions.newBuilder().build(); + } + + private SignalWithStartWorkflowOptions( + String workflowId, + String taskQueue, + java.time.Duration workflowExecutionTimeout, + java.time.Duration workflowRunTimeout, + java.time.Duration workflowTaskTimeout, + io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy, + io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy, + io.temporal.common.RetryOptions retryOptions, + String cronSchedule, + java.util.Map memo, + io.temporal.common.SearchAttributes typedSearchAttributes, + io.temporal.common.Priority priority, + io.temporal.common.VersioningOverride versioningOverride, + java.time.Duration startDelay, + String staticSummary, + String staticDetails) { + this.workflowId = workflowId; + this.taskQueue = taskQueue; + this.workflowExecutionTimeout = workflowExecutionTimeout; + this.workflowRunTimeout = workflowRunTimeout; + this.workflowTaskTimeout = workflowTaskTimeout; + this.workflowIdReusePolicy = workflowIdReusePolicy; + this.workflowIdConflictPolicy = workflowIdConflictPolicy; + this.retryOptions = retryOptions; + this.cronSchedule = cronSchedule; + this.memo = memo; + this.typedSearchAttributes = typedSearchAttributes; + this.priority = priority; + this.versioningOverride = versioningOverride; + this.startDelay = startDelay; + this.staticSummary = staticSummary; + this.staticDetails = staticDetails; + } + + /** + * Workflow ID. Typed calls derive it from the workflow reference when omitted; an explicit ID + * must match. Required for name-based calls. + * + * @return the workflowId + */ + public String getWorkflowId() { + return workflowId; + } + + /** + * Task queue to run the workflow on. Defaults to the calling workflow's task queue. + * + * @return the taskQueue + */ + public String getTaskQueue() { + return taskQueue; + } + + /** + * Total workflow execution timeout, including retries and continue-as-new. Defaults to unlimited. + * + * @return the workflowExecutionTimeout + */ + public java.time.Duration getWorkflowExecutionTimeout() { + return workflowExecutionTimeout; + } + + /** + * Timeout of a single workflow run. Defaults to the workflow execution timeout. + * + * @return the workflowRunTimeout + */ + public java.time.Duration getWorkflowRunTimeout() { + return workflowRunTimeout; + } + + /** + * Timeout of a single workflow task. Defaults to 10 seconds. + * + * @return the workflowTaskTimeout + */ + public java.time.Duration getWorkflowTaskTimeout() { + return workflowTaskTimeout; + } + + /** + * Behavior when a closed workflow with the same ID exists. Default is allow-duplicate. + * + * @return the workflowIdReusePolicy + */ + public io.temporal.api.enums.v1.WorkflowIdReusePolicy getWorkflowIdReusePolicy() { + return workflowIdReusePolicy; + } + + /** + * Behavior when a workflow is currently running with the same ID. Set to use-existing for + * idempotent deduplication on workflow ID. Cannot be set if id-reuse-policy is + * terminate-if-running. Defaults to use-existing. + * + * @return the workflowIdConflictPolicy + */ + public io.temporal.api.enums.v1.WorkflowIdConflictPolicy getWorkflowIdConflictPolicy() { + return workflowIdConflictPolicy; + } + + /** + * Retry policy for the workflow. + * + * @return the retryOptions + */ + public io.temporal.common.RetryOptions getRetryOptions() { + return retryOptions; + } + + /** + * Cron schedule for recurring workflow executions. See https://docs.temporal.io/cron-job. + * + * @return the cronSchedule + */ + public String getCronSchedule() { + return cronSchedule; + } + + /** + * Memo for the workflow. + * + * @return the memo + */ + public java.util.Map getMemo() { + return memo; + } + + /** + * Typed search attributes for the workflow. + * + * @return the typedSearchAttributes + */ + public io.temporal.common.SearchAttributes getTypedSearchAttributes() { + return typedSearchAttributes; + } + + /** + * Priority of the workflow execution. + * + * @return the priority + */ + public io.temporal.common.Priority getPriority() { + return priority; + } + + /** + * Override for workflow versioning behavior. + * + * @return the versioningOverride + */ + public io.temporal.common.VersioningOverride getVersioningOverride() { + return versioningOverride; + } + + /** + * Amount of time to wait before starting the workflow. This does not work with cron-schedule. + * + * @return the startDelay + */ + public java.time.Duration getStartDelay() { + return startDelay; + } + + /** + * Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can be + * in single-line Temporal Markdown format. + * + * @return the staticSummary + */ + public String getStaticSummary() { + return staticSummary; + } + + /** + * General fixed details for the workflow execution that may appear in UI and CLI. This can be in + * Temporal Markdown format and can span multiple lines. This value is fixed on the workflow + * execution and cannot be updated. + * + * @return the staticDetails + */ + public String getStaticDetails() { + return staticDetails; + } + + @Override + public boolean equals(Object value) { + if (this == value) return true; + if (!(value instanceof SignalWithStartWorkflowOptions)) return false; + SignalWithStartWorkflowOptions other = (SignalWithStartWorkflowOptions) value; + return java.util.Objects.deepEquals(this.workflowId, other.workflowId) + && java.util.Objects.deepEquals(this.taskQueue, other.taskQueue) + && java.util.Objects.deepEquals( + this.workflowExecutionTimeout, other.workflowExecutionTimeout) + && java.util.Objects.deepEquals(this.workflowRunTimeout, other.workflowRunTimeout) + && java.util.Objects.deepEquals(this.workflowTaskTimeout, other.workflowTaskTimeout) + && java.util.Objects.deepEquals(this.workflowIdReusePolicy, other.workflowIdReusePolicy) + && java.util.Objects.deepEquals( + this.workflowIdConflictPolicy, other.workflowIdConflictPolicy) + && java.util.Objects.deepEquals(this.retryOptions, other.retryOptions) + && java.util.Objects.deepEquals(this.cronSchedule, other.cronSchedule) + && java.util.Objects.deepEquals(this.memo, other.memo) + && java.util.Objects.deepEquals(this.typedSearchAttributes, other.typedSearchAttributes) + && java.util.Objects.deepEquals(this.priority, other.priority) + && java.util.Objects.deepEquals(this.versioningOverride, other.versioningOverride) + && java.util.Objects.deepEquals(this.startDelay, other.startDelay) + && java.util.Objects.deepEquals(this.staticSummary, other.staticSummary) + && java.util.Objects.deepEquals(this.staticDetails, other.staticDetails); + } + + @Override + public int hashCode() { + return java.util.Arrays.deepHashCode( + new Object[] { + workflowId, + taskQueue, + workflowExecutionTimeout, + workflowRunTimeout, + workflowTaskTimeout, + workflowIdReusePolicy, + workflowIdConflictPolicy, + retryOptions, + cronSchedule, + memo, + typedSearchAttributes, + priority, + versioningOverride, + startDelay, + staticSummary, + staticDetails + }); + } + + @Override + public String toString() { + return "SignalWithStartWorkflowOptions{" + + "workflowId=" + + workflowId + + ", " + + "taskQueue=" + + taskQueue + + ", " + + "workflowExecutionTimeout=" + + workflowExecutionTimeout + + ", " + + "workflowRunTimeout=" + + workflowRunTimeout + + ", " + + "workflowTaskTimeout=" + + workflowTaskTimeout + + ", " + + "workflowIdReusePolicy=" + + workflowIdReusePolicy + + ", " + + "workflowIdConflictPolicy=" + + workflowIdConflictPolicy + + ", " + + "retryOptions=" + + retryOptions + + ", " + + "cronSchedule=" + + cronSchedule + + ", " + + "memo=" + + memo + + ", " + + "typedSearchAttributes=" + + typedSearchAttributes + + ", " + + "priority=" + + priority + + ", " + + "versioningOverride=" + + versioningOverride + + ", " + + "startDelay=" + + startDelay + + ", " + + "staticSummary=" + + staticSummary + + ", " + + "staticDetails=" + + staticDetails + + "}"; + } + + public Builder toBuilder() { + return newBuilder(this); + } + + public static Builder newBuilder(SignalWithStartWorkflowOptions value) { + return new Builder(value); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static final class Builder { + private String workflowId = null; + private String taskQueue = null; + private java.time.Duration workflowExecutionTimeout = null; + private java.time.Duration workflowRunTimeout = null; + private java.time.Duration workflowTaskTimeout = null; + private io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy = null; + private io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy = null; + private io.temporal.common.RetryOptions retryOptions = null; + private String cronSchedule = null; + private java.util.Map memo = null; + private io.temporal.common.SearchAttributes typedSearchAttributes = null; + private io.temporal.common.Priority priority = null; + private io.temporal.common.VersioningOverride versioningOverride = null; + private java.time.Duration startDelay = null; + private String staticSummary = null; + private String staticDetails = null; + + private Builder() {} + + private Builder(SignalWithStartWorkflowOptions value) { + if (value == null) return; + this.workflowId = value.workflowId; + this.taskQueue = value.taskQueue; + this.workflowExecutionTimeout = value.workflowExecutionTimeout; + this.workflowRunTimeout = value.workflowRunTimeout; + this.workflowTaskTimeout = value.workflowTaskTimeout; + this.workflowIdReusePolicy = value.workflowIdReusePolicy; + this.workflowIdConflictPolicy = value.workflowIdConflictPolicy; + this.retryOptions = value.retryOptions; + this.cronSchedule = value.cronSchedule; + this.memo = value.memo; + this.typedSearchAttributes = value.typedSearchAttributes; + this.priority = value.priority; + this.versioningOverride = value.versioningOverride; + this.startDelay = value.startDelay; + this.staticSummary = value.staticSummary; + this.staticDetails = value.staticDetails; + } + + /** + * Workflow ID. Typed calls derive it from the workflow reference when omitted; an explicit ID + * must match. Required for name-based calls. + * + * @param value the workflowId + * @return this builder + */ + public Builder setWorkflowId(String value) { + this.workflowId = value; + return this; + } + + /** + * Task queue to run the workflow on. Defaults to the calling workflow's task queue. + * + * @param value the taskQueue + * @return this builder + */ + public Builder setTaskQueue(String value) { + this.taskQueue = value; + return this; + } + + /** + * Total workflow execution timeout, including retries and continue-as-new. Defaults to + * unlimited. + * + * @param value the workflowExecutionTimeout + * @return this builder + */ + public Builder setWorkflowExecutionTimeout(java.time.Duration value) { + this.workflowExecutionTimeout = value; + return this; + } + + /** + * Timeout of a single workflow run. Defaults to the workflow execution timeout. + * + * @param value the workflowRunTimeout + * @return this builder + */ + public Builder setWorkflowRunTimeout(java.time.Duration value) { + this.workflowRunTimeout = value; + return this; + } + + /** + * Timeout of a single workflow task. Defaults to 10 seconds. + * + * @param value the workflowTaskTimeout + * @return this builder + */ + public Builder setWorkflowTaskTimeout(java.time.Duration value) { + this.workflowTaskTimeout = value; + return this; + } + + /** + * Behavior when a closed workflow with the same ID exists. Default is allow-duplicate. + * + * @param value the workflowIdReusePolicy + * @return this builder + */ + public Builder setWorkflowIdReusePolicy(io.temporal.api.enums.v1.WorkflowIdReusePolicy value) { + this.workflowIdReusePolicy = value; + return this; + } + + /** + * Behavior when a workflow is currently running with the same ID. Set to use-existing for + * idempotent deduplication on workflow ID. Cannot be set if id-reuse-policy is + * terminate-if-running. Defaults to use-existing. + * + * @param value the workflowIdConflictPolicy + * @return this builder + */ + public Builder setWorkflowIdConflictPolicy( + io.temporal.api.enums.v1.WorkflowIdConflictPolicy value) { + this.workflowIdConflictPolicy = value; + return this; + } + + /** + * Retry policy for the workflow. + * + * @param value the retryOptions + * @return this builder + */ + public Builder setRetryOptions(io.temporal.common.RetryOptions value) { + this.retryOptions = value; + return this; + } + + /** + * Cron schedule for recurring workflow executions. See https://docs.temporal.io/cron-job. + * + * @param value the cronSchedule + * @return this builder + */ + public Builder setCronSchedule(String value) { + this.cronSchedule = value; + return this; + } + + /** + * Memo for the workflow. + * + * @param value the memo + * @return this builder + */ + public Builder setMemo(java.util.Map value) { + this.memo = value; + return this; + } + + /** + * Typed search attributes for the workflow. + * + * @param value the typedSearchAttributes + * @return this builder + */ + public Builder setTypedSearchAttributes(io.temporal.common.SearchAttributes value) { + this.typedSearchAttributes = value; + return this; + } + + /** + * Priority of the workflow execution. + * + * @param value the priority + * @return this builder + */ + public Builder setPriority(io.temporal.common.Priority value) { + this.priority = value; + return this; + } + + /** + * Override for workflow versioning behavior. + * + * @param value the versioningOverride + * @return this builder + */ + public Builder setVersioningOverride(io.temporal.common.VersioningOverride value) { + this.versioningOverride = value; + return this; + } + + /** + * Amount of time to wait before starting the workflow. This does not work with cron-schedule. + * + * @param value the startDelay + * @return this builder + */ + public Builder setStartDelay(java.time.Duration value) { + this.startDelay = value; + return this; + } + + /** + * Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can + * be in single-line Temporal Markdown format. + * + * @param value the staticSummary + * @return this builder + */ + public Builder setStaticSummary(String value) { + this.staticSummary = value; + return this; + } + + /** + * General fixed details for the workflow execution that may appear in UI and CLI. This can be + * in Temporal Markdown format and can span multiple lines. This value is fixed on the workflow + * execution and cannot be updated. + * + * @param value the staticDetails + * @return this builder + */ + public Builder setStaticDetails(String value) { + this.staticDetails = value; + return this; + } + + public SignalWithStartWorkflowOptions build() { + return new SignalWithStartWorkflowOptions( + workflowId, + taskQueue, + workflowExecutionTimeout, + workflowRunTimeout, + workflowTaskTimeout, + workflowIdReusePolicy, + workflowIdConflictPolicy, + retryOptions, + cronSchedule, + memo, + typedSearchAttributes, + priority, + versioningOverride, + startDelay, + staticSummary, + staticDetails); + } + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowRequest.java b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowRequest.java new file mode 100644 index 0000000000..40aca1a90d --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowRequest.java @@ -0,0 +1,806 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +/** Request fields for signaling a workflow, starting it first if needed. */ +@io.temporal.common.converter.TransferTypeConvertible( + SignalWithStartWorkflowRequest.Converter.class) +@SuppressWarnings({"unchecked", "rawtypes"}) +public final class SignalWithStartWorkflowRequest { + private final String workflow; + private final java.util.List args; + private final String workflowId; + private final String taskQueue; + private final String signal; + private final java.util.List signalArgs; + private final java.time.Duration workflowExecutionTimeout; + private final java.time.Duration workflowRunTimeout; + private final java.time.Duration workflowTaskTimeout; + private final io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy; + private final io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy; + private final io.temporal.common.RetryOptions retryOptions; + private final String cronSchedule; + private final java.util.Map memo; + private final io.temporal.common.SearchAttributes typedSearchAttributes; + private final io.temporal.common.Priority priority; + private final io.temporal.common.VersioningOverride versioningOverride; + private final java.time.Duration startDelay; + private final io.temporal.workflow.UserMetadata userMetadata; + private final String namespace; + private final java.util.Map headers; + + @com.fasterxml.jackson.annotation.JsonCreator + public SignalWithStartWorkflowRequest( + @com.fasterxml.jackson.annotation.JsonProperty("workflow") String workflow, + @com.fasterxml.jackson.annotation.JsonProperty("args") java.util.List args, + @com.fasterxml.jackson.annotation.JsonProperty("workflowId") String workflowId, + @com.fasterxml.jackson.annotation.JsonProperty("taskQueue") String taskQueue, + @com.fasterxml.jackson.annotation.JsonProperty("signal") String signal, + @com.fasterxml.jackson.annotation.JsonProperty("signalArgs") + java.util.List signalArgs, + @com.fasterxml.jackson.annotation.JsonProperty("workflowExecutionTimeout") + java.time.Duration workflowExecutionTimeout, + @com.fasterxml.jackson.annotation.JsonProperty("workflowRunTimeout") + java.time.Duration workflowRunTimeout, + @com.fasterxml.jackson.annotation.JsonProperty("workflowTaskTimeout") + java.time.Duration workflowTaskTimeout, + @com.fasterxml.jackson.annotation.JsonProperty("workflowIdReusePolicy") + io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy, + @com.fasterxml.jackson.annotation.JsonProperty("workflowIdConflictPolicy") + io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy, + @com.fasterxml.jackson.annotation.JsonProperty("retryOptions") + io.temporal.common.RetryOptions retryOptions, + @com.fasterxml.jackson.annotation.JsonProperty("cronSchedule") String cronSchedule, + @com.fasterxml.jackson.annotation.JsonProperty("memo") java.util.Map memo, + @com.fasterxml.jackson.annotation.JsonProperty("typedSearchAttributes") + io.temporal.common.SearchAttributes typedSearchAttributes, + @com.fasterxml.jackson.annotation.JsonProperty("priority") + io.temporal.common.Priority priority, + @com.fasterxml.jackson.annotation.JsonProperty("versioningOverride") + io.temporal.common.VersioningOverride versioningOverride, + @com.fasterxml.jackson.annotation.JsonProperty("startDelay") java.time.Duration startDelay, + @com.fasterxml.jackson.annotation.JsonProperty("userMetadata") + io.temporal.workflow.UserMetadata userMetadata, + @com.fasterxml.jackson.annotation.JsonProperty("namespace") String namespace, + @com.fasterxml.jackson.annotation.JsonProperty("headers") + java.util.Map headers) { + this.workflow = workflow; + this.args = args; + this.workflowId = workflowId; + this.taskQueue = taskQueue; + this.signal = signal; + this.signalArgs = signalArgs; + this.workflowExecutionTimeout = workflowExecutionTimeout; + this.workflowRunTimeout = workflowRunTimeout; + this.workflowTaskTimeout = workflowTaskTimeout; + this.workflowIdReusePolicy = workflowIdReusePolicy; + this.workflowIdConflictPolicy = workflowIdConflictPolicy; + this.retryOptions = retryOptions; + this.cronSchedule = cronSchedule; + this.memo = memo; + this.typedSearchAttributes = typedSearchAttributes; + this.priority = priority; + this.versioningOverride = versioningOverride; + this.startDelay = startDelay; + this.userMetadata = userMetadata; + this.namespace = namespace; + this.headers = headers; + } + + /** + * @return the workflow + */ + public String getWorkflow() { + return workflow; + } + + /** + * Arguments for the workflow. + * + * @return the args + */ + public java.util.List getArgs() { + return args; + } + + /** + * Workflow ID. Typed calls derive it from the workflow reference when omitted; an explicit ID + * must match. Required for name-based calls. + * + * @return the workflowId + */ + public String getWorkflowId() { + return workflowId; + } + + /** + * Task queue to run the workflow on. Defaults to the calling workflow's task queue. + * + * @return the taskQueue + */ + public String getTaskQueue() { + return taskQueue; + } + + /** + * @return the signal + */ + public String getSignal() { + return signal; + } + + /** + * Arguments for the signal. + * + * @return the signalArgs + */ + public java.util.List getSignalArgs() { + return signalArgs; + } + + /** + * Total workflow execution timeout, including retries and continue-as-new. Defaults to unlimited. + * + * @return the workflowExecutionTimeout + */ + public java.time.Duration getWorkflowExecutionTimeout() { + return workflowExecutionTimeout; + } + + /** + * Timeout of a single workflow run. Defaults to the workflow execution timeout. + * + * @return the workflowRunTimeout + */ + public java.time.Duration getWorkflowRunTimeout() { + return workflowRunTimeout; + } + + /** + * Timeout of a single workflow task. Defaults to 10 seconds. + * + * @return the workflowTaskTimeout + */ + public java.time.Duration getWorkflowTaskTimeout() { + return workflowTaskTimeout; + } + + /** + * Behavior when a closed workflow with the same ID exists. Default is allow-duplicate. + * + * @return the workflowIdReusePolicy + */ + public io.temporal.api.enums.v1.WorkflowIdReusePolicy getWorkflowIdReusePolicy() { + return workflowIdReusePolicy; + } + + /** + * Behavior when a workflow is currently running with the same ID. Set to use-existing for + * idempotent deduplication on workflow ID. Cannot be set if id-reuse-policy is + * terminate-if-running. Defaults to use-existing. + * + * @return the workflowIdConflictPolicy + */ + public io.temporal.api.enums.v1.WorkflowIdConflictPolicy getWorkflowIdConflictPolicy() { + return workflowIdConflictPolicy; + } + + /** + * Retry policy for the workflow. + * + * @return the retryOptions + */ + public io.temporal.common.RetryOptions getRetryOptions() { + return retryOptions; + } + + /** + * Cron schedule for recurring workflow executions. See https://docs.temporal.io/cron-job. + * + * @return the cronSchedule + */ + public String getCronSchedule() { + return cronSchedule; + } + + /** + * Memo for the workflow. + * + * @return the memo + */ + public java.util.Map getMemo() { + return memo; + } + + /** + * Typed search attributes for the workflow. + * + * @return the typedSearchAttributes + */ + public io.temporal.common.SearchAttributes getTypedSearchAttributes() { + return typedSearchAttributes; + } + + /** + * Priority of the workflow execution. + * + * @return the priority + */ + public io.temporal.common.Priority getPriority() { + return priority; + } + + /** + * Override for workflow versioning behavior. + * + * @return the versioningOverride + */ + public io.temporal.common.VersioningOverride getVersioningOverride() { + return versioningOverride; + } + + /** + * Amount of time to wait before starting the workflow. This does not work with cron-schedule. + * + * @return the startDelay + */ + public java.time.Duration getStartDelay() { + return startDelay; + } + + /** + * Static metadata for the workflow execution. + * + * @return the userMetadata + */ + public io.temporal.workflow.UserMetadata getUserMetadata() { + return userMetadata; + } + + /** + * Namespace of the workflow execution. + * + * @return the namespace + */ + public String getNamespace() { + return namespace; + } + + /** + * Headers for the request. + * + * @return the headers + */ + public java.util.Map getHeaders() { + return headers; + } + + public Builder toBuilder() { + return newBuilder(this); + } + + public static Builder newBuilder(SignalWithStartWorkflowRequest value) { + return new Builder(value); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static final class Builder { + private String workflow = null; + private java.util.List args = null; + private String workflowId = ""; + private String taskQueue = null; + private String signal = ""; + private java.util.List signalArgs = null; + private java.time.Duration workflowExecutionTimeout = null; + private java.time.Duration workflowRunTimeout = null; + private java.time.Duration workflowTaskTimeout = null; + private io.temporal.api.enums.v1.WorkflowIdReusePolicy workflowIdReusePolicy = null; + private io.temporal.api.enums.v1.WorkflowIdConflictPolicy workflowIdConflictPolicy = null; + private io.temporal.common.RetryOptions retryOptions = null; + private String cronSchedule = null; + private java.util.Map memo = null; + private io.temporal.common.SearchAttributes typedSearchAttributes = null; + private io.temporal.common.Priority priority = null; + private io.temporal.common.VersioningOverride versioningOverride = null; + private java.time.Duration startDelay = null; + private io.temporal.workflow.UserMetadata userMetadata = null; + private String namespace = ""; + private java.util.Map headers = null; + + private Builder() {} + + private Builder(SignalWithStartWorkflowRequest value) { + if (value == null) return; + this.workflow = value.workflow; + this.args = value.args; + this.workflowId = value.workflowId; + this.taskQueue = value.taskQueue; + this.signal = value.signal; + this.signalArgs = value.signalArgs; + this.workflowExecutionTimeout = value.workflowExecutionTimeout; + this.workflowRunTimeout = value.workflowRunTimeout; + this.workflowTaskTimeout = value.workflowTaskTimeout; + this.workflowIdReusePolicy = value.workflowIdReusePolicy; + this.workflowIdConflictPolicy = value.workflowIdConflictPolicy; + this.retryOptions = value.retryOptions; + this.cronSchedule = value.cronSchedule; + this.memo = value.memo; + this.typedSearchAttributes = value.typedSearchAttributes; + this.priority = value.priority; + this.versioningOverride = value.versioningOverride; + this.startDelay = value.startDelay; + this.userMetadata = value.userMetadata; + this.namespace = value.namespace; + this.headers = value.headers; + } + + /** + * @param value the workflow + * @return this builder + */ + public Builder setWorkflow(String value) { + this.workflow = value; + return this; + } + + /** + * Arguments for the workflow. + * + * @param value the args + * @return this builder + */ + public Builder setArgs(java.util.List value) { + this.args = value; + return this; + } + + /** + * Workflow ID. Typed calls derive it from the workflow reference when omitted; an explicit ID + * must match. Required for name-based calls. + * + * @param value the workflowId + * @return this builder + */ + public Builder setWorkflowId(String value) { + this.workflowId = value; + return this; + } + + /** + * Task queue to run the workflow on. Defaults to the calling workflow's task queue. + * + * @param value the taskQueue + * @return this builder + */ + public Builder setTaskQueue(String value) { + this.taskQueue = value; + return this; + } + + /** + * @param value the signal + * @return this builder + */ + public Builder setSignal(String value) { + this.signal = value; + return this; + } + + /** + * Arguments for the signal. + * + * @param value the signalArgs + * @return this builder + */ + public Builder setSignalArgs(java.util.List value) { + this.signalArgs = value; + return this; + } + + /** + * Total workflow execution timeout, including retries and continue-as-new. Defaults to + * unlimited. + * + * @param value the workflowExecutionTimeout + * @return this builder + */ + public Builder setWorkflowExecutionTimeout(java.time.Duration value) { + this.workflowExecutionTimeout = value; + return this; + } + + /** + * Timeout of a single workflow run. Defaults to the workflow execution timeout. + * + * @param value the workflowRunTimeout + * @return this builder + */ + public Builder setWorkflowRunTimeout(java.time.Duration value) { + this.workflowRunTimeout = value; + return this; + } + + /** + * Timeout of a single workflow task. Defaults to 10 seconds. + * + * @param value the workflowTaskTimeout + * @return this builder + */ + public Builder setWorkflowTaskTimeout(java.time.Duration value) { + this.workflowTaskTimeout = value; + return this; + } + + /** + * Behavior when a closed workflow with the same ID exists. Default is allow-duplicate. + * + * @param value the workflowIdReusePolicy + * @return this builder + */ + public Builder setWorkflowIdReusePolicy(io.temporal.api.enums.v1.WorkflowIdReusePolicy value) { + this.workflowIdReusePolicy = value; + return this; + } + + /** + * Behavior when a workflow is currently running with the same ID. Set to use-existing for + * idempotent deduplication on workflow ID. Cannot be set if id-reuse-policy is + * terminate-if-running. Defaults to use-existing. + * + * @param value the workflowIdConflictPolicy + * @return this builder + */ + public Builder setWorkflowIdConflictPolicy( + io.temporal.api.enums.v1.WorkflowIdConflictPolicy value) { + this.workflowIdConflictPolicy = value; + return this; + } + + /** + * Retry policy for the workflow. + * + * @param value the retryOptions + * @return this builder + */ + public Builder setRetryOptions(io.temporal.common.RetryOptions value) { + this.retryOptions = value; + return this; + } + + /** + * Cron schedule for recurring workflow executions. See https://docs.temporal.io/cron-job. + * + * @param value the cronSchedule + * @return this builder + */ + public Builder setCronSchedule(String value) { + this.cronSchedule = value; + return this; + } + + /** + * Memo for the workflow. + * + * @param value the memo + * @return this builder + */ + public Builder setMemo(java.util.Map value) { + this.memo = value; + return this; + } + + /** + * Typed search attributes for the workflow. + * + * @param value the typedSearchAttributes + * @return this builder + */ + public Builder setTypedSearchAttributes(io.temporal.common.SearchAttributes value) { + this.typedSearchAttributes = value; + return this; + } + + /** + * Priority of the workflow execution. + * + * @param value the priority + * @return this builder + */ + public Builder setPriority(io.temporal.common.Priority value) { + this.priority = value; + return this; + } + + /** + * Override for workflow versioning behavior. + * + * @param value the versioningOverride + * @return this builder + */ + public Builder setVersioningOverride(io.temporal.common.VersioningOverride value) { + this.versioningOverride = value; + return this; + } + + /** + * Amount of time to wait before starting the workflow. This does not work with cron-schedule. + * + * @param value the startDelay + * @return this builder + */ + public Builder setStartDelay(java.time.Duration value) { + this.startDelay = value; + return this; + } + + /** + * Static metadata for the workflow execution. + * + * @param value the userMetadata + * @return this builder + */ + public Builder setUserMetadata(io.temporal.workflow.UserMetadata value) { + this.userMetadata = value; + return this; + } + + /** + * Namespace of the workflow execution. + * + * @param value the namespace + * @return this builder + */ + public Builder setNamespace(String value) { + this.namespace = value; + return this; + } + + /** + * Headers for the request. + * + * @param value the headers + * @return this builder + */ + public Builder setHeaders(java.util.Map value) { + this.headers = value; + return this; + } + + /** + * Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can + * be in single-line Temporal Markdown format. + * + * @param value the staticSummary + * @return this builder + */ + public Builder setStaticSummary(String value) { + this.userMetadata = + io.temporal.workflow.UserMetadata.newBuilder(this.userMetadata) + .setStaticSummary(value) + .build(); + return this; + } + + /** + * General fixed details for the workflow execution that may appear in UI and CLI. This can be + * in Temporal Markdown format and can span multiple lines. This value is fixed on the workflow + * execution and cannot be updated. + * + * @param value the staticDetails + * @return this builder + */ + public Builder setStaticDetails(String value) { + this.userMetadata = + io.temporal.workflow.UserMetadata.newBuilder(this.userMetadata) + .setStaticDetails(value) + .build(); + return this; + } + + public SignalWithStartWorkflowRequest build() { + return new SignalWithStartWorkflowRequest( + workflow, + args, + workflowId, + taskQueue, + signal, + signalArgs, + workflowExecutionTimeout, + workflowRunTimeout, + workflowTaskTimeout, + workflowIdReusePolicy, + workflowIdConflictPolicy, + retryOptions, + cronSchedule, + memo, + typedSearchAttributes, + priority, + versioningOverride, + startDelay, + userMetadata, + namespace, + headers); + } + } + + public io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest toProto( + io.temporal.common.converter.DataConverter converter) { + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest.Builder proto = + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest.newBuilder(); + if (this.workflow != null) + proto.setWorkflowType( + io.temporal.internal.nexus.system.TemporalModelConverters.workflowTypeToProto( + converter, (this.workflow))); + if (this.args != null) + proto.setInput( + converter + .toPayloads((this.args).toArray()) + .orElse(io.temporal.api.common.v1.Payloads.getDefaultInstance())); + if (this.workflowId != null) proto.setWorkflowId((this.workflowId)); + if (this.taskQueue != null) + proto.setTaskQueue( + io.temporal.internal.nexus.system.TemporalModelConverters.taskQueueToProto( + converter, (this.taskQueue))); + if (this.signal != null) proto.setSignalName((this.signal)); + if (this.signalArgs != null) + proto.setSignalInput( + converter + .toPayloads((this.signalArgs).toArray()) + .orElse(io.temporal.api.common.v1.Payloads.getDefaultInstance())); + if (this.workflowExecutionTimeout != null) + proto.setWorkflowExecutionTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationToProto( + converter, (this.workflowExecutionTimeout))); + if (this.workflowRunTimeout != null) + proto.setWorkflowRunTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationToProto( + converter, (this.workflowRunTimeout))); + if (this.workflowTaskTimeout != null) + proto.setWorkflowTaskTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationToProto( + converter, (this.workflowTaskTimeout))); + if (this.workflowIdReusePolicy != null) + proto.setWorkflowIdReusePolicy( + io.temporal.api.enums.v1.WorkflowIdReusePolicy.forNumber( + (this.workflowIdReusePolicy).getNumber())); + if (this.workflowIdConflictPolicy != null) + proto.setWorkflowIdConflictPolicy( + io.temporal.api.enums.v1.WorkflowIdConflictPolicy.forNumber( + (this.workflowIdConflictPolicy).getNumber())); + if (this.retryOptions != null) + proto.setRetryPolicy( + io.temporal.internal.nexus.system.TemporalModelConverters.retryPolicyToProto( + converter, (this.retryOptions))); + if (this.cronSchedule != null) proto.setCronSchedule((this.cronSchedule)); + if (this.memo != null) + proto.setMemo( + io.temporal.internal.nexus.system.TemporalModelConverters.memoToProto( + converter, (this.memo))); + if (this.typedSearchAttributes != null) + proto.setSearchAttributes( + io.temporal.internal.nexus.system.TemporalModelConverters.searchAttributesToProto( + converter, (this.typedSearchAttributes))); + if (this.priority != null) + proto.setPriority( + io.temporal.internal.nexus.system.TemporalModelConverters.priorityToProto( + converter, (this.priority))); + if (this.versioningOverride != null) + proto.setVersioningOverride( + io.temporal.internal.nexus.system.TemporalModelConverters.versioningOverrideToProto( + converter, (this.versioningOverride))); + if (this.startDelay != null) + proto.setWorkflowStartDelay( + io.temporal.internal.nexus.system.TemporalModelConverters.durationToProto( + converter, (this.startDelay))); + if (this.userMetadata != null) proto.setUserMetadata((this.userMetadata).toProto(converter)); + if (this.namespace != null) proto.setNamespace((this.namespace)); + if (this.headers != null) + proto.setHeader( + io.temporal.internal.nexus.system.TemporalModelConverters.headerToProto( + converter, (this.headers))); + return proto.build(); + } + + public static SignalWithStartWorkflowRequest fromProto( + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest proto, + io.temporal.common.converter.DataConverter converter, + java.lang.reflect.Type modelType) { + Builder builder = SignalWithStartWorkflowRequest.newBuilder(); + builder.setWorkflow( + io.temporal.internal.nexus.system.TemporalModelConverters.workflowTypeFromProto( + converter, proto.getWorkflowType())); + if (proto.hasInput()) + builder.setArgs( + io.temporal.internal.nexus.system.TemporalModelConverters.payloadsFromProto( + converter, proto.getInput())); + builder.setWorkflowId(proto.getWorkflowId()); + builder.setTaskQueue( + io.temporal.internal.nexus.system.TemporalModelConverters.taskQueueFromProto( + converter, proto.getTaskQueue())); + builder.setSignal(proto.getSignalName()); + if (proto.hasSignalInput()) + builder.setSignalArgs( + io.temporal.internal.nexus.system.TemporalModelConverters.payloadsFromProto( + converter, proto.getSignalInput())); + if (proto.hasWorkflowExecutionTimeout()) + builder.setWorkflowExecutionTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationFromProto( + converter, proto.getWorkflowExecutionTimeout())); + if (proto.hasWorkflowRunTimeout()) + builder.setWorkflowRunTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationFromProto( + converter, proto.getWorkflowRunTimeout())); + if (proto.hasWorkflowTaskTimeout()) + builder.setWorkflowTaskTimeout( + io.temporal.internal.nexus.system.TemporalModelConverters.durationFromProto( + converter, proto.getWorkflowTaskTimeout())); + builder.setWorkflowIdReusePolicy( + io.temporal.api.enums.v1.WorkflowIdReusePolicy.forNumber( + (proto.getWorkflowIdReusePolicy()).getNumber())); + builder.setWorkflowIdConflictPolicy( + io.temporal.api.enums.v1.WorkflowIdConflictPolicy.forNumber( + (proto.getWorkflowIdConflictPolicy()).getNumber())); + if (proto.hasRetryPolicy()) + builder.setRetryOptions( + io.temporal.internal.nexus.system.TemporalModelConverters.retryPolicyFromProto( + converter, proto.getRetryPolicy())); + builder.setCronSchedule(proto.getCronSchedule()); + if (proto.hasMemo()) + builder.setMemo( + io.temporal.internal.nexus.system.TemporalModelConverters.memoFromProto( + converter, proto.getMemo())); + if (proto.hasSearchAttributes()) + builder.setTypedSearchAttributes( + io.temporal.internal.nexus.system.TemporalModelConverters.searchAttributesFromProto( + converter, proto.getSearchAttributes())); + if (proto.hasPriority()) + builder.setPriority( + io.temporal.internal.nexus.system.TemporalModelConverters.priorityFromProto( + converter, proto.getPriority())); + if (proto.hasVersioningOverride()) + builder.setVersioningOverride( + io.temporal.internal.nexus.system.TemporalModelConverters.versioningOverrideFromProto( + converter, proto.getVersioningOverride())); + if (proto.hasWorkflowStartDelay()) + builder.setStartDelay( + io.temporal.internal.nexus.system.TemporalModelConverters.durationFromProto( + converter, proto.getWorkflowStartDelay())); + if (proto.hasUserMetadata()) + builder.setUserMetadata( + io.temporal.workflow.UserMetadata.fromProto( + proto.getUserMetadata(), converter, io.temporal.workflow.UserMetadata.class)); + builder.setNamespace(proto.getNamespace()); + if (proto.hasHeader()) + builder.setHeaders( + io.temporal.internal.nexus.system.TemporalModelConverters.headerFromProto( + converter, proto.getHeader())); + return builder.build(); + } + + public static final class Converter + implements io.temporal.common.converter.TransferTypeConverter< + SignalWithStartWorkflowRequest> { + public java.lang.reflect.Type getTransferType(java.lang.reflect.Type valueType) { + return io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest.class; + } + + public Object toTransferType(SignalWithStartWorkflowRequest value) { + return value == null + ? null + : value.toProto( + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter()); + } + + public SignalWithStartWorkflowRequest fromTransferType( + Object value, java.lang.reflect.Type valueType) { + return value == null + ? null + : fromProto( + (io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest) value, + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter(), + valueType); + } + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowResponse.java b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowResponse.java new file mode 100644 index 0000000000..037146bf81 --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/SignalWithStartWorkflowResponse.java @@ -0,0 +1,132 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +/** Result of signaling a workflow and starting it if needed. */ +@io.temporal.common.converter.TransferTypeConvertible( + SignalWithStartWorkflowResponse.Converter.class) +@SuppressWarnings({"unchecked", "rawtypes"}) +public final class SignalWithStartWorkflowResponse { + private final String runId; + private final Boolean started; + + @com.fasterxml.jackson.annotation.JsonCreator + public SignalWithStartWorkflowResponse( + @com.fasterxml.jackson.annotation.JsonProperty("runId") String runId, + @com.fasterxml.jackson.annotation.JsonProperty("started") Boolean started) { + this.runId = runId; + this.started = started; + } + + /** + * Run ID of the signaled workflow. + * + * @return the runId + */ + public String getRunId() { + return runId; + } + + /** + * Whether the workflow was started. + * + * @return the started + */ + public Boolean getStarted() { + return started; + } + + public Builder toBuilder() { + return newBuilder(this); + } + + public static Builder newBuilder(SignalWithStartWorkflowResponse value) { + return new Builder(value); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static final class Builder { + private String runId = ""; + private Boolean started = false; + + private Builder() {} + + private Builder(SignalWithStartWorkflowResponse value) { + if (value == null) return; + this.runId = value.runId; + this.started = value.started; + } + + /** + * Run ID of the signaled workflow. + * + * @param value the runId + * @return this builder + */ + public Builder setRunId(String value) { + this.runId = value; + return this; + } + + /** + * Whether the workflow was started. + * + * @param value the started + * @return this builder + */ + public Builder setStarted(Boolean value) { + this.started = value; + return this; + } + + public SignalWithStartWorkflowResponse build() { + return new SignalWithStartWorkflowResponse(runId, started); + } + } + + public io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse toProto( + io.temporal.common.converter.DataConverter converter) { + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse.Builder proto = + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse.newBuilder(); + if (this.runId != null) proto.setRunId((this.runId)); + if (this.started != null) proto.setStarted((this.started)); + return proto.build(); + } + + public static SignalWithStartWorkflowResponse fromProto( + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse proto, + io.temporal.common.converter.DataConverter converter, + java.lang.reflect.Type modelType) { + Builder builder = SignalWithStartWorkflowResponse.newBuilder(); + builder.setRunId(proto.getRunId()); + builder.setStarted(proto.getStarted()); + return builder.build(); + } + + public static final class Converter + implements io.temporal.common.converter.TransferTypeConverter< + SignalWithStartWorkflowResponse> { + public java.lang.reflect.Type getTransferType(java.lang.reflect.Type valueType) { + return io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse.class; + } + + public Object toTransferType(SignalWithStartWorkflowResponse value) { + return value == null + ? null + : value.toProto( + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter()); + } + + public SignalWithStartWorkflowResponse fromTransferType( + Object value, java.lang.reflect.Type valueType) { + return value == null + ? null + : fromProto( + (io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse) value, + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter(), + valueType); + } + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/SystemNexusWorkflowOutboundInterceptor.java b/temporal-sdk/src/main/generated/io/temporal/workflow/SystemNexusWorkflowOutboundInterceptor.java new file mode 100644 index 0000000000..330ae90e6c --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/SystemNexusWorkflowOutboundInterceptor.java @@ -0,0 +1,83 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +/** Generated typed system Nexus hooks, separate from ordinary Nexus interception. */ +public interface SystemNexusWorkflowOutboundInterceptor { + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor.ExecuteNexusOperationOutput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + executeSignalWithStartWorkflow( + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + input); + + /** Forwards each typed hook to the next interceptor without entering ordinary Nexus hooks. */ + abstract class Base implements SystemNexusWorkflowOutboundInterceptor { + protected abstract SystemNexusWorkflowOutboundInterceptor nextSystemNexusInterceptor(); + + @Override + public io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationOutput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + executeSignalWithStartWorkflow( + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + input) { + return nextSystemNexusInterceptor().executeSignalWithStartWorkflow(input); + } + } + + /** Executes typed hooks through the terminal transport, never through the interceptor chain. */ + @SuppressWarnings({"unchecked", "rawtypes"}) + abstract class Terminal implements SystemNexusWorkflowOutboundInterceptor { + protected abstract + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationOutput< + R> + executeSystemNexusOperation( + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput< + R> + input); + + /** Merges workflow context into wire-ready headers using SDK-owned codec policy. */ + protected abstract java.util.Map + propagateSystemNexusHeaders( + java.util.Map headers, + io.temporal.payload.context.SerializationContext context); + + @Override + public io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationOutput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + executeSignalWithStartWorkflow( + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput< + io.temporal.workflow.SignalWithStartWorkflowResponse> + input) { + io.temporal.workflow.SignalWithStartWorkflowRequest request = + (io.temporal.workflow.SignalWithStartWorkflowRequest) input.getArg(); + request = + request.toBuilder() + .setHeaders( + propagateSystemNexusHeaders( + request.getHeaders(), + io.temporal.workflow.internal.SystemNexusOperations.serializationContext( + input.getService(), input.getOperation(), request))) + .build(); + input = + new io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput<>( + input.getEndpoint(), + input.getService(), + input.getOperation(), + input.getResultClass(), + input.getResultType(), + request, + input.getOptions(), + input.getHeaders()); + return executeSystemNexusOperation(input); + } + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/UserMetadata.java b/temporal-sdk/src/main/generated/io/temporal/workflow/UserMetadata.java new file mode 100644 index 0000000000..1f8f0497b7 --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/UserMetadata.java @@ -0,0 +1,141 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +/** Static metadata for a workflow execution. */ +@io.temporal.common.converter.TransferTypeConvertible(UserMetadata.Converter.class) +@SuppressWarnings({"unchecked", "rawtypes"}) +public final class UserMetadata { + private final Object staticSummary; + private final Object staticDetails; + + @com.fasterxml.jackson.annotation.JsonCreator + public UserMetadata( + @com.fasterxml.jackson.annotation.JsonProperty("staticSummary") Object staticSummary, + @com.fasterxml.jackson.annotation.JsonProperty("staticDetails") Object staticDetails) { + this.staticSummary = staticSummary; + this.staticDetails = staticDetails; + } + + /** + * Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can be + * in single-line Temporal Markdown format. + * + * @return the staticSummary + */ + public Object getStaticSummary() { + return staticSummary; + } + + /** + * General fixed details for the workflow execution that may appear in UI and CLI. This can be in + * Temporal Markdown format and can span multiple lines. This value is fixed on the workflow + * execution and cannot be updated. + * + * @return the staticDetails + */ + public Object getStaticDetails() { + return staticDetails; + } + + public Builder toBuilder() { + return newBuilder(this); + } + + public static Builder newBuilder(UserMetadata value) { + return new Builder(value); + } + + public static Builder newBuilder() { + return new Builder(); + } + + public static final class Builder { + private Object staticSummary = null; + private Object staticDetails = null; + + private Builder() {} + + private Builder(UserMetadata value) { + if (value == null) return; + this.staticSummary = value.staticSummary; + this.staticDetails = value.staticDetails; + } + + /** + * Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can + * be in single-line Temporal Markdown format. + * + * @param value the staticSummary + * @return this builder + */ + public Builder setStaticSummary(Object value) { + this.staticSummary = value; + return this; + } + + /** + * General fixed details for the workflow execution that may appear in UI and CLI. This can be + * in Temporal Markdown format and can span multiple lines. This value is fixed on the workflow + * execution and cannot be updated. + * + * @param value the staticDetails + * @return this builder + */ + public Builder setStaticDetails(Object value) { + this.staticDetails = value; + return this; + } + + public UserMetadata build() { + return new UserMetadata(staticSummary, staticDetails); + } + } + + public io.temporal.api.sdk.v1.UserMetadata toProto( + io.temporal.common.converter.DataConverter converter) { + io.temporal.api.sdk.v1.UserMetadata.Builder proto = + io.temporal.api.sdk.v1.UserMetadata.newBuilder(); + if (this.staticSummary != null) + proto.setSummary(converter.toPayload((this.staticSummary)).get()); + if (this.staticDetails != null) + proto.setDetails(converter.toPayload((this.staticDetails)).get()); + return proto.build(); + } + + public static UserMetadata fromProto( + io.temporal.api.sdk.v1.UserMetadata proto, + io.temporal.common.converter.DataConverter converter, + java.lang.reflect.Type modelType) { + Builder builder = UserMetadata.newBuilder(); + if (proto.hasSummary()) + builder.setStaticSummary( + (Object) converter.fromPayload(proto.getSummary(), Object.class, Object.class)); + if (proto.hasDetails()) + builder.setStaticDetails( + (Object) converter.fromPayload(proto.getDetails(), Object.class, Object.class)); + return builder.build(); + } + + public static final class Converter + implements io.temporal.common.converter.TransferTypeConverter { + public java.lang.reflect.Type getTransferType(java.lang.reflect.Type valueType) { + return io.temporal.api.sdk.v1.UserMetadata.class; + } + + public Object toTransferType(UserMetadata value) { + return value == null + ? null + : value.toProto( + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter()); + } + + public UserMetadata fromTransferType(Object value, java.lang.reflect.Type valueType) { + return value == null + ? null + : fromProto( + (io.temporal.api.sdk.v1.UserMetadata) value, + io.temporal.internal.nexus.system.TemporalModelConverters.currentDataConverter(), + valueType); + } + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/WorkflowOperations.java b/temporal-sdk/src/main/generated/io/temporal/workflow/WorkflowOperations.java new file mode 100644 index 0000000000..5c4ea5b7a1 --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/WorkflowOperations.java @@ -0,0 +1,991 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow; + +@SuppressWarnings({"unchecked", "rawtypes"}) +public abstract class WorkflowOperations { + protected WorkflowOperations() {} + + private static io.temporal.workflow.SignalWithStartWorkflowRequest.Builder + newSignalWithStartWorkflowRequestBuilder( + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + java.util.Objects.requireNonNull(options, "options"); + io.temporal.workflow.SignalWithStartWorkflowRequest.Builder builder = + io.temporal.workflow.SignalWithStartWorkflowRequest.newBuilder(); + builder.setTaskQueue( + options.getTaskQueue() == null + ? io.temporal.workflow.Workflow.getInfo().getTaskQueue() + : options.getTaskQueue()); + if (options.getWorkflowExecutionTimeout() != null) + builder.setWorkflowExecutionTimeout(options.getWorkflowExecutionTimeout()); + if (options.getWorkflowRunTimeout() != null) + builder.setWorkflowRunTimeout(options.getWorkflowRunTimeout()); + if (options.getWorkflowTaskTimeout() != null) + builder.setWorkflowTaskTimeout(options.getWorkflowTaskTimeout()); + builder.setWorkflowIdReusePolicy( + options.getWorkflowIdReusePolicy() == null + ? io.temporal.api.enums.v1.WorkflowIdReusePolicy + .WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE + : options.getWorkflowIdReusePolicy()); + if (options.getWorkflowIdConflictPolicy() != null) + builder.setWorkflowIdConflictPolicy(options.getWorkflowIdConflictPolicy()); + if (options.getRetryOptions() != null) builder.setRetryOptions(options.getRetryOptions()); + if (options.getCronSchedule() != null) builder.setCronSchedule(options.getCronSchedule()); + if (options.getMemo() != null) builder.setMemo(options.getMemo()); + if (options.getTypedSearchAttributes() != null) + builder.setTypedSearchAttributes(options.getTypedSearchAttributes()); + if (options.getPriority() != null) builder.setPriority(options.getPriority()); + if (options.getVersioningOverride() != null) + builder.setVersioningOverride(options.getVersioningOverride()); + if (options.getStartDelay() != null) builder.setStartDelay(options.getStartDelay()); + if (options.getStaticSummary() != null) builder.setStaticSummary(options.getStaticSummary()); + if (options.getStaticDetails() != null) builder.setStaticDetails(options.getStaticDetails()); + builder.setNamespace( + io.temporal.internal.nexus.system.TemporalModelConverters.workflowNamespace()); + return builder; + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param workflow the workflow name + * @param args arguments supplied to {@code workflow} + * @param signal the signal name + * @param signalArgs arguments supplied to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + String workflow, + Object[] args, + String signal, + Object[] signalArgs, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + io.temporal.workflow.SignalWithStartWorkflowRequest.Builder requestBuilder = + newSignalWithStartWorkflowRequestBuilder(options); + requestBuilder.setWorkflowId( + java.util.Objects.requireNonNull(options.getWorkflowId(), "workflowId")); + requestBuilder.setArgs(java.util.Arrays.asList(java.util.Objects.requireNonNull(args, "args"))); + requestBuilder.setWorkflow(java.util.Objects.requireNonNull(workflow, "workflow")); + requestBuilder.setSignalArgs( + java.util.Arrays.asList(java.util.Objects.requireNonNull(signalArgs, "signalArgs"))); + requestBuilder.setSignal(java.util.Objects.requireNonNull(signal, "signal")); + io.temporal.workflow.SignalWithStartWorkflowRequest request = requestBuilder.build(); + return executeSignalWithStartWorkflow(request); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param workflow the workflow callable + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func workflow, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(), signal, () -> signal.apply(), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func workflow, + io.temporal.workflow.Functions.Proc1 signal, + T signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(), signal, () -> signal.apply(signalArg1), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param workflow the workflow callable + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc workflow, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(), signal, () -> signal.apply(), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc workflow, + io.temporal.workflow.Functions.Proc1 signal, + T signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(), signal, () -> signal.apply(signalArg1), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func1 workflow, + T workflowArg1, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(workflowArg1), signal, () -> signal.apply(), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func1 workflow, + T workflowArg1, + io.temporal.workflow.Functions.Proc1 signal, + U signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc1 workflow, + T workflowArg1, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, () -> workflow.apply(workflowArg1), signal, () -> signal.apply(), options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc1 workflow, + T workflowArg1, + io.temporal.workflow.Functions.Proc1 signal, + U signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func2 workflow, + T workflowArg1, + U workflowArg2, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func2 workflow, + T workflowArg1, + U workflowArg2, + io.temporal.workflow.Functions.Proc1 signal, + V signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc2 workflow, + T workflowArg1, + U workflowArg2, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc2 workflow, + T workflowArg1, + U workflowArg2, + io.temporal.workflow.Functions.Proc1 signal, + V signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func3 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func3 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + io.temporal.workflow.Functions.Proc1 signal, + W signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc3 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc3 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + io.temporal.workflow.Functions.Proc1 signal, + W signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func4 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func4 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + io.temporal.workflow.Functions.Proc1 signal, + X signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc4 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc4 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + io.temporal.workflow.Functions.Proc1 signal, + X signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func5 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func5 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + io.temporal.workflow.Functions.Proc1 signal, + Y signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc5 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc5 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + io.temporal.workflow.Functions.Proc1 signal, + Y signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> workflow.apply(workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 6 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param workflowArg6 argument 6 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func6 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + Y workflowArg6, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> + workflow.apply( + workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5, workflowArg6), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param result type of {@code workflow} + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 6 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param workflowArg6 argument 6 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Func6 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + Y workflowArg6, + io.temporal.workflow.Functions.Proc1 signal, + Z signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> + workflow.apply( + workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5, workflowArg6), + signal, + () -> signal.apply(signalArg1), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 6 to {@code workflow} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param workflowArg6 argument 6 passed to {@code workflow} + * @param signal the signal callable + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc6 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + Y workflowArg6, + io.temporal.workflow.Functions.Proc signal, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> + workflow.apply( + workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5, workflowArg6), + signal, + () -> signal.apply(), + options); + } + + /** + * Signal a workflow, starting it first if needed. + * + * @param type of argument 1 to {@code workflow} + * @param type of argument 2 to {@code workflow} + * @param type of argument 3 to {@code workflow} + * @param type of argument 4 to {@code workflow} + * @param type of argument 5 to {@code workflow} + * @param type of argument 6 to {@code workflow} + * @param type of argument 1 to {@code signal} + * @param workflow the workflow callable + * @param workflowArg1 argument 1 passed to {@code workflow} + * @param workflowArg2 argument 2 passed to {@code workflow} + * @param workflowArg3 argument 3 passed to {@code workflow} + * @param workflowArg4 argument 4 passed to {@code workflow} + * @param workflowArg5 argument 5 passed to {@code workflow} + * @param workflowArg6 argument 6 passed to {@code workflow} + * @param signal the signal callable + * @param signalArg1 argument 1 passed to {@code signal} + * @param options options for this operation; must not be null + * @return A workflow handle to the started workflow. + */ + public static + io.temporal.workflow.ExternalWorkflowStub signalWithStartWorkflow( + io.temporal.workflow.Functions.Proc6 workflow, + T workflowArg1, + U workflowArg2, + V workflowArg3, + W workflowArg4, + X workflowArg5, + Y workflowArg6, + io.temporal.workflow.Functions.Proc1 signal, + Z signalArg1, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + return invokeSignalWithStartWorkflow( + workflow, + () -> + workflow.apply( + workflowArg1, workflowArg2, workflowArg3, workflowArg4, workflowArg5, workflowArg6), + signal, + () -> signal.apply(signalArg1), + options); + } + + private static io.temporal.workflow.ExternalWorkflowStub invokeSignalWithStartWorkflow( + Object workflow, + io.temporal.workflow.Functions.Proc workflowInvocation, + Object signal, + io.temporal.workflow.Functions.Proc signalInvocation, + io.temporal.workflow.SignalWithStartWorkflowOptions options) { + io.temporal.workflow.SignalWithStartWorkflowRequest.Builder requestBuilder = + newSignalWithStartWorkflowRequestBuilder(options); + io.temporal.internal.sync.ExternalWorkflowInvocationHandler.ProbeResult workflowMetadata = + io.temporal.internal.nexus.system.TemporalModelConverters.captureWorkflowCall( + workflow, + workflowInvocation, + (capturedName, capturedArguments) -> { + requestBuilder.setWorkflow(capturedName); + requestBuilder.setArgs(java.util.Arrays.asList(capturedArguments)); + }); + io.temporal.internal.nexus.system.TemporalModelConverters.captureSignalCall( + signal, + signalInvocation, + (capturedName, capturedArguments) -> { + requestBuilder.setSignal(capturedName); + requestBuilder.setSignalArgs(java.util.Arrays.asList(capturedArguments)); + }); + requestBuilder.setWorkflowId( + java.util.Objects.requireNonNull( + io.temporal.internal.nexus.system.TemporalModelConverters.mergeWorkflowIdForStart( + workflowMetadata, options.getWorkflowId()), + "workflowId")); + requestBuilder.setRetryOptions( + io.temporal.internal.nexus.system.TemporalModelConverters.mergeMethodRetry( + workflowMetadata, options.getRetryOptions())); + requestBuilder.setCronSchedule( + io.temporal.internal.nexus.system.TemporalModelConverters.mergeCronSchedule( + workflowMetadata, options.getCronSchedule())); + io.temporal.workflow.SignalWithStartWorkflowRequest request = requestBuilder.build(); + return executeSignalWithStartWorkflow(request); + } + + static io.temporal.workflow.ExternalWorkflowStub executeSignalWithStartWorkflow( + io.temporal.workflow.SignalWithStartWorkflowRequest request) { + io.temporal.workflow.SignalWithStartWorkflowResponse result = + (io.temporal.workflow.SignalWithStartWorkflowResponse) + io.temporal.workflow.Workflow.newUntypedNexusServiceStub( + "temporal.api.workflowservice.v1.WorkflowService", + io.temporal.workflow.NexusServiceOptions.newBuilder() + .setEndpoint("__temporal_system") + .build()) + .execute( + "SignalWithStartWorkflowExecution", + io.temporal.workflow.SignalWithStartWorkflowResponse.class, + io.temporal.workflow.SignalWithStartWorkflowResponse.class, + request); + return io.temporal.internal.nexus.system.TemporalModelConverters.signalWithStartWorkflowHandle( + request.getWorkflowId(), result.getRunId()); + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/internal/SystemNexusOperations.java b/temporal-sdk/src/main/generated/io/temporal/workflow/internal/SystemNexusOperations.java new file mode 100644 index 0000000000..819192af41 --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/internal/SystemNexusOperations.java @@ -0,0 +1,40 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow.internal; + +/** Generated operation dispatch and serialization context acquisition. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +public final class SystemNexusOperations { + private SystemNexusOperations() {} + + public static + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor.ExecuteNexusOperationOutput< + R> + execute( + io.temporal.workflow.SystemNexusWorkflowOutboundInterceptor interceptor, + io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput< + R> + input) { + if ("temporal.api.workflowservice.v1.WorkflowService".equals(input.getService()) + && "SignalWithStartWorkflowExecution".equals(input.getOperation())) + return (io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationOutput< + R>) + interceptor.executeSignalWithStartWorkflow( + (io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor + .ExecuteNexusOperationInput) + input); + throw new IllegalArgumentException( + "Unsupported system Nexus operation: " + input.getService() + "/" + input.getOperation()); + } + + public static io.temporal.payload.context.SerializationContext serializationContext( + String service, String operation, Object request) { + if ("temporal.api.workflowservice.v1.WorkflowService".equals(service) + && "SignalWithStartWorkflowExecution".equals(operation)) + return io.temporal.internal.nexus.system.TemporalModelConverters + .signalWithStartWorkflowSerializationContext( + (io.temporal.workflow.SignalWithStartWorkflowRequest) request); + return null; + } +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/internal/WorkflowService.java b/temporal-sdk/src/main/generated/io/temporal/workflow/internal/WorkflowService.java new file mode 100644 index 0000000000..cb0045f134 --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/internal/WorkflowService.java @@ -0,0 +1,15 @@ +// Generated by nexgen v0.2.12. DO NOT EDIT! +package io.temporal.workflow.internal; + +@io.nexusrpc.Service(name = "temporal.api.workflowservice.v1.WorkflowService") +public interface WorkflowService { + /** + * Signal a workflow, starting it first if needed. + * + * @param request the operation request + * @return A workflow handle to the started workflow. + */ + @io.nexusrpc.Operation(name = "SignalWithStartWorkflowExecution") + io.temporal.workflow.SignalWithStartWorkflowResponse signalWithStartWorkflow( + io.temporal.workflow.SignalWithStartWorkflowRequest request); +} diff --git a/temporal-sdk/src/main/generated/io/temporal/workflow/system-nexus-roots.txt b/temporal-sdk/src/main/generated/io/temporal/workflow/system-nexus-roots.txt new file mode 100644 index 0000000000..434e51e32a --- /dev/null +++ b/temporal-sdk/src/main/generated/io/temporal/workflow/system-nexus-roots.txt @@ -0,0 +1,2 @@ +temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest +temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse diff --git a/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptor.java b/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptor.java index 37b3ea125a..06a5c657e2 100644 --- a/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptor.java +++ b/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptor.java @@ -37,7 +37,8 @@ * WorkflowInboundCallsInterceptor. */ @Experimental -public interface WorkflowOutboundCallsInterceptor { +public interface WorkflowOutboundCallsInterceptor + extends io.temporal.workflow.SystemNexusWorkflowOutboundInterceptor { final class ActivityInput { private final String activityName; diff --git a/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptorBase.java b/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptorBase.java index 40553b0367..6f9752d057 100644 --- a/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptorBase.java +++ b/temporal-sdk/src/main/java/io/temporal/common/interceptors/WorkflowOutboundCallsInterceptorBase.java @@ -19,10 +19,17 @@ import java.util.function.Supplier; /** Convenience base class for WorkflowOutboundCallsInterceptor implementations. */ -public class WorkflowOutboundCallsInterceptorBase implements WorkflowOutboundCallsInterceptor { +public class WorkflowOutboundCallsInterceptorBase + extends io.temporal.workflow.SystemNexusWorkflowOutboundInterceptor.Base + implements WorkflowOutboundCallsInterceptor { private final WorkflowOutboundCallsInterceptor next; + @Override + protected WorkflowOutboundCallsInterceptor nextSystemNexusInterceptor() { + return next; + } + public WorkflowOutboundCallsInterceptorBase(WorkflowOutboundCallsInterceptor next) { this.next = next; } diff --git a/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusDataConverter.java b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusDataConverter.java new file mode 100644 index 0000000000..32d8592732 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/SystemNexusDataConverter.java @@ -0,0 +1,93 @@ +package io.temporal.internal.nexus.system; + +import com.google.protobuf.Message; +import io.temporal.api.common.v1.Payload; +import io.temporal.api.common.v1.Payloads; +import io.temporal.api.failure.v1.Failure; +import io.temporal.common.converter.DataConverter; +import io.temporal.common.converter.DataConverterException; +import io.temporal.common.converter.RawValue; +import io.temporal.internal.common.converter.TemporalTransferTypeDataConverter; +import io.temporal.internal.payload.visitor.SystemNexusPayloads; +import java.lang.reflect.Type; +import java.util.Optional; +import java.util.function.Supplier; +import javax.annotation.Nonnull; + +/** Keeps the server-readable envelope separate from the destination workflow's user converter. */ +public final class SystemNexusDataConverter implements DataConverter { + public static final String ENDPOINT = "__temporal_system"; + private final DataConverter userConverter; + + /** Returns the user converter active in the current synchronous transfer conversion scope. */ + public static DataConverter currentDataConverter() { + return SystemNexusConverterContext.currentDataConverter(); + } + + static T withDataConverter(DataConverter converter, Supplier action) { + return SystemNexusConverterContext.withDataConverter(converter, action); + } + + public SystemNexusDataConverter(DataConverter userConverter) { + this.userConverter = userConverter; + } + + @Override + public Optional toPayload(T value) { + if (value instanceof RawValue) return Optional.of(((RawValue) value).getPayload()); + return withDataConverter( + userConverter, + () -> { + Object transferred = TemporalTransferTypeDataConverter.toTransferValue(value); + if (!(transferred instanceof Message)) + throw new DataConverterException( + "System Nexus inputs must have a protobuf transfer type"); + return Optional.of(SystemNexusPayloads.pack((Message) transferred)); + }); + } + + @Override + public T fromPayload(Payload payload, Class valueClass, Type valueType) { + if (valueClass == RawValue.class) return valueClass.cast(new RawValue(payload)); + return withDataConverter( + userConverter, + () -> { + Message value = SystemNexusPayloads.unpack(payload).build(); + TemporalTransferTypeDataConverter.TransferType transfer = + TemporalTransferTypeDataConverter.transferTypeFor(valueClass, valueType); + if (transfer == null) return valueClass.cast(value); + if (!transfer.getRawType().isInstance(value)) + throw new DataConverterException( + "Unexpected system Nexus response type: " + + value.getDescriptorForType().getFullName()); + return transfer.fromValue(value, valueClass); + }); + } + + @Override + public Optional toPayloads(Object... values) { + if (values == null || values.length == 0) return Optional.empty(); + Payloads.Builder result = Payloads.newBuilder(); + for (Object value : values) result.addPayloads(toPayload(value).get()); + return Optional.of(result.build()); + } + + @Override + public T fromPayloads( + int index, Optional values, Class valueClass, Type valueType) { + if (!values.isPresent() || index >= values.get().getPayloadsCount()) return null; + return fromPayload(values.get().getPayloads(index), valueClass, valueType); + } + + @Nonnull + @Override + public RuntimeException failureToException(@Nonnull Failure failure) { + return userConverter.failureToException(failure); + } + + @Nonnull + @Override + public Failure exceptionToFailure(@Nonnull Throwable failure) { + return userConverter.exceptionToFailure(failure); + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/TemporalModelConverters.java b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/TemporalModelConverters.java new file mode 100644 index 0000000000..fad0cbdae5 --- /dev/null +++ b/temporal-sdk/src/main/java/io/temporal/internal/nexus/system/TemporalModelConverters.java @@ -0,0 +1,219 @@ +package io.temporal.internal.nexus.system; + +import io.temporal.api.common.v1.*; +import io.temporal.api.taskqueue.v1.TaskQueue; +import io.temporal.common.CronSchedule; +import io.temporal.common.MethodRetry; +import io.temporal.common.RetryOptions; +import io.temporal.common.VersioningOverride; +import io.temporal.common.converter.DataConverter; +import io.temporal.common.metadata.WorkflowMethodType; +import io.temporal.internal.common.*; +import io.temporal.internal.sync.ExternalWorkflowInvocationHandler; +import io.temporal.payload.context.WorkflowSerializationContext; +import io.temporal.workflow.*; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +/** SDK-owned model conversion hooks used by the generated system Nexus bindings. */ +public final class TemporalModelConverters { + private TemporalModelConverters() {} + + /** Returns the user converter active during system Nexus transfer conversion. */ + public static DataConverter currentDataConverter() { + return SystemNexusDataConverter.currentDataConverter(); + } + + public static String workflowNamespace() { + return Workflow.getInfo().getNamespace(); + } + + /** Workflow-side bindings encode arguments but do not decode unknown-arity payload sequences. */ + public static List payloadsFromProto(DataConverter converter, Payloads value) { + throw new UnsupportedOperationException( + "Decoding payload sequences is not implemented for workflow-side bindings"); + } + + /** Returns a handle bound to the execution reported by signal with start. */ + public static ExternalWorkflowStub signalWithStartWorkflowHandle( + String workflowId, String runId) { + return Workflow.newUntypedExternalWorkflowStub( + WorkflowExecution.newBuilder() + .setWorkflowId(workflowId) + .setRunId(runId == null ? "" : runId) + .build()); + } + + /** Captures one typed workflow invocation without starting a child workflow. */ + public static ExternalWorkflowInvocationHandler.ProbeResult captureWorkflowCall( + Object method, Functions.Proc invocation, BiConsumer result) { + ExternalWorkflowInvocationHandler.ProbeResult call = + ExternalWorkflowInvocationHandler.probe(invocation, WorkflowMethodType.WORKFLOW); + result.accept(call.getMetadata().getName(), call.getArguments()); + return call; + } + + /** Captures one typed signal invocation without sending a signal. */ + public static void captureSignalCall( + Object method, Functions.Proc invocation, BiConsumer result) { + ExternalWorkflowInvocationHandler.ProbeResult call = + ExternalWorkflowInvocationHandler.probe(invocation, WorkflowMethodType.SIGNAL); + result.accept(call.getMetadata().getName(), call.getArguments()); + } + + /** Resolves a start operation's workflow ID from its bound workflow reference. */ + public static String mergeWorkflowIdForStart( + ExternalWorkflowInvocationHandler.ProbeResult call, String explicit) { + WorkflowExecution execution = call.getStub().getExecution(); + if (!execution.getRunId().isEmpty()) { + throw new IllegalArgumentException( + "Cannot start through a workflow reference bound to a run ID"); + } + String id = execution.getWorkflowId(); + if (id.isEmpty()) { + throw new IllegalArgumentException("Workflow reference must have a nonempty workflow ID"); + } + if (explicit != null && !explicit.equals(id)) { + throw new IllegalArgumentException( + "Explicit workflow ID does not match the workflow reference"); + } + return id; + } + + /** Merges the original method annotation with explicit retry settings. */ + public static RetryOptions mergeMethodRetry( + ExternalWorkflowInvocationHandler.ProbeResult call, RetryOptions explicit) { + return RetryOptions.merge( + call.getMetadata().getWorkflowMethod().getAnnotation(MethodRetry.class), explicit); + } + + /** Explicit schedules, including an empty string, override the method annotation. */ + public static String mergeCronSchedule( + ExternalWorkflowInvocationHandler.ProbeResult call, String explicit) { + CronSchedule annotation = + call.getMetadata().getWorkflowMethod().getAnnotation(CronSchedule.class); + return OptionsUtils.merge(annotation == null ? "" : annotation.value(), explicit, String.class); + } + + public static WorkflowSerializationContext signalWithStartWorkflowSerializationContext( + SignalWithStartWorkflowRequest request) { + return new WorkflowSerializationContext(request.getNamespace(), request.getWorkflowId()); + } + + public static RuntimeException failureFromProto( + DataConverter converter, io.temporal.api.failure.v1.Failure value) { + return converter.failureToException(value); + } + + public static io.temporal.api.failure.v1.Failure failureToProto( + DataConverter converter, RuntimeException value) { + return converter.exceptionToFailure(value); + } + + public static WorkflowType workflowTypeToProto(DataConverter converter, String value) { + return WorkflowType.newBuilder().setName(value).build(); + } + + public static String workflowTypeFromProto(DataConverter converter, WorkflowType value) { + return value.getName(); + } + + public static TaskQueue taskQueueToProto(DataConverter converter, String value) { + return TaskQueue.newBuilder().setName(value).build(); + } + + public static String taskQueueFromProto(DataConverter converter, TaskQueue value) { + return value.getName(); + } + + public static com.google.protobuf.Duration durationToProto( + DataConverter converter, Duration value) { + return ProtobufTimeUtils.toProtoDuration(value); + } + + public static Duration durationFromProto( + DataConverter converter, com.google.protobuf.Duration value) { + return ProtobufTimeUtils.toJavaDuration(value); + } + + public static RetryPolicy retryPolicyToProto(DataConverter converter, RetryOptions value) { + return RetryOptionsUtils.toRetryPolicy(value).build(); + } + + public static RetryOptions retryPolicyFromProto(DataConverter converter, RetryPolicy value) { + return RetryOptionsUtils.toRetryOptions(value); + } + + public static Memo memoToProto(DataConverter converter, Map value) { + return Memo.newBuilder().putAllFields(HeaderUtils.intoPayloadMap(converter, value)).build(); + } + + public static Map memoFromProto(DataConverter converter, Memo value) { + Map result = new LinkedHashMap<>(); + value + .getFieldsMap() + .forEach( + (key, payload) -> + result.put(key, converter.fromPayload(payload, Object.class, Object.class))); + return result; + } + + /** Copies wire-ready payloads; producer-specific encoding happens before model conversion. */ + public static Header headerToProto(DataConverter converter, Map value) { + return Header.newBuilder().putAllFields(value).build(); + } + + public static Map headerFromProto(DataConverter converter, Header value) { + return new LinkedHashMap<>(value.getFieldsMap()); + } + + public static io.temporal.api.common.v1.SearchAttributes searchAttributesToProto( + DataConverter converter, io.temporal.common.SearchAttributes value) { + return SearchAttributesUtil.encodeTyped(value); + } + + public static io.temporal.common.SearchAttributes searchAttributesFromProto( + DataConverter converter, io.temporal.api.common.v1.SearchAttributes value) { + return SearchAttributesUtil.decodeTyped(value); + } + + public static Priority priorityToProto( + DataConverter converter, io.temporal.common.Priority value) { + return ProtoConverters.toProto(value); + } + + public static io.temporal.common.Priority priorityFromProto( + DataConverter converter, Priority value) { + return ProtoConverters.fromProto(value); + } + + public static io.temporal.api.workflow.v1.VersioningOverride versioningOverrideToProto( + DataConverter converter, VersioningOverride value) { + return ProtoConverters.toProto(value); + } + + @SuppressWarnings("deprecation") + public static VersioningOverride versioningOverrideFromProto( + DataConverter converter, io.temporal.api.workflow.v1.VersioningOverride value) { + if (value.hasOneTime() && value.getOneTime().hasTargetDeploymentVersion()) + return new VersioningOverride.OneTimeVersioningOverride( + deployment(value.getOneTime().getTargetDeploymentVersion())); + if (value.hasPinned() && value.getPinned().hasVersion()) + return new VersioningOverride.PinnedVersioningOverride( + deployment(value.getPinned().getVersion())); + if (!value.getPinnedVersion().isEmpty()) + return new VersioningOverride.PinnedVersioningOverride( + io.temporal.common.WorkerDeploymentVersion.fromCanonicalString(value.getPinnedVersion())); + if (value.getAutoUpgrade()) return new VersioningOverride.AutoUpgradeVersioningOverride(); + throw new IllegalArgumentException("Unknown versioning override proto shape"); + } + + private static io.temporal.common.WorkerDeploymentVersion deployment( + io.temporal.api.deployment.v1.WorkerDeploymentVersion value) { + return new io.temporal.common.WorkerDeploymentVersion( + value.getDeploymentName(), value.getBuildId()); + } +} diff --git a/temporal-sdk/src/main/java/io/temporal/internal/sync/NexusServiceStubImpl.java b/temporal-sdk/src/main/java/io/temporal/internal/sync/NexusServiceStubImpl.java index 821b92f075..01f0ea9ac4 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/sync/NexusServiceStubImpl.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/sync/NexusServiceStubImpl.java @@ -61,7 +61,7 @@ public Promise executeAsync( .mergeNexusOperationOptions(options.getOperationMethodOptions().get(operationName)) .build(); WorkflowOutboundCallsInterceptor.ExecuteNexusOperationOutput result = - outboundCallsInterceptor.executeNexusOperation( + executeNexusOperation( new WorkflowOutboundCallsInterceptor.ExecuteNexusOperationInput<>( options.getEndpoint(), name, @@ -88,7 +88,7 @@ public NexusOperationHandle start( .mergeNexusOperationOptions(options.getOperationMethodOptions().get(operationName)) .build(); WorkflowOutboundCallsInterceptor.ExecuteNexusOperationOutput result = - outboundCallsInterceptor.executeNexusOperation( + executeNexusOperation( new WorkflowOutboundCallsInterceptor.ExecuteNexusOperationInput<>( options.getEndpoint(), name, @@ -101,6 +101,16 @@ public NexusOperationHandle start( return new NexusOperationHandleImpl<>(result.getOperationExecution(), result.getResult()); } + private WorkflowOutboundCallsInterceptor.ExecuteNexusOperationOutput executeNexusOperation( + WorkflowOutboundCallsInterceptor.ExecuteNexusOperationInput input) { + if (io.temporal.internal.nexus.system.SystemNexusDataConverter.ENDPOINT.equals( + input.getEndpoint())) { + return io.temporal.workflow.internal.SystemNexusOperations.execute( + outboundCallsInterceptor, input); + } + return outboundCallsInterceptor.executeNexusOperation(input); + } + @Override public NexusServiceOptions getOptions() { return options; diff --git a/temporal-sdk/src/main/java/io/temporal/internal/sync/SyncWorkflowContext.java b/temporal-sdk/src/main/java/io/temporal/internal/sync/SyncWorkflowContext.java index ada310fe18..f2894c7216 100644 --- a/temporal-sdk/src/main/java/io/temporal/internal/sync/SyncWorkflowContext.java +++ b/temporal-sdk/src/main/java/io/temporal/internal/sync/SyncWorkflowContext.java @@ -51,6 +51,7 @@ import io.temporal.payload.codec.PayloadCodec; 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 io.temporal.worker.WorkflowImplementationOptions; import io.temporal.workflow.*; @@ -77,7 +78,9 @@ * definition on the worker meets ReplayWorkflowContext which contains information from the * WorkflowTask */ -final class SyncWorkflowContext implements WorkflowContext, WorkflowOutboundCallsInterceptor { +final class SyncWorkflowContext + extends io.temporal.workflow.SystemNexusWorkflowOutboundInterceptor.Terminal + implements WorkflowContext, WorkflowOutboundCallsInterceptor { private static final Logger log = LoggerFactory.getLogger(SyncWorkflowContext.class); private final String namespace; @@ -856,6 +859,25 @@ public ChildWorkflowOutput executeChildWorkflow(ChildWorkflowInput inp return new ChildWorkflowOutput<>(result, executionPromise); } + @Nullable + @Override + protected Map propagateSystemNexusHeaders( + @Nullable Map headers, @Nullable SerializationContext context) { + io.temporal.api.common.v1.Header propagated = + toHeaderGrpc( + new Header(headers == null ? Collections.emptyMap() : headers), + HeaderUtils.fromContextPropagators(contextPropagators), + context == null ? headerCodec : HeaderUtils.withContext(headerCodec, context)); + return headers == null && propagated.getFieldsCount() == 0 ? null : propagated.getFieldsMap(); + } + + @Override + protected ExecuteNexusOperationOutput executeSystemNexusOperation( + ExecuteNexusOperationInput input) { + // Execute on this terminal directly, without re-entering the outbound interceptor chain. + return executeNexusOperation(input); + } + @Override public ExecuteNexusOperationOutput executeNexusOperation( ExecuteNexusOperationInput input) { @@ -878,10 +900,24 @@ public ExecuteNexusOperationOutput executeNexusOperation( // contextualized by the endpoint, service and operation instead. The same converter decodes the // result and converts failures, so each operation keeps the converter selected for it even when // several operations are in flight at once. - DataConverter nexusDataConverter = - dataConverter.withContext( - new NexusSerializationContext( - input.getEndpoint(), input.getService(), input.getOperation())); + final DataConverter nexusDataConverter; + final DataConverter userMetadataDataConverter; + if (io.temporal.internal.nexus.system.SystemNexusDataConverter.ENDPOINT.equals( + input.getEndpoint())) { + io.temporal.payload.context.SerializationContext context = + io.temporal.workflow.internal.SystemNexusOperations.serializationContext( + input.getService(), input.getOperation(), input.getArg()); + userMetadataDataConverter = + context == null ? dataConverter : dataConverter.withContext(context); + nexusDataConverter = + new io.temporal.internal.nexus.system.SystemNexusDataConverter(userMetadataDataConverter); + } else { + nexusDataConverter = + dataConverter.withContext( + new NexusSerializationContext( + input.getEndpoint(), input.getService(), input.getOperation())); + userMetadataDataConverter = nexusDataConverter; + } Optional payload = nexusDataConverter.toPayload(input.getArg()); @@ -902,7 +938,7 @@ public ExecuteNexusOperationOutput executeNexusOperation( @Nullable UserMetadata userMetadata = - makeUserMetaData(input.getOptions().getSummary(), null, nexusDataConverter); + makeUserMetaData(input.getOptions().getSummary(), null, userMetadataDataConverter); StartNexusOperationParameters parameters = new StartNexusOperationParameters( diff --git a/temporal-sdk/src/main/java/io/temporal/workflow/Workflow.java b/temporal-sdk/src/main/java/io/temporal/workflow/Workflow.java index 5ada7deac8..85cf90141e 100644 --- a/temporal-sdk/src/main/java/io/temporal/workflow/Workflow.java +++ b/temporal-sdk/src/main/java/io/temporal/workflow/Workflow.java @@ -53,7 +53,7 @@ * * @see io.temporal.workflow */ -public final class Workflow { +public final class Workflow extends WorkflowOperations { public static final int DEFAULT_VERSION = WorkflowInternal.DEFAULT_VERSION; /** diff --git a/temporal-sdk/src/main/nexus/README.md b/temporal-sdk/src/main/nexus/README.md new file mode 100644 index 0000000000..ba63f8f5e9 --- /dev/null +++ b/temporal-sdk/src/main/nexus/README.md @@ -0,0 +1,70 @@ +# System Nexus bindings + +The WIT definitions here are a temporary copy of the shared multi-language +definitions in nex-gen's `advanced/samples/inputs/workflow-service.wit` and +`deps/nexus-temporal-types/model.wit`. Keep the copies identical; Java directives +belong in the shared source alongside the other languages. The SDK will +eventually consume these definitions from the API repo instead. Protobuf +descriptors from +`temporal-serviceclient:generateProto` validate the mappings during generation. + +Regenerate with nexgen 0.2.12 from temporalio/nexgen#245, built with its +`advanced` feature, and `google-java-format` 1.24.0 on `PATH`: + +```sh +./gradlew :temporal-sdk:generateNexusSystemApi \ + -PnexgenBinary=/path/to/nexgen +./gradlew --offline spotlessApply +``` + +Generated Java and `system-nexus-roots.txt` are checked in under +`src/main/generated/io/temporal/workflow`, an isolated main Java source root. +The generator uses `--targets workflow`, `--package-name io.temporal.workflow`, +and the WIT annotation `@nexus.operations-class java="WorkflowOperations"`. +`Workflow` extends this +generated base once; additional operations require no handwritten facade methods. +Generated operations take only function references/names and their inputs as +parameters. All other fields live in a mandatory generated options object. +Its builder validates required caller values; defaults and merged fields resolve +at invocation. Typed calls derive an omitted workflow ID from the workflow +reference; name-based calls require an explicit ID before dispatch. +All generated API types are available from the workflow package. +Typed overloads take bound methods followed directly by arguments. SDK-owned +call-extractor hooks resolve annotated workflow/signal names and arguments +without executing commands; the generated wrapper constructs the request. +Primary callable arities zero through six and other callable arities zero or one +come from Java rendering policy and the IDL's primary marker. No operation names +or composite-operation roles are encoded in the generator. Java-only +`merge-from-function` hooks declare ID resolution plus retry and cron merging from the workflow +method's original annotations. The generator retains raw probe metadata, and +SDK helpers apply normal client precedence without synthesizing `WorkflowOptions`. +Explicit workflow IDs must match the workflow reference, which must not be +pinned to a run ID. Signal execution bindings are ignored. +The manifest derives from operation input/output protobuf transfer types. The service client's Java +payload visitor generator consumes it, including payload-free response roots, +without depending on compiled SDK classes. + +Regeneration passes `--format` to nexgen, which invokes the installed +`google-java-format` command. Version 1.24.0 matches the SDK's Spotless +configuration. Nexgen does not download the formatter. Normal SDK builds use +the checked-in output and do not require either tool. + +`TemporalModelConverters` lives in `io.temporal.internal.nexus.system` and +contains SDK-owned conversion and output-transform helpers. Generated dispatch +and service helpers live in `io.temporal.workflow.internal`. The nexgen +sample support file contains its own copies of these implementations. +The shared Temporal payload-sequence binding uses the support helper +`payloadsFromProto`, which explicitly rejects inbound conversion without known +argument types and arity. Outbound batch encoding is unchanged. +Converter scoping lives +in `SystemNexusConverterContext`; generated transfer converters obtain the active +converter through `TemporalModelConverters.currentDataConverter()` and fail +when no scope is active, matching Python. Protobuf field access is generated +directly. +Normal Java SDK builds do not require Rust or nex-gen. + +The SDK wraps any configured `DataConverter` in `SystemNexusDataConverter` for +system operations. That wrapper handles the outer envelope and delegates nested +user conversion; custom converters do not need to recognize system envelopes. +The shared payload visitor descends into marked envelopes for payload traversal. +`CodecDataConverter` contains no system Nexus handling. diff --git a/temporal-sdk/src/main/nexus/SIGNAL_WITH_START.md b/temporal-sdk/src/main/nexus/SIGNAL_WITH_START.md new file mode 100644 index 0000000000..46179e71f8 --- /dev/null +++ b/temporal-sdk/src/main/nexus/SIGNAL_WITH_START.md @@ -0,0 +1,143 @@ +# Signal with start inside workflows + +The generated workflow API atomically signals an external workflow, starting it +when necessary. It requires a server supporting the system workflow service with +`history.enableSignalWithStartFromWorkflow` enabled. + +```java +ExternalWorkflowStub external = Workflow.signalWithStartWorkflow( + "TargetWorkflow", new Object[] {input}, + "notify", new Object[] {signal}, + SignalWithStartWorkflowOptions.newBuilder() + .setWorkflowId("target") + .setTaskQueue("target-queue") + .setWorkflowRunTimeout(timeout) + .build()); +``` + +Import `Workflow`, `SignalWithStartWorkflowOptions`, and `ExternalWorkflowStub` +from `io.temporal.workflow`. The generated options builder contains the API's +options, including timeouts, retry policy, memo, conflict policy, and flattened +static summary/details setters. Task queue defaults to the calling workflow's +task queue at invocation; an explicit task queue overrides it. Options can be +built outside a workflow and reused without capturing workflow context. The +workflow ID can be omitted for typed calls and is required for name-based calls before +dispatch. Only the workflow and signal references or +names and their inputs are direct parameters. Every overload requires a non-null +options object. The request +is constructed internally. Namespace defaults to the caller's namespace. Request ID is omitted: +the system service manages it. + +The call returns after signal delivery/start completes. The returned external +stub supports further signals and cancellation. Use +`Async.function(() -> Workflow.signalWithStartWorkflow(workflowType, args, +signalName, signalArgs, options))` for a promise. + +Signal with start uses `executeSignalWithStartWorkflow`, not ordinary +`executeNexusOperation` interception. `WorkflowOutboundCallsInterceptorBase` +forwards the specific hook to the next interceptor. Direct implementations of +`WorkflowOutboundCallsInterceptor` must implement that hook and call +`next.executeSignalWithStartWorkflow(input)` to forward it, just like other +outbound operations. The generated `SystemNexusWorkflowOutboundInterceptor.Base` +provides typed forwarding, while its generated `Terminal` implements the typed +hooks through `executeSystemNexusOperation`. `SyncWorkflowContext` supplies that +terminal transport without re-entering the interceptor chain. Adding operations +does not require handwritten forwarding or terminal methods. + +Like the Go bindings, WIT selects the embedded header field with +`@nexus.context-propagation`. The generated Java terminal merges configured +context propagators after typed interception, using the destination workflow's +serialization context. Only producers opting into `encodeHeaders()` use the +header codec. Interceptor-supplied wire-ready payloads and legacy propagator +headers are preserved without another codec layer. These are workflow payload +headers, separate from Nexus transport headers. + +The typed overload checks workflow and signal arguments against their interface: + +```java +ExternalWorkflowStub external = Workflow.signalWithStartWorkflow( + target::run, input, + target::notifySignal, signal, + SignalWithStartWorkflowOptions.newBuilder() + .setTaskQueue("target-queue").setWorkflowRunTimeout(timeout).build()); +``` + +Create `target` with `Workflow.newExternalWorkflowStub(TargetWorkflow.class, "target")`. +Typed calls derive their destination ID from this workflow reference. A supplied +ID must match it. A workflow reference pinned to a run ID is rejected because +signal-with-start cannot honor that restriction. The signal reference provides +its name and arguments; its workflow ID and run ID are ignored. Options are not +modified, so ID-less options can be reused with different workflow references. +Pass bound workflow and signal methods followed directly by their arguments. +Typed overloads cover zero through six workflow arguments and zero or one signal +argument, including void workflow methods. Other arities use the name-based API. +The compiler checks arguments and retains generic workflow result information in +the functional interface. The operation itself returns an external stub, not the +workflow result. + +The existing external invocation handler probes method names, arguments, result +types, target execution, and the original annotated method using scoped +thread locals. It sends no commands while probing and restores normal invocation +behavior afterward, including on failure. The probe captures the original method +metadata from the actual stub invocation, without inspecting serialized lambdas. +Query/update methods, missing calls, and repeated calls are rejected. Both APIs +take invocation arguments directly; options do not contain argument fields. +Both forms support `Async.function`. + +Typed calls merge the workflow method's `@MethodRetry` and `@CronSchedule` with +explicit retry/cron options, matching the client SDK. Retry fields use +`RetryOptions.merge(annotation, explicitOptions)`; explicit non-default settings +take precedence over annotation values. Cron uses the annotation when the +explicit value is null; an explicit empty string disables the annotated schedule. +The signal method's annotations are not used for these fields. Defaults apply +when retry/cron options are unset. Untyped calls have no method annotations to merge. + +The shared WIT declares `@nexus.merge-from-function function="workflow"` hooks +on the retry and cron fields. Java generation retains the function's raw probe +metadata and calls the selected SDK merge helpers, without synthesizing +`WorkflowOptions` or hardcoding retry/cron policy in the generator. This directive +currently affects Java only. + +The shared ID field uses the same `merge-from-function` hook, referring to the +workflow function. Required values are validated after resolution; no extra +identity-specific generator metadata is needed. Other options use their +explicit values and existing defaults. + +`Workflow` inherits generated operations from `WorkflowOperations`. New WIT +operations become available after regeneration, without adding handwritten +options, capture proxies, stubs, or facade methods. The output transform, request +fields, and serialization-context hook are declared in WIT. The converter uses +the destination namespace and workflow ID for nested payloads, codecs, and +failures; the outer system envelope remains server-readable. + +`SystemSignalWithStartIntegrationTest` verifies this converter selection against a +supporting server with a signing codec, overlapping calls to distinct destination +workflows, payload inspection in history, and replay. Both scenarios run with +external storage disabled and enabled at a zero-byte offload threshold, with +both ordinary and batch-packing codecs. The batch codec packs three workflow +arguments, including a null, into one payload. The receiving workflow decodes +them using its declared argument types and arity. The +storage cases verify nested references in history, inline system envelopes, +retrieval during workflow execution, and destination codec metadata after +retrieval. Replaying both caller and target histories also exercises retrieval +of stored workflow and signal inputs. Converter unit tests cover valid and +unknown versioning override shapes; unknown shapes are rejected. + +This operation serializes the request and deserializes a response with no user +payloads. Generated request-model decoding of argument sequences is explicitly +unsupported: the shared Temporal `payloads` binding delegates to a support helper +that throws `UnsupportedOperationException`, rather than partially decoding an +unknown-length batch. This does not affect server-side workflow argument decoding. +Future operations returning embedded payloads must use generic response +models and propagate concrete result types from the API to transfer conversion. + +## Real-server tests + +The repository's dev-server profile enables the operation on its pinned server. +Run the signal-with-start, codec-context, external storage, and replay tests with: + +```sh +./gradlew --offline :temporal-sdk:test \ + --tests 'io.temporal.workflow.nexus.SystemSignalWithStartIntegrationTest' \ + -PtestServer=dev-server +``` diff --git a/temporal-sdk/src/main/nexus/deps/nexus-temporal-types/model.wit b/temporal-sdk/src/main/nexus/deps/nexus-temporal-types/model.wit new file mode 100644 index 0000000000..42ce3b562d --- /dev/null +++ b/temporal-sdk/src/main/nexus/deps/nexus-temporal-types/model.wit @@ -0,0 +1,257 @@ +package nexus:temporal-types@1.0.0; + +interface model { + /// String-shaped placeholder for semantic types that generators reinterpret. + type placeholder = string; + + /// @nexus.proto "temporal.api.common.v1.Payload" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="Object" + /// python="typing.Any" + /// typescript="common.Payload" + /// go="any" + /// dotnet="object?" + /// dotnet-from="ProtoExtensions.FromPayload" + /// dotnet-to="ProtoExtensions.ToPayload" + /// typescript-import="@temporalio/common" + type payload = placeholder; + + /// @nexus.proto "temporal.api.common.v1.Payloads" + /// typescript-import="@temporalio/proto" + /// @nexus.type + /// java="java.util.List" + /// java-from="payloadsFromProto" + /// go="[]any" + /// dotnet="IReadOnlyCollection" + /// dotnet-from="ProtoExtensions.FromPayloads" + /// dotnet-to="ProtoExtensions.ToPayloads" + type payloads = list; + + /// Temporal failure represented by the target SDK's native exception/error type. + /// The SDK failure converter owns the recursive cause and failure-info structure. + /// @nexus.proto "temporal.api.failure.v1.Failure" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="RuntimeException" + /// java-from="failureFromProto" + /// java-to="failureToProto" + /// python="BaseException" + /// typescript="Error" + /// typescript-from="errorFromFailure" + /// typescript-to="errorToFailure" + /// go="error" + /// dotnet="System.Exception" + /// dotnet-from="ProtoExtensions.FromFailureProto" + /// dotnet-to="ProtoExtensions.ToFailureProto" + type failure = placeholder; + + /// Callable result annotation for workflow functions. + /// @nexus.type + /// python="collections.abc.Awaitable[WorkflowResult]" + /// typescript="Promise" + /// go="any" + /// dotnet="System.Threading.Tasks.Task" + type workflow-result = placeholder; + + /// Receiver/context argument for workflow callable method forms. + /// @nexus.type python="typing.Any" typescript="any" go="go.temporal.io/sdk/internal:internal.Context" dotnet="object" + type callable-prefix = placeholder; + + /// @nexus.function-args + /// varargs=true + /// param="args" + /// typescript-drop-prefix=true + workflow-call: async func(callable-prefix: callable-prefix, args: payloads) -> workflow-result; + + /// Callable result annotation for signal functions. + /// @nexus.type java="Void" python="None | collections.abc.Awaitable[None]" typescript="void" go="any" dotnet="void" + type signal-result = placeholder; + + /// @nexus.function-args + /// varargs=true + /// param="signal-args" + /// typescript-drop-prefix=true + signal-call: func(callable-prefix: callable-prefix, signal-args: payloads) -> signal-result; + + /// @nexus.proto "temporal.api.common.v1.WorkflowType" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="String" + /// java-from="workflowTypeFromProto" + /// java-to="workflowTypeToProto" + /// python="str" + /// typescript="string" + /// go="string" + /// dotnet="string" + /// dotnet-from="ProtoExtensions.FromWorkflowTypeProto" + /// dotnet-to="ProtoExtensions.ToWorkflowTypeProto" + type workflow-type = placeholder; + + /// @nexus.function + /// primary=true + /// signature="workflow-call" + /// args-field="input" + /// result-type-parameter="WorkflowResult" + /// alternate-type="workflow-type" + /// go-name-extractor="WorkflowFunctionName" + /// dotnet-name-extractor="TemporalFunctionNames.WorkflowName" + /// dotnet-call-extractor="TemporalFunctionNames.ExtractCall" + /// java-call-extractor="captureWorkflowCall" + /// java-call-metadata-type="io.temporal.internal.sync.ExternalWorkflowInvocationHandler.ProbeResult" + /// @nexus.add-rpc-compatible-with "workflow-type" + type workflow-function = placeholder; + + /// @nexus.function + /// signature="signal-call" + /// args-field="signal-input" + /// alternate-type="string" + /// go-value-type="string" + /// go-args-type="any" + /// python-converter="signal_function_to_proto" + /// typescript-name-extractor="signalFunctionName" + /// dotnet-name-extractor="TemporalFunctionNames.SignalName" + /// dotnet-call-extractor="TemporalFunctionNames.ExtractCall" + /// java-call-extractor="captureSignalCall" + /// typescript-value-type="common.SignalDefinition" + /// typescript-args-type="Value extends common.SignalDefinition ? Args : never" + /// typescript-import="@temporalio/common" + /// @nexus.add-rpc-compatible-with "string" + type signal-function = placeholder; + + /// @nexus.proto "temporal.api.common.v1.RetryPolicy" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.common.RetryOptions" + /// java-from="retryPolicyFromProto" + /// java-to="retryPolicyToProto" + /// python="temporalio.common.RetryPolicy" + /// typescript="common.RetryPolicy" + /// go="go.temporal.io/sdk/internal.RetryPolicy" + /// dotnet="Temporalio.Common.RetryPolicy" + /// dotnet-from="ProtoExtensions.FromRetryPolicyProto" + /// typescript-import="@temporalio/common" + type retry-policy = placeholder; + + /// @nexus.proto "temporal.api.taskqueue.v1.TaskQueue" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="String" + /// java-from="taskQueueFromProto" + /// java-to="taskQueueToProto" + /// python="str" + /// typescript="string" + /// go="string" + /// dotnet="string" + /// dotnet-from="ProtoExtensions.FromTaskQueueProto" + /// dotnet-to="ProtoExtensions.ToTaskQueueProto" + type task-queue = placeholder; + + /// @nexus.proto "temporal.api.common.v1.Memo" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="java.util.Map" + /// java-from="memoFromProto" + /// java-to="memoToProto" + /// python="collections.abc.Mapping[str, typing.Any]" + /// typescript="Record" + /// go="map[string]any" + /// dotnet="IReadOnlyDictionary" + /// dotnet-from="ProtoExtensions.FromMemoProto" + type memo = placeholder; + + /// @nexus.proto "temporal.api.common.v1.Header" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="java.util.Map" + /// java-from="headerFromProto" + /// java-to="headerToProto" + /// python="collections.abc.Mapping[str, typing.Any]" + /// typescript="Record" + /// go="map[string]*go.temporal.io/api/common/v1:common.Payload" + /// dotnet="IReadOnlyDictionary" + /// dotnet-from="ProtoExtensions.FromHeaderProto" + /// dotnet-to="ProtoExtensions.ToHeaderProto" + /// typescript-import="@temporalio/common" + type header = placeholder; + + /// @nexus.proto "temporal.api.common.v1.SearchAttributes" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.common.SearchAttributes" + /// java-from="searchAttributesFromProto" + /// java-to="searchAttributesToProto" + /// python="temporalio.common.TypedSearchAttributes" + /// typescript="common.TypedSearchAttributes" + /// go="go.temporal.io/sdk/internal.SearchAttributes" + /// dotnet="Temporalio.Common.SearchAttributeCollection" + /// dotnet-from="ProtoExtensions.FromSearchAttributesProto" + /// typescript-import="@temporalio/common" + type search-attributes = placeholder; + + /// @nexus.proto "temporal.api.common.v1.Priority" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.common.Priority" + /// java-from="priorityFromProto" + /// java-to="priorityToProto" + /// python="temporalio.common.Priority" + /// typescript="common.Priority" + /// go="go.temporal.io/sdk/internal.Priority" + /// dotnet="Temporalio.Common.Priority" + /// dotnet-from="ProtoExtensions.FromPriorityProto" + /// typescript-import="@temporalio/common" + type priority = placeholder; + + /// @nexus.proto "temporal.api.workflow.v1.VersioningOverride" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.common.VersioningOverride" + /// java-from="versioningOverrideFromProto" + /// java-to="versioningOverrideToProto" + /// python="temporalio.common.VersioningOverride" + /// typescript="common.VersioningOverride" + /// go="go.temporal.io/sdk/internal.VersioningOverride" + /// dotnet="Temporalio.Common.VersioningOverride" + /// dotnet-from="ProtoExtensions.FromVersioningOverrideProto" + /// typescript-import="@temporalio/common" + type versioning-override = placeholder; + + /// @nexus.proto "google.protobuf.Duration" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="java.time.Duration" + /// java-from="durationFromProto" + /// java-to="durationToProto" + /// python="datetime.timedelta" + /// typescript="common.Duration" + /// go="time.Duration" + /// dotnet="System.TimeSpan" + /// dotnet-from="ProtoExtensions.FromDurationProto" + /// typescript-import="@temporalio/common" + type duration = placeholder; + + /// @nexus.proto "temporal.api.enums.v1.WorkflowIdReusePolicy" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.api.enums.v1.WorkflowIdReusePolicy" + /// python="temporalio.common.WorkflowIDReusePolicy" + /// typescript="common.WorkflowIdReusePolicy" + /// go="go.temporal.io/api/enums/v1:enums.WorkflowIdReusePolicy" + /// dotnet="Temporalio.Api.Enums.V1.WorkflowIdReusePolicy" + /// typescript-import="@temporalio/common" + type workflow-id-reuse-policy = placeholder; + + /// @nexus.proto "temporal.api.enums.v1.WorkflowIdConflictPolicy" typescript-import="@temporalio/proto" + /// @nexus.type + /// java="io.temporal.api.enums.v1.WorkflowIdConflictPolicy" + /// python="temporalio.common.WorkflowIDConflictPolicy" + /// typescript="common.WorkflowIdConflictPolicy" + /// go="go.temporal.io/api/enums/v1:enums.WorkflowIdConflictPolicy" + /// dotnet="Temporalio.Api.Enums.V1.WorkflowIdConflictPolicy" + /// typescript-import="@temporalio/common" + type workflow-id-conflict-policy = placeholder; + + /// @nexus.doc "Static metadata for a workflow execution." + /// @nexus.proto "temporal.api.sdk.v1.UserMetadata" typescript-import="@temporalio/proto" + /// @nexus.flatten-in-api + /// @nexus.experimental + record user-metadata { + /// @nexus.doc "Single-line fixed summary for the workflow execution that may appear in UI and CLI. This can be in single-line Temporal Markdown format." + /// @nexus.proto-field "summary" + /// @nexus.flattened-type java="String" python="str" typescript="string" dotnet="string" go="string" + static-summary: option, + /// @nexus.doc "General fixed details for the workflow execution that may appear in UI and CLI. This can be in Temporal Markdown format and can span multiple lines. This value is fixed on the workflow execution and cannot be updated." + /// @nexus.proto-field "details" + /// @nexus.flattened-type java="String" python="str" typescript="string" dotnet="string" go="string" + static-details: option, + } +} diff --git a/temporal-sdk/src/main/nexus/workflow-service.wit b/temporal-sdk/src/main/nexus/workflow-service.wit new file mode 100644 index 0000000000..c14831094b --- /dev/null +++ b/temporal-sdk/src/main/nexus/workflow-service.wit @@ -0,0 +1,169 @@ +package temporal:nexus@1.0.0; + +world system { + export workflow-service; +} + +/// @nexus.endpoint "temporal-system" go="__temporal_system" python="__temporal_system" java="__temporal_system" +/// @nexus.service-name "temporal.api.workflowservice.v1.WorkflowService" +/// @nexus.namespace dotnet="Temporalio.Workflows" go="go.temporal.io/sdk/advanced/samples/go/workflowservice" +/// @nexus.facade go="go.temporal.io/sdk/advanced/samples/go/workflowservice_facade" +/// @nexus.operations-class dotnet="SystemNexusWorkflowOperations" java="WorkflowOperations" +/// @nexus.delay-load-temporalio-workflow +/// @nexus.experimental +interface workflow-service { + use nexus:temporal-types/model@1.0.0.{ + duration, + header, + memo, + payloads, + placeholder, + priority, + retry-policy, + search-attributes, + signal-function, + task-queue, + user-metadata, + versioning-override, + workflow-function, + workflow-id-conflict-policy, + workflow-id-reuse-policy, + }; + + /// @nexus.doc "Request fields for signaling a workflow, starting it first if needed." + /// @nexus.experimental + /// @nexus.proto "temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest" typescript-import="@temporalio/proto" + record signal-with-start-workflow-request { + /// @nexus.doc + /// python="Workflow type name or callable identifying the workflow to start." + /// typescript="Workflow type name or workflow function identifying the workflow to start." + /// dotnet="Workflow type name or workflow expression identifying the workflow to start." + /// go="Workflow function identifying the workflow to start." + /// @nexus.proto-field "workflow_type" + workflow: workflow-function, + /// @nexus.doc "Unique identifier for the workflow execution. Must be nonempty." java="Workflow ID. Typed calls derive it from the workflow reference when omitted; an explicit ID must match. Required for name-based calls." + /// @nexus.name java="workflowId" + /// @nexus.proto-field "workflow_id" + /// @nexus.merge-from-function function="workflow" java="mergeWorkflowIdForStart" + id: string, + /// @nexus.doc "Task queue to run the workflow on. Defaults to the calling workflow's task queue." + /// @nexus.default targets="workflow" + /// java="io.temporal.workflow.Workflow.getInfo().getTaskQueue()" + /// python="_support.workflow_task_queue()" + /// typescript="workflow.workflowInfo().taskQueue" + /// go="internal.GetWorkflowInfo(ctx).TaskQueueName" + /// dotnet="Temporalio.Workflows.Workflow.Info.TaskQueue" + task-queue: task-queue, + /// @nexus.doc + /// python="Signal name or callable to send with the start request." + /// typescript="Signal name or signal definition to send with the start request." + /// dotnet="Signal name or signal expression to send with the start request." + /// go="Signal name to send with the start request." + /// @nexus.proto-field "signal_name" + signal: signal-function, + /// @nexus.doc "Total workflow execution timeout, including retries and continue-as-new. Defaults to unlimited." + /// @nexus.proto-field "workflow_execution_timeout" + /// @nexus.name go="WorkflowExecutionTimeout" java="workflowExecutionTimeout" + execution-timeout: option, + /// @nexus.doc "Timeout of a single workflow run. Defaults to the workflow execution timeout." + /// @nexus.proto-field "workflow_run_timeout" + /// @nexus.name go="WorkflowRunTimeout" java="workflowRunTimeout" + run-timeout: option, + /// @nexus.doc "Timeout of a single workflow task. Defaults to 10 seconds." + /// @nexus.proto-field "workflow_task_timeout" + /// @nexus.name go="WorkflowTaskTimeout" java="workflowTaskTimeout" + task-timeout: option, + /// @nexus.omit + identity: placeholder, + /// @nexus.omit + request-id: placeholder, + /// @nexus.doc "Behavior when a closed workflow with the same ID exists. Default is allow-duplicate." + /// @nexus.proto-field "workflow_id_reuse_policy" + /// @nexus.default + /// java="io.temporal.api.enums.v1.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE" + /// python="temporalio.common.WorkflowIDReusePolicy.ALLOW_DUPLICATE" + /// typescript="common.WorkflowIdReusePolicy.ALLOW_DUPLICATE" + /// go="enums.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE" + /// dotnet="Temporalio.Api.Enums.V1.WorkflowIdReusePolicy.AllowDuplicate" + /// @nexus.name go="WorkflowIDReusePolicy" java="workflowIdReusePolicy" + id-reuse-policy: workflow-id-reuse-policy, + /// @nexus.doc "Behavior when a workflow is currently running with the same ID. Set to use-existing for idempotent deduplication on workflow ID. Cannot be set if id-reuse-policy is terminate-if-running. Defaults to use-existing." + /// @nexus.proto-field "workflow_id_conflict_policy" + /// @nexus.name go="WorkflowIDConflictPolicy" java="workflowIdConflictPolicy" + id-conflict-policy: option, + /// @nexus.doc "Retry policy for the workflow." + /// @nexus.name java="retryOptions" + /// @nexus.merge-from-function function="workflow" java="mergeMethodRetry" + retry-policy: option, + /// @nexus.doc "Cron schedule for recurring workflow executions. See https://docs.temporal.io/cron-job." + /// @nexus.merge-from-function function="workflow" java="mergeCronSchedule" + cron-schedule: option, + /// @nexus.doc "Memo for the workflow." + memo: option, + /// @nexus.doc "Typed search attributes for the workflow." + /// @nexus.name go="TypedSearchAttributes" java="typedSearchAttributes" + search-attributes: option, + /// @nexus.doc "Priority of the workflow execution." + priority: option, + /// @nexus.doc "Override for workflow versioning behavior." + versioning-override: option, + /// @nexus.doc "Amount of time to wait before starting the workflow. This does not work with cron-schedule." + /// @nexus.proto-field "workflow_start_delay" + start-delay: option, + /// @nexus.doc "Static metadata for the workflow execution." + user-metadata: option, + /// @nexus.source targets="workflow" java="workflowNamespace()" python="workflow_namespace()" typescript="workflowNamespace()" go="WorkflowNamespace(ctx)" dotnet="TemporalWorkflowContext.WorkflowNamespace()" + /// @nexus.doc "Namespace of the workflow execution." + namespace: string, + /// @nexus.omit + control: placeholder, + /// @nexus.api-omit + /// @nexus.doc "Headers for the request." + /// @nexus.proto-field "header" + headers: option
, + /// @nexus.omit + links: placeholder, + /// @nexus.omit + time-skipping-config: placeholder, + } + + /// @nexus.doc "Result of signaling a workflow and starting it if needed." + /// @nexus.experimental + /// @nexus.proto "temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse" typescript-import="@temporalio/proto" + record signal-with-start-workflow-response { + /// @nexus.doc "Run ID of the signaled workflow." + run-id: string, + /// @nexus.doc "Whether the workflow was started." + started: bool, + /// @nexus.omit + signal-link: placeholder, + /// @nexus.omit + first-execution-run-id: placeholder, + } + + /// @nexus.doc + /// "Signal a workflow, starting it first if needed." + /// go="Signal a workflow, starting it first if needed. Encode payloads with the configured data converter." + /// returns="A workflow handle to the started workflow." + /// go-returns="A workflow.Execution with details about the signaled workflow." + /// @nexus.output-transform + /// java-type="io.temporal.workflow.ExternalWorkflowStub" + /// java="signalWithStartWorkflowHandle(request.getWorkflowId(), result.getRunId())" + /// python-type="temporalio.workflow.ExternalWorkflowHandle[WorkflowResult]" + /// python="temporalio.workflow.get_external_workflow_handle(request.id, run_id=result.run_id)" + /// typescript-type="ExternalWorkflowHandle" + /// typescript-type-import="../../../../workflow" + /// typescript="workflow.getExternalWorkflowHandle(request.id, result.runId ?? undefined)" + /// typescript-import="@temporalio/workflow" + /// dotnet-type="Temporalio.Workflows.ExternalWorkflowHandle" + /// dotnet="Temporalio.Workflows.Workflow.GetExternalWorkflowHandle(request.Id, result.RunId)" + /// go-type="go.temporal.io/sdk/workflow:workflow.Execution" + /// go="func() (workflow.Execution, error) { return workflow.Execution{ID: request.ID, RunID: result.GetRunId()}, nil }()" + /// @nexus.operation name="SignalWithStartWorkflowExecution" + /// @nexus.serialization-context java="signalWithStartWorkflowSerializationContext" python="signal_with_start_workflow_serialization_context" typescript="signalWithStartWorkflowSerializationContext" dotnet="WorkflowServiceSerializationContexts.SignalWithStartWorkflow" go="SignalWithStartWorkflowSerializationContext" + /// @nexus.context-propagation go="request.headers" java="request.headers" + /// @nexus.experimental + signal-with-start-workflow: func( + request: signal-with-start-workflow-request, + ) -> signal-with-start-workflow-response; +} diff --git a/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusDataConverterTest.java b/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusDataConverterTest.java new file mode 100644 index 0000000000..8ef05820d5 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/internal/nexus/system/SystemNexusDataConverterTest.java @@ -0,0 +1,315 @@ +package io.temporal.internal.nexus.system; + +import static org.junit.Assert.*; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.Mockito.*; + +import com.google.protobuf.ByteString; +import io.temporal.api.common.v1.Payload; +import io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest; +import io.temporal.common.converter.*; +import io.temporal.internal.payload.visitor.SystemNexusPayloads; +import io.temporal.payload.codec.PayloadCodec; +import io.temporal.payload.context.SerializationContext; +import io.temporal.payload.context.WorkflowSerializationContext; +import io.temporal.workflow.*; +import io.temporal.workflow.internal.SystemNexusOperations; +import java.lang.reflect.Type; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import org.junit.Test; + +public class SystemNexusDataConverterTest { + private static final String SERVICE = "temporal.api.workflowservice.v1.WorkflowService"; + private static final String OPERATION = "SignalWithStartWorkflowExecution"; + + private static SignalWithStartWorkflowRequest request(String id) { + return SignalWithStartWorkflowRequest.newBuilder() + .setNamespace("destination") + .setWorkflowId(id) + .setWorkflow("Target") + .setTaskQueue("queue") + .setSignal("notify") + .setArgs(Arrays.asList("workflow", 42)) + .setSignalArgs(Collections.singletonList("signal")) + .setMemo(Collections.singletonMap("memo", "value")) + .setHeaders( + Collections.singletonMap( + "trace", DefaultDataConverter.STANDARD_INSTANCE.toPayload("trace-value").get())) + .setUserMetadata(UserMetadata.newBuilder().setStaticSummary("summary").build()) + .build(); + } + + @Test + public void decodesUnmarkedServerResponse() { + Payload response = + SystemNexusPayloads.pack( + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse + .newBuilder() + .setRunId("run") + .setStarted(true) + .build()) + .toBuilder() + .removeMetadata("__temporal_system_payload") + .build(); + assertFalse(SystemNexusPayloads.isSystemPayload(response)); + SignalWithStartWorkflowResponse decoded = + new SystemNexusDataConverter(DefaultDataConverter.STANDARD_INSTANCE) + .fromPayload( + response, + SignalWithStartWorkflowResponse.class, + SignalWithStartWorkflowResponse.class); + assertEquals("run", decoded.getRunId()); + assertEquals(Boolean.TRUE, decoded.getStarted()); + } + + @Test + public void nestedPayloadsUseDestinationContextAndOuterEnvelopeBypassesCodecs() throws Exception { + SignalWithStartWorkflowRequest request = request("target"); + WorkflowSerializationContext context = + (WorkflowSerializationContext) + SystemNexusOperations.serializationContext(SERVICE, OPERATION, request); + assertEquals("destination", context.getNamespace()); + assertEquals("target", context.getWorkflowId()); + DataConverter user = + new CodecDataConverter( + DefaultDataConverter.STANDARD_INSTANCE, + Collections.singletonList(new ContextCodec(null))) + .withContext(context); + SystemNexusDataConverter converter = new SystemNexusDataConverter(user); + Payload encoded = converter.toPayload(request).get(); + assertTrue(SystemNexusPayloads.isSystemPayload(encoded)); + assertFalse(encoded.getMetadataMap().containsKey("test-context")); + SignalWithStartWorkflowExecutionRequest wire = + SignalWithStartWorkflowExecutionRequest.parseFrom(encoded.getData()); + assertEquals("", wire.getRequestId()); + assertEquals( + "target", wire.getInput().getPayloads(0).getMetadataOrThrow("test-context").toStringUtf8()); + assertEquals( + "target", + wire.getSignalInput().getPayloads(0).getMetadataOrThrow("test-context").toStringUtf8()); + assertEquals( + "target", + wire.getMemo().getFieldsOrThrow("memo").getMetadataOrThrow("test-context").toStringUtf8()); + assertArrayEquals( + request.getArgs().toArray(), + user.fromPayloads( + Optional.of(wire.getInput()), + new Class[] {String.class, Integer.class}, + new Type[] {String.class, Integer.class})); + assertEquals( + "signal", + user.fromPayloads(0, Optional.of(wire.getSignalInput()), String.class, String.class)); + assertEquals( + "value", + user.fromPayload(wire.getMemo().getFieldsOrThrow("memo"), String.class, String.class)); + assertEquals(request.getHeaders().get("trace"), wire.getHeader().getFieldsOrThrow("trace")); + assertEquals( + "summary", + user.fromPayload(wire.getUserMetadata().getSummary(), String.class, String.class)); + } + + @Test + public void customDataConverterReceivesUserValuesWithoutSystemEnvelopeHandling() + throws Exception { + SignalWithStartWorkflowRequest request = request("target"); + DataConverter user = + mock(DataConverter.class, delegatesTo(DefaultDataConverter.STANDARD_INSTANCE)); + SystemNexusDataConverter converter = new SystemNexusDataConverter(user); + Payload encoded = converter.toPayload(request).get(); + assertTrue(SystemNexusPayloads.isSystemPayload(encoded)); + SignalWithStartWorkflowExecutionRequest wire = + SignalWithStartWorkflowExecutionRequest.parseFrom(encoded.getData()); + assertEquals("target", wire.getWorkflowId()); + verify(user).toPayloads("workflow", 42); + verify(user).toPayloads("signal"); + verify(user).toPayload("value"); + verify(user, never()).toPayload(request); + verify(user, never()).toPayload(isA(com.google.protobuf.Message.class)); + assertEquals(2, wire.getInput().getPayloadsCount()); + assertEquals(1, wire.getSignalInput().getPayloadsCount()); + assertEquals(request.getHeaders().get("trace"), wire.getHeader().getFieldsOrThrow("trace")); + } + + @Test + public void requestPayloadSequenceDecodingIsExplicitlyUnsupported() { + SystemNexusDataConverter converter = + new SystemNexusDataConverter(DefaultDataConverter.STANDARD_INSTANCE); + Payload encoded = converter.toPayload(request("target")).get(); + DataConverterException failure = + assertThrows( + DataConverterException.class, + () -> + converter.fromPayload( + encoded, + SignalWithStartWorkflowRequest.class, + SignalWithStartWorkflowRequest.class)); + assertTrue(failure.getCause() instanceof UnsupportedOperationException); + assertEquals( + "Decoding payload sequences is not implemented for workflow-side bindings", + failure.getCause().getMessage()); + assertThrows(IllegalStateException.class, SystemNexusDataConverter::currentDataConverter); + } + + @Test + public void responseAndRawValuesRoundTripAndConverterScopesRestore() { + SystemNexusDataConverter converter = + new SystemNexusDataConverter(DefaultDataConverter.STANDARD_INSTANCE); + SignalWithStartWorkflowResponse response = + SignalWithStartWorkflowResponse.newBuilder().setRunId("run").setStarted(true).build(); + Payload encoded = converter.toPayload(response).get(); + assertEquals( + "run", + converter + .fromPayload( + encoded, + SignalWithStartWorkflowResponse.class, + SignalWithStartWorkflowResponse.class) + .getRunId()); + assertSame(encoded, converter.toPayload(new RawValue(encoded)).get()); + assertThrows(IllegalStateException.class, SystemNexusDataConverter::currentDataConverter); + } + + @Test + public void converterScopesRestoreAfterNestedFailure() { + DataConverter outer = DefaultDataConverter.STANDARD_INSTANCE; + DataConverter inner = new DefaultDataConverter(); + assertThrows(IllegalStateException.class, SystemNexusDataConverter::currentDataConverter); + SystemNexusDataConverter.withDataConverter( + outer, + () -> { + assertSame(outer, SystemNexusDataConverter.currentDataConverter()); + assertThrows( + IllegalArgumentException.class, + () -> + SystemNexusDataConverter.withDataConverter( + inner, + () -> { + assertSame(inner, SystemNexusDataConverter.currentDataConverter()); + throw new IllegalArgumentException("test"); + })); + assertSame(outer, SystemNexusDataConverter.currentDataConverter()); + return null; + }); + assertThrows(IllegalStateException.class, SystemNexusDataConverter::currentDataConverter); + } + + @Test + public void transferConversionRequiresActiveUserConverter() { + SignalWithStartWorkflowRequest.Converter converter = + new SignalWithStartWorkflowRequest.Converter(); + IllegalStateException encodeFailure = + assertThrows( + IllegalStateException.class, () -> converter.toTransferType(request("target"))); + assertEquals("System Nexus user converter context is not active", encodeFailure.getMessage()); + assertThrows( + IllegalStateException.class, + () -> + converter.fromTransferType( + SignalWithStartWorkflowExecutionRequest.getDefaultInstance(), + SignalWithStartWorkflowRequest.class)); + } + + @Test + public void operationsEncodeUsingIndependentDestinationConverters() { + SignalWithStartWorkflowRequest first = request("first"); + SignalWithStartWorkflowRequest second = request("second"); + DataConverter base = + new CodecDataConverter( + DefaultDataConverter.STANDARD_INSTANCE, + Collections.singletonList(new ContextCodec(null))); + SystemNexusDataConverter firstConverter = + new SystemNexusDataConverter( + base.withContext( + SystemNexusOperations.serializationContext(SERVICE, OPERATION, first))); + SystemNexusDataConverter secondConverter = + new SystemNexusDataConverter( + base.withContext( + SystemNexusOperations.serializationContext(SERVICE, OPERATION, second))); + Payload firstPayload = firstConverter.toPayload(first).get(); + Payload secondPayload = secondConverter.toPayload(second).get(); + SignalWithStartWorkflowExecutionRequest firstWire = + firstConverter.fromPayload( + firstPayload, + SignalWithStartWorkflowExecutionRequest.class, + SignalWithStartWorkflowExecutionRequest.class); + SignalWithStartWorkflowExecutionRequest secondWire = + secondConverter.fromPayload( + secondPayload, + SignalWithStartWorkflowExecutionRequest.class, + SignalWithStartWorkflowExecutionRequest.class); + assertEquals("first", firstWire.getWorkflowId()); + assertEquals("second", secondWire.getWorkflowId()); + assertEquals( + "first", + firstWire.getInput().getPayloads(0).getMetadataOrThrow("test-context").toStringUtf8()); + assertEquals( + "second", + secondWire.getInput().getPayloads(0).getMetadataOrThrow("test-context").toStringUtf8()); + assertThrows(IllegalStateException.class, SystemNexusDataConverter::currentDataConverter); + } + + @Test + public void failuresAndEncodedAttributesUseTheDestinationConverter() { + DataConverter user = + new CodecDataConverter( + DefaultDataConverter.STANDARD_INSTANCE, + Collections.singletonList(new ContextCodec(null)), + true) + .withContext(new WorkflowSerializationContext("destination", "target")); + SystemNexusDataConverter converter = new SystemNexusDataConverter(user); + io.temporal.api.failure.v1.Failure failure = + converter.exceptionToFailure( + io.temporal.failure.ApplicationFailure.newFailure("message", "type", "details")); + io.temporal.failure.ApplicationFailure decoded = + (io.temporal.failure.ApplicationFailure) converter.failureToException(failure); + assertEquals("message", decoded.getOriginalMessage()); + assertEquals("details", decoded.getDetails().get(0, String.class)); + } + + private static final class ContextCodec implements PayloadCodec { + private final String id; + + private ContextCodec(String id) { + this.id = id; + } + + @Nonnull + @Override + public PayloadCodec withContext(@Nonnull SerializationContext context) { + assertTrue(context instanceof WorkflowSerializationContext); + return new ContextCodec(((WorkflowSerializationContext) context).getWorkflowId()); + } + + @Nonnull + @Override + public List encode(@Nonnull List values) { + assertNotNull(id); + return values.stream() + .map( + value -> { + assertFalse(SystemNexusPayloads.isSystemPayload(value)); + assertFalse( + "Payload was encoded twice", + value.getMetadataMap().containsKey("test-context")); + return value.toBuilder() + .putMetadata("test-context", ByteString.copyFromUtf8(id)) + .build(); + }) + .collect(Collectors.toList()); + } + + @Nonnull + @Override + public List decode(@Nonnull List values) { + return values.stream() + .map( + value -> { + assertEquals(id, value.getMetadataOrThrow("test-context").toStringUtf8()); + return value.toBuilder().removeMetadata("test-context").build(); + }) + .collect(Collectors.toList()); + } + } +} 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..9c1807dcf6 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 @@ -36,6 +36,34 @@ /** Tests external storage message conversion. */ public class ExternalStorageRunnerTest { + @Test + public void systemEnvelopeOffloadsOnlyNestedPayloads() throws Exception { + TestStorageDriver driver = TestStorageDriver.named("system"); + ExternalStorageRunner transformer = transformer(driver, 0); + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest request = + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest.newBuilder() + .setInput(Payloads.newBuilder().addPayloads(payload("workflow"))) + .setSignalInput(Payloads.newBuilder().addPayloads(payload("signal"))) + .setSearchAttributes( + SearchAttributes.newBuilder().putIndexedFields("key", payload("search"))) + .build(); + Payload envelope = io.temporal.internal.payload.visitor.SystemNexusPayloads.pack(request); + Payloads original = Payloads.newBuilder().addPayloads(envelope).build(); + Payloads.Builder builder = original.toBuilder(); + transformer.store(builder, null, null, CancellationToken.none()); + Payload stored = builder.getPayloads(0); + assertTrue(io.temporal.internal.payload.visitor.SystemNexusPayloads.isSystemPayload(stored)); + assertNull(ExternalStorageReferences.tryParseReference(stored)); + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest nested = + io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest.parseFrom( + stored.getData()); + assertNotNull(ExternalStorageReferences.tryParseReference(nested.getInput().getPayloads(0))); + assertNotNull( + ExternalStorageReferences.tryParseReference(nested.getSignalInput().getPayloads(0))); + assertEquals(request.getSearchAttributes(), nested.getSearchAttributes()); + assertEquals(original, transformer.retrieve(builder.build(), CancellationToken.none())); + } + @Test public void storeAndRetrieveRoundTripsOverAMessage() throws Exception { TestStorageDriver driver = TestStorageDriver.named("d1"); diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/TemporalModelConvertersTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/TemporalModelConvertersTest.java new file mode 100644 index 0000000000..e3621df656 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/workflow/TemporalModelConvertersTest.java @@ -0,0 +1,69 @@ +package io.temporal.workflow; + +import static org.junit.Assert.*; + +import io.temporal.common.VersioningOverride; +import io.temporal.common.WorkerDeploymentVersion; +import io.temporal.common.converter.DataConverter; +import io.temporal.common.converter.DefaultDataConverter; +import io.temporal.internal.nexus.system.TemporalModelConverters; +import org.junit.Test; + +public class TemporalModelConvertersTest { + private static final DataConverter CONVERTER = DefaultDataConverter.STANDARD_INSTANCE; + + @Test + @SuppressWarnings("deprecation") + public void versioningOverridesRoundTripKnownShapes() { + WorkerDeploymentVersion version = new WorkerDeploymentVersion("deployment", "build"); + VersioningOverride.PinnedVersioningOverride pinned = + (VersioningOverride.PinnedVersioningOverride) + roundTrip(new VersioningOverride.PinnedVersioningOverride(version)); + assertEquals(version, pinned.getVersion()); + VersioningOverride.OneTimeVersioningOverride oneTime = + (VersioningOverride.OneTimeVersioningOverride) + roundTrip(new VersioningOverride.OneTimeVersioningOverride(version)); + assertEquals(version, oneTime.getTargetVersion()); + assertTrue( + roundTrip(new VersioningOverride.AutoUpgradeVersioningOverride()) + instanceof VersioningOverride.AutoUpgradeVersioningOverride); + VersioningOverride.PinnedVersioningOverride legacy = + (VersioningOverride.PinnedVersioningOverride) + TemporalModelConverters.versioningOverrideFromProto( + CONVERTER, + io.temporal.api.workflow.v1.VersioningOverride.newBuilder() + .setPinnedVersion("deployment.build") + .build()); + assertEquals(version, legacy.getVersion()); + } + + @Test + public void rejectsEmptyAndIncompleteVersioningOverrides() { + for (io.temporal.api.workflow.v1.VersioningOverride value : + new io.temporal.api.workflow.v1.VersioningOverride[] { + io.temporal.api.workflow.v1.VersioningOverride.getDefaultInstance(), + io.temporal.api.workflow.v1.VersioningOverride.newBuilder().setAutoUpgrade(false).build(), + io.temporal.api.workflow.v1.VersioningOverride.newBuilder() + .setPinned( + io.temporal.api.workflow.v1.VersioningOverride.PinnedOverride + .getDefaultInstance()) + .build(), + io.temporal.api.workflow.v1.VersioningOverride.newBuilder() + .setOneTime( + io.temporal.api.workflow.v1.VersioningOverride.OneTimeOverride + .getDefaultInstance()) + .build() + }) { + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> TemporalModelConverters.versioningOverrideFromProto(CONVERTER, value)); + assertEquals("Unknown versioning override proto shape", error.getMessage()); + } + } + + private static VersioningOverride roundTrip(VersioningOverride value) { + return TemporalModelConverters.versioningOverrideFromProto( + CONVERTER, TemporalModelConverters.versioningOverrideToProto(CONVERTER, value)); + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java index b0dd0eb354..fef64c1339 100644 --- a/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java +++ b/temporal-sdk/src/test/java/io/temporal/workflow/TypedWorkflowMethodCaptureTest.java @@ -6,8 +6,10 @@ import io.temporal.api.common.v1.WorkflowExecution; import io.temporal.common.CronSchedule; import io.temporal.common.MethodRetry; +import io.temporal.common.RetryOptions; import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; import io.temporal.common.metadata.WorkflowMethodType; +import io.temporal.internal.nexus.system.TemporalModelConverters; import io.temporal.internal.sync.ExternalWorkflowInvocationHandler; import io.temporal.internal.sync.ExternalWorkflowInvocationHandler.ProbeResult; import io.temporal.internal.sync.StubMarker; @@ -109,6 +111,41 @@ public void probesNamesArgumentsAnnotationsAndReturnTypesWithoutCommands() { normalSignal, assertThrows(RuntimeException.class, () -> target.signal("outside", 1))); } + @Test + public void mergesOriginalAnnotationsWithExplicitValuesWithoutPrematureDefaults() { + Target target = stub(Target.class, "target"); + Functions.Func1 method = target::start; + ProbeResult call = + ExternalWorkflowInvocationHandler.probe( + () -> method.apply("input"), WorkflowMethodType.WORKFLOW); + RetryOptions defaults = TemporalModelConverters.mergeMethodRetry(call, null); + assertEquals(java.time.Duration.ofSeconds(7), defaults.getInitialInterval()); + assertEquals(3, defaults.getMaximumAttempts()); + assertEquals(3.0, defaults.getBackoffCoefficient(), 0); + RetryOptions explicit = RetryOptions.newBuilder().setMaximumAttempts(9).build(); + RetryOptions merged = TemporalModelConverters.mergeMethodRetry(call, explicit); + assertEquals(9, merged.getMaximumAttempts()); + assertEquals(java.time.Duration.ofSeconds(7), merged.getInitialInterval()); + assertEquals(java.time.Duration.ofSeconds(100), merged.getMaximumInterval()); + assertEquals(3.0, merged.getBackoffCoefficient(), 0); + assertArrayEquals(new String[] {"NoRetry"}, merged.getDoNotRetry()); + assertNull(explicit.getInitialInterval()); + assertEquals("0 * * * *", TemporalModelConverters.mergeCronSchedule(call, null)); + assertEquals("1 * * * *", TemporalModelConverters.mergeCronSchedule(call, "1 * * * *")); + assertEquals("", TemporalModelConverters.mergeCronSchedule(call, "")); + + GenericTarget plain = stub(GenericTarget.class, "plain"); + Functions.Func> plainMethod = plain::start; + ProbeResult noAnnotations = + ExternalWorkflowInvocationHandler.probe( + () -> plainMethod.apply(), WorkflowMethodType.WORKFLOW); + assertNull(TemporalModelConverters.mergeMethodRetry(noAnnotations, null)); + assertSame(explicit, TemporalModelConverters.mergeMethodRetry(noAnnotations, explicit)); + assertNull(TemporalModelConverters.mergeCronSchedule(noAnnotations, null)); + assertEquals("", TemporalModelConverters.mergeCronSchedule(noAnnotations, "")); + verifyNoInteractions(outbound); + } + @Test public void rejectsMissingRepeatedAndWrongKindInvocations() { Target target = stub(Target.class, "target"); diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SignalWithStartWorkflowTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SignalWithStartWorkflowTest.java new file mode 100644 index 0000000000..80f487bcdc --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SignalWithStartWorkflowTest.java @@ -0,0 +1,406 @@ +package io.temporal.workflow.nexus; + +import static org.junit.Assert.*; + +import io.temporal.common.interceptors.*; +import io.temporal.testing.internal.SDKTestWorkflowRule; +import io.temporal.worker.WorkerFactoryOptions; +import io.temporal.workflow.*; +import io.temporal.workflow.SignalWithStartWorkflowRequest; +import io.temporal.workflow.SignalWithStartWorkflowResponse; +import org.junit.Rule; +import org.junit.Test; + +public class SignalWithStartWorkflowTest { + private final java.util.concurrent.atomic.AtomicInteger scheduledOperations = + new java.util.concurrent.atomic.AtomicInteger(); + + @Rule + public SDKTestWorkflowRule rule = + SDKTestWorkflowRule.newBuilder() + .setWorkflowTypes( + CallerImpl.class, IdentityCallerImpl.class, QueueDefaultsCallerImpl.class) + .setWorkerFactoryOptions( + WorkerFactoryOptions.newBuilder() + .setWorkerInterceptors( + new WorkerInterceptorBase() { + @Override + public WorkflowInboundCallsInterceptor interceptWorkflow( + WorkflowInboundCallsInterceptor next) { + return new WorkflowInboundCallsInterceptorBase(next) { + @Override + public void init(WorkflowOutboundCallsInterceptor outbound) { + super.init( + new WorkflowOutboundCallsInterceptorBase(outbound) { + @Override + public ExecuteNexusOperationOutput< + SignalWithStartWorkflowResponse> + executeSignalWithStartWorkflow( + ExecuteNexusOperationInput< + SignalWithStartWorkflowResponse> + input) { + SignalWithStartWorkflowRequest request = + (SignalWithStartWorkflowRequest) input.getArg(); + scheduledOperations.incrementAndGet(); + assertEquals("Target", request.getWorkflow()); + assertEquals( + Workflow.getInfo().getNamespace(), + request.getNamespace()); + assertEquals("notify", request.getSignal()); + assertEquals( + request.getWorkflowId().endsWith("queue-defaults") + ? Workflow.getInfo().getTaskQueue() + : "queue", + request.getTaskQueue()); + if (request.getWorkflowId().startsWith("typed")) { + assertEquals( + java.time.Duration.ofSeconds(7), + request.getRetryOptions().getInitialInterval()); + assertEquals( + request.getWorkflowId().equals("typed-overrides") + ? 9 + : 3, + request.getRetryOptions().getMaximumAttempts()); + assertEquals( + request.getWorkflowId().equals("typed-overrides") + ? "" + : "0 * * * *", + request.getCronSchedule()); + } else { + assertNull(request.getRetryOptions()); + assertNull(request.getCronSchedule()); + } + assertEquals( + io.temporal.api.enums.v1.WorkflowIdReusePolicy + .WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE, + request.getWorkflowIdReusePolicy()); + if (request.getWorkflowId().contains("defaults")) { + assertTrue(request.getArgs().isEmpty()); + assertTrue(request.getSignalArgs().isEmpty()); + } else { + assertEquals("input", request.getArgs().get(0)); + if (request.getWorkflowId().equals("arity6")) { + assertEquals( + java.util.Arrays.asList( + "input", + 2, + 3L, + true, + java.util.Collections.singletonList("nested"), + java.util.Collections.singletonMap("key", 4)), + request.getArgs()); + } + assertEquals("signal", request.getSignalArgs().get(0)); + assertEquals( + "summary", + request.getUserMetadata().getStaticSummary()); + assertEquals( + java.time.Duration.ofMinutes(3), + request.getWorkflowRunTimeout()); + } + return new ExecuteNexusOperationOutput<>( + Workflow.newPromise( + SignalWithStartWorkflowResponse.newBuilder() + .setRunId("run") + .build()), + Workflow.newPromise(() -> java.util.Optional.empty())); + } + }); + } + }; + } + }) + .build()) + .build(); + + @Test + public void generatedWorkflowMethodsReturnExternalStubs() { + assertEquals( + "sync:run,defaults:run,typed:run,typed-overrides:run,typed-defaults:run,arity6:run", + rule.newWorkflowStubTimeoutOptions(Caller.class).run()); + } + + @Test + public void optionsDeferWorkflowIdValidationUntilInvocation() { + assertThrows( + NullPointerException.class, + () -> + Workflow.signalWithStartWorkflow( + "Target", new Object[0], "notify", new Object[0], null)); + SignalWithStartWorkflowOptions withoutId = SignalWithStartWorkflowOptions.newBuilder().build(); + assertNull(withoutId.getWorkflowId()); + assertNull(withoutId.getTaskQueue()); + SignalWithStartWorkflowOptions options = + SignalWithStartWorkflowOptions.newBuilder() + .setWorkflowId("id") + .setTaskQueue("queue") + .build(); + assertEquals("id", options.getWorkflowId()); + assertEquals("queue", options.toBuilder().setWorkflowId("copy").build().getTaskQueue()); + } + + @Test + public void taskQueueDefaultsAtInvocationForTypedAndNameBasedCalls() { + assertEquals( + java.util.Arrays.asList("queue-defaults", "typed-queue-defaults"), + rule.newWorkflowStubTimeoutOptions(QueueDefaultsCaller.class).run()); + assertEquals(2, scheduledOperations.get()); + } + + @WorkflowInterface + public interface QueueDefaultsCaller { + @WorkflowMethod + java.util.List run(); + } + + public static class QueueDefaultsCallerImpl implements QueueDefaultsCaller { + @Override + public java.util.List run() { + SignalWithStartWorkflowOptions options = SignalWithStartWorkflowOptions.newBuilder().build(); + ExternalWorkflowStub untyped = + Workflow.signalWithStartWorkflow( + "Target", + new Object[0], + "notify", + new Object[0], + options.toBuilder().setWorkflowId("queue-defaults").build()); + EmptyTarget target = + Workflow.newExternalWorkflowStub(EmptyTarget.class, "typed-queue-defaults"); + ExternalWorkflowStub typed = + Workflow.signalWithStartWorkflow(target::start, target::signalValue, options); + assertNull(options.getWorkflowId()); + assertNull(options.getTaskQueue()); + return java.util.Arrays.asList( + untyped.getExecution().getWorkflowId(), typed.getExecution().getWorkflowId()); + } + } + + @WorkflowInterface + public interface TypedTarget { + @WorkflowMethod(name = "Target") + @io.temporal.common.MethodRetry(initialIntervalSeconds = 7, maximumAttempts = 3) + @io.temporal.common.CronSchedule("0 * * * *") + int start(String input); + + @SignalMethod(name = "notify") + @io.temporal.common.MethodRetry(maximumAttempts = 99) + @io.temporal.common.CronSchedule("signal-annotation-must-not-be-used") + void signalValue(String value); + } + + @WorkflowInterface + public interface EmptyTarget { + @WorkflowMethod(name = "Target") + @io.temporal.common.MethodRetry(initialIntervalSeconds = 7, maximumAttempts = 3) + @io.temporal.common.CronSchedule("0 * * * *") + void start(); + + @SignalMethod(name = "notify") + void signalValue(); + } + + @WorkflowInterface + public interface SixArgumentTarget { + @WorkflowMethod(name = "Target") + java.util.List start( + String first, + int second, + long third, + boolean fourth, + java.util.List fifth, + java.util.Map sixth); + + @SignalMethod(name = "notify") + void signalValue(String value); + } + + @WorkflowInterface + public interface Caller { + @WorkflowMethod + String run(); + } + + @Test + public void workflowReferenceDeterminesIdentityAndSignalBindingIsIgnored() { + assertEquals( + java.util.Arrays.asList("typed-identity-a", "typed-identity-b"), + rule.newWorkflowStubTimeoutOptions(IdentityCaller.class).run()); + assertEquals(2, scheduledOperations.get()); + } + + @WorkflowInterface + public interface IdentityCaller { + @WorkflowMethod + java.util.List run(); + } + + public static class IdentityCallerImpl implements IdentityCaller { + @Override + public java.util.List run() { + SignalWithStartWorkflowOptions options = + SignalWithStartWorkflowOptions.newBuilder() + .setTaskQueue("queue") + .setStaticSummary("summary") + .setWorkflowRunTimeout(java.time.Duration.ofMinutes(3)) + .build(); + TypedTarget first = Workflow.newExternalWorkflowStub(TypedTarget.class, "typed-identity-a"); + TypedTarget second = Workflow.newExternalWorkflowStub(TypedTarget.class, "typed-identity-b"); + TypedTarget signal = + Workflow.newExternalWorkflowStub( + TypedTarget.class, + io.temporal.api.common.v1.WorkflowExecution.newBuilder() + .setWorkflowId("ignored-signal-id") + .setRunId("ignored-signal-run") + .build()); + ExternalWorkflowStub a = + Workflow.signalWithStartWorkflow( + first::start, "input", signal::signalValue, "signal", options); + ExternalWorkflowStub b = + Workflow.signalWithStartWorkflow( + second::start, "input", signal::signalValue, "signal", options); + assertNull(options.getWorkflowId()); + assertThrows( + IllegalArgumentException.class, + () -> + Workflow.signalWithStartWorkflow( + first::start, + "input", + signal::signalValue, + "signal", + options.toBuilder().setWorkflowId("different-id").build())); + assertThrows( + IllegalArgumentException.class, + () -> + Workflow.signalWithStartWorkflow( + first::start, + "input", + signal::signalValue, + "signal", + options.toBuilder().setWorkflowId("").build())); + TypedTarget pinned = + Workflow.newExternalWorkflowStub( + TypedTarget.class, + io.temporal.api.common.v1.WorkflowExecution.newBuilder() + .setWorkflowId("typed-identity-a") + .setRunId("pinned-run") + .build()); + assertThrows( + IllegalArgumentException.class, + () -> + Workflow.signalWithStartWorkflow( + pinned::start, "input", signal::signalValue, "signal", options)); + TypedTarget missingId = Workflow.newExternalWorkflowStub(TypedTarget.class, ""); + assertThrows( + IllegalArgumentException.class, + () -> + Workflow.signalWithStartWorkflow( + missingId::start, "input", signal::signalValue, "signal", options)); + return java.util.Arrays.asList( + a.getExecution().getWorkflowId(), b.getExecution().getWorkflowId()); + } + } + + public static class CallerImpl implements Caller { + @Override + public String run() { + assertEquals( + "workflowId", + assertThrows( + NullPointerException.class, + () -> + Workflow.signalWithStartWorkflow( + "Target", + new Object[0], + "notify", + new Object[0], + SignalWithStartWorkflowOptions.newBuilder().build())) + .getMessage()); + SignalWithStartWorkflowOptions options = + SignalWithStartWorkflowOptions.newBuilder() + .setWorkflowId("sync") + .setTaskQueue("queue") + .setStaticSummary("summary") + .setWorkflowRunTimeout(java.time.Duration.ofMinutes(3)) + .build(); + ExternalWorkflowStub sync = + Workflow.signalWithStartWorkflow( + "Target", new Object[] {"input"}, "notify", new Object[] {"signal"}, options); + ExternalWorkflowStub defaults = + Workflow.signalWithStartWorkflow( + "Target", + new Object[0], + "notify", + new Object[0], + SignalWithStartWorkflowOptions.newBuilder() + .setWorkflowId("defaults") + .setTaskQueue("queue") + .build()); + SignalWithStartWorkflowOptions typedOptions = options; + TypedTarget target = Workflow.newExternalWorkflowStub(TypedTarget.class, "typed"); + ExternalWorkflowStub typed = + Workflow.signalWithStartWorkflow( + target::start, + "input", + target::signalValue, + "signal", + typedOptions.toBuilder().setWorkflowId("typed").build()); + ExternalWorkflowStub typedOverrides = + Workflow.signalWithStartWorkflow( + Workflow.newExternalWorkflowStub(TypedTarget.class, "typed-overrides")::start, + "input", + target::signalValue, + "signal", + typedOptions.toBuilder() + .setWorkflowId("typed-overrides") + .setRetryOptions( + io.temporal.common.RetryOptions.newBuilder().setMaximumAttempts(9).build()) + .setCronSchedule("") + .build()); + EmptyTarget empty = Workflow.newExternalWorkflowStub(EmptyTarget.class, "typed-defaults"); + ExternalWorkflowStub typedDefaults = + Workflow.signalWithStartWorkflow( + empty::start, + empty::signalValue, + SignalWithStartWorkflowOptions.newBuilder().setTaskQueue("queue").build()); + assertThrows( + NullPointerException.class, + () -> Workflow.signalWithStartWorkflow(empty::start, empty::signalValue, null)); + SixArgumentTarget six = Workflow.newExternalWorkflowStub(SixArgumentTarget.class, "arity6"); + ExternalWorkflowStub arity6 = + Workflow.signalWithStartWorkflow( + six::start, + "input", + 2, + 3L, + true, + java.util.Collections.singletonList("nested"), + java.util.Collections.singletonMap("key", 4), + six::signalValue, + "signal", + typedOptions.toBuilder().setWorkflowId("arity6").build()); + return sync.getExecution().getWorkflowId() + + ":" + + sync.getExecution().getRunId() + + "," + + defaults.getExecution().getWorkflowId() + + ":" + + defaults.getExecution().getRunId() + + "," + + typed.getExecution().getWorkflowId() + + ":" + + typed.getExecution().getRunId() + + "," + + typedOverrides.getExecution().getWorkflowId() + + ":" + + typedOverrides.getExecution().getRunId() + + "," + + typedDefaults.getExecution().getWorkflowId() + + ":" + + typedDefaults.getExecution().getRunId() + + "," + + arity6.getExecution().getWorkflowId() + + ":" + + arity6.getExecution().getRunId(); + } + } +} diff --git a/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SystemSignalWithStartIntegrationTest.java b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SystemSignalWithStartIntegrationTest.java new file mode 100644 index 0000000000..5e71d76e38 --- /dev/null +++ b/temporal-sdk/src/test/java/io/temporal/workflow/nexus/SystemSignalWithStartIntegrationTest.java @@ -0,0 +1,525 @@ +package io.temporal.workflow.nexus; + +import static org.junit.Assert.*; + +import com.google.protobuf.ByteString; +import io.temporal.api.common.v1.Payload; +import io.temporal.api.common.v1.Payloads; +import io.temporal.api.enums.v1.WorkflowIdConflictPolicy; +import io.temporal.api.history.v1.HistoryEvent; +import io.temporal.api.sdk.v1.ExternalStorageReference; +import io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest; +import io.temporal.client.WorkflowClientOptions; +import io.temporal.client.WorkflowStub; +import io.temporal.common.CancellationToken; +import io.temporal.common.context.ContextPropagator; +import io.temporal.common.converter.CodecDataConverter; +import io.temporal.common.converter.DefaultDataConverter; +import io.temporal.common.interceptors.WorkerInterceptorBase; +import io.temporal.common.interceptors.WorkflowInboundCallsInterceptor; +import io.temporal.common.interceptors.WorkflowInboundCallsInterceptorBase; +import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptor; +import io.temporal.common.interceptors.WorkflowOutboundCallsInterceptorBase; +import io.temporal.internal.payload.storage.ExternalStorageRunner; +import io.temporal.internal.payload.storage.TestStorageDriver; +import io.temporal.internal.payload.visitor.SystemNexusPayloads; +import io.temporal.payload.codec.PayloadCodec; +import io.temporal.payload.context.SerializationContext; +import io.temporal.payload.context.WorkflowSerializationContext; +import io.temporal.payload.storage.ExternalStorage; +import io.temporal.testing.CloudTestExclusion.RequiresCloudProvisioning; +import io.temporal.testing.CloudTestExclusionNote; +import io.temporal.testing.WorkflowReplayer; +import io.temporal.testing.internal.SDKTestWorkflowRule; +import io.temporal.testing.internal.TracingWorkerInterceptor; +import io.temporal.worker.WorkerFactoryOptions; +import io.temporal.workflow.*; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@CloudTestExclusionNote("Requires a server supporting the Temporal system Nexus workflow service.") +@Category(RequiresCloudProvisioning.class) +@RunWith(Parameterized.class) +public class SystemSignalWithStartIntegrationTest { + private static final TestContextPropagator LEGACY = new TestContextPropagator("legacy", false); + private static final TestContextPropagator ENCODED = new TestContextPropagator("encoded", true); + + @Parameterized.Parameters(name = "externalStorage={0}, batchCodec={1}") + public static Object[][] storageAndCodecModes() { + return new Object[][] {{false, false}, {true, false}, {false, true}, {true, true}}; + } + + private final boolean externalStorageEnabled; + private final boolean batchCodecEnabled; + private final TestStorageDriver storageDriver = TestStorageDriver.named("signal-with-start"); + private final ExternalStorage storage = + ExternalStorage.newBuilder().setDriver(storageDriver).setPayloadSizeThreshold(0).build(); + + @Rule public final SDKTestWorkflowRule rule; + + public SystemSignalWithStartIntegrationTest( + boolean externalStorageEnabled, boolean batchCodecEnabled) { + this.externalStorageEnabled = externalStorageEnabled; + this.batchCodecEnabled = batchCodecEnabled; + rule = + SDKTestWorkflowRule.newBuilder() + .setWorkflowTypes(CallerImpl.class, ConcurrentCallerImpl.class, TargetImpl.class) + .setWorkerFactoryOptions( + WorkerFactoryOptions.newBuilder() + .setWorkerInterceptors( + new WorkerInterceptorBase() { + @Override + public WorkflowInboundCallsInterceptor interceptWorkflow( + WorkflowInboundCallsInterceptor next) { + return new WorkflowInboundCallsInterceptorBase(next) { + @Override + public void init(WorkflowOutboundCallsInterceptor outbound) { + super.init( + new WorkflowOutboundCallsInterceptorBase(outbound) { + @Override + public ExecuteNexusOperationOutput< + SignalWithStartWorkflowResponse> + executeSignalWithStartWorkflow( + ExecuteNexusOperationInput< + SignalWithStartWorkflowResponse> + input) { + SignalWithStartWorkflowRequest request = + (SignalWithStartWorkflowRequest) input.getArg(); + Map headers = new HashMap<>(); + if (request.getHeaders() != null) + headers.putAll(request.getHeaders()); + headers.put( + "manual", + DefaultDataConverter.STANDARD_INSTANCE + .toPayload("manual-header") + .get()); + return super.executeSignalWithStartWorkflow( + new ExecuteNexusOperationInput<>( + input.getEndpoint(), + input.getService(), + input.getOperation(), + input.getResultClass(), + input.getResultType(), + request.toBuilder().setHeaders(headers).build(), + input.getOptions(), + input.getHeaders())); + } + + @Override + public + ExecuteNexusOperationOutput executeNexusOperation( + ExecuteNexusOperationInput input) { + throw new AssertionError( + "System operations must bypass ordinary Nexus interception"); + } + }); + } + }; + } + }, + new TracingWorkerInterceptor( + new TracingWorkerInterceptor.FilteredTrace() { + @Override + public boolean add(String event) { + assertFalse( + "Direct implementations must also bypass ordinary Nexus hooks", + event.startsWith("executeNexusOperation ")); + return super.add(event); + } + })) + .build()) + .setWorkflowClientOptions( + WorkflowClientOptions.newBuilder() + .setContextPropagators(Arrays.asList(LEGACY, ENCODED)) + .setExternalStorage(externalStorageEnabled ? storage : null) + .setDataConverter( + new CodecDataConverter( + DefaultDataConverter.STANDARD_INSTANCE, + Collections.singletonList( + new DestinationCodec(null, batchCodecEnabled)))) + .build()) + .build(); + } + + @Before + public void requireSystemService() { + Assume.assumeTrue( + "System Nexus requires a supporting external server", + SDKTestWorkflowRule.useExternalService); + } + + @Test + public void startsThenSignalsTheExistingExecutionAndReplays() throws Exception { + Caller caller = rule.newWorkflowStubTimeoutOptions(Caller.class); + String target = caller.run(); + assertEquals( + "start:first:second", + rule.getWorkflowClient().newUntypedWorkflowStub(target).getResult(String.class)); + assertStorageUsed(); + String callerId = + io.temporal.client.WorkflowStub.fromTyped(caller).getExecution().getWorkflowId(); + WorkflowReplayer.replayWorkflowExecution(rule.getExecutionHistory(callerId), rule.getWorker()); + replayTarget(target); + } + + @Test + public void concurrentCallsUseDestinationCodecContextAndPreserveOuterEnvelopes() + throws Exception { + ConcurrentCaller caller = rule.newWorkflowStubTimeoutOptions(ConcurrentCaller.class); + List targets = caller.run(); + for (String target : targets) { + assertEquals( + "start:first:second", + rule.getWorkflowClient().newUntypedWorkflowStub(target).getResult(String.class)); + } + assertStorageUsed(); + String callerId = WorkflowStub.fromTyped(caller).getExecution().getWorkflowId(); + int scheduled = 0; + for (HistoryEvent event : rule.getExecutionHistory(callerId).getEvents()) { + if (!event.hasNexusOperationScheduledEventAttributes()) continue; + scheduled++; + Payload envelope = event.getNexusOperationScheduledEventAttributes().getInput(); + assertTrue(SystemNexusPayloads.isSystemPayload(envelope)); + assertFalse(envelope.containsMetadata(DestinationCodec.KEY)); + assertEquals(0, envelope.getExternalPayloadsCount()); + SignalWithStartWorkflowExecutionRequest request = + SignalWithStartWorkflowExecutionRequest.parseFrom(envelope.getData()); + assertTrue(targets.contains(request.getWorkflowId())); + String expected = request.getNamespace() + "/" + request.getWorkflowId(); + List embedded = embeddedPayloads(request); + assertEquals(batchCodecEnabled ? 5 : 7, embedded.size()); + assertEquals(batchCodecEnabled ? 1 : 3, request.getInput().getPayloadsCount()); + assertEquals(3, request.getHeader().getFieldsCount()); + if (externalStorageEnabled) { + List offloaded = new ArrayList<>(embedded); + offloaded.addAll(request.getHeader().getFieldsMap().values()); + for (Payload payload : offloaded) { + assertEquals( + ExternalStorageReference.getDescriptor().getFullName(), + payload.getMetadataOrThrow("messageType").toStringUtf8()); + assertTrue(payload.getExternalPayloadsCount() > 0); + } + request = + ExternalStorageRunner.create(storage, request.getNamespace()) + .retrieve(request, CancellationToken.none()); + embedded = embeddedPayloads(request); + } + for (Payload payload : embedded) { + assertEquals(expected, payload.getMetadataOrThrow(DestinationCodec.KEY).toStringUtf8()); + } + assertEquals( + DefaultDataConverter.STANDARD_INSTANCE.toPayload("manual-header").get(), + request.getHeader().getFieldsOrThrow("manual")); + assertEquals( + DefaultDataConverter.STANDARD_INSTANCE.toPayload("legacy-context").get(), + request.getHeader().getFieldsOrThrow("legacy")); + Payload encoded = request.getHeader().getFieldsOrThrow("encoded"); + assertEquals(expected, encoded.getMetadataOrThrow(DestinationCodec.KEY).toStringUtf8()); + Payload decoded = + new DestinationCodec(expected, batchCodecEnabled) + .decode(Collections.singletonList(encoded)) + .get(0); + assertEquals( + "encoded-context", + DefaultDataConverter.STANDARD_INSTANCE.fromPayload(decoded, String.class, String.class)); + } + assertEquals(4, scheduled); + WorkflowReplayer.replayWorkflowExecution(rule.getExecutionHistory(callerId), rule.getWorker()); + for (String target : targets) { + replayTarget(target); + } + } + + private void replayTarget(String workflowId) throws Exception { + int retrievesBeforeReplay = storageDriver.retrieves.get(); + WorkflowReplayer.replayWorkflowExecution( + rule.getExecutionHistory(workflowId), rule.getWorker()); + if (externalStorageEnabled) { + assertTrue( + "Target replay must retrieve the stored workflow and signal inputs", + storageDriver.retrieves.get() > retrievesBeforeReplay); + } + } + + private void assertStorageUsed() { + if (externalStorageEnabled) { + assertTrue("Workflow execution must offload payloads", storageDriver.stores.get() > 0); + assertTrue("Workflow execution must retrieve payloads", storageDriver.retrieves.get() > 0); + for (Payload stored : storageDriver.storedPayloads()) { + assertFalse( + "The outer system envelope must remain inline", + SystemNexusPayloads.isSystemPayload(stored)); + } + } else { + assertEquals(0, storageDriver.stores.get()); + assertEquals(0, storageDriver.retrieves.get()); + } + } + + private static List embeddedPayloads(SignalWithStartWorkflowExecutionRequest request) { + List payloads = new ArrayList<>(); + payloads.addAll(request.getInput().getPayloadsList()); + payloads.addAll(request.getSignalInput().getPayloadsList()); + payloads.addAll(request.getMemo().getFieldsMap().values()); + payloads.add(request.getUserMetadata().getSummary()); + payloads.add(request.getUserMetadata().getDetails()); + return payloads; + } + + @WorkflowInterface + public interface ConcurrentCaller { + @WorkflowMethod + List run(); + } + + public static class ConcurrentCallerImpl implements ConcurrentCaller { + @Override + public List run() { + List targets = + Arrays.asList( + Workflow.getInfo().getWorkflowId() + "-first", + Workflow.getInfo().getWorkflowId() + "-second"); + List> calls = new ArrayList<>(); + for (String id : targets) { + calls.add( + Async.procedure( + () -> { + installCallerContext(); + SignalWithStartWorkflowOptions options = + SignalWithStartWorkflowOptions.newBuilder() + .setTaskQueue(Workflow.getInfo().getTaskQueue()) + .setCronSchedule("") + .setWorkflowIdConflictPolicy( + WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING) + .setMemo(Collections.singletonMap("memo", "memo-value")) + .setStaticSummary("summary") + .setStaticDetails("details") + .build(); + Target target = Workflow.newExternalWorkflowStub(Target.class, id); + Workflow.signalWithStartWorkflow( + target::run, + "start", + (String) null, + "extra", + target::notifySignal, + "first", + options); + Workflow.signalWithStartWorkflow( + "SystemSignalTarget", + new Object[] {"ignored", null, "extra"}, + "notifySignal", + new Object[] {"second"}, + options.toBuilder().setWorkflowId(id).build()); + })); + } + Promise.allOf(calls).get(); + return targets; + } + } + + private static void installCallerContext() { + LEGACY.setCurrentContext("legacy-context"); + ENCODED.setCurrentContext("encoded-context"); + } + + private static final class TestContextPropagator implements ContextPropagator { + private final String name; + private final boolean encoded; + private final ThreadLocal current = new ThreadLocal<>(); + + private TestContextPropagator(String name, boolean encoded) { + this.name = name; + this.encoded = encoded; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean encodeHeaders() { + return encoded; + } + + @Override + public Map serializeContext(Object context) { + return context == null + ? Collections.emptyMap() + : Collections.singletonMap( + name, DefaultDataConverter.STANDARD_INSTANCE.toPayload(context).get()); + } + + @Override + public Object deserializeContext(Map context) { + Payload payload = context.get(name); + if (payload == null) return null; + assertFalse( + "Propagator must receive its decoded header", + payload.containsMetadata(DestinationCodec.KEY)); + return DefaultDataConverter.STANDARD_INSTANCE.fromPayload( + payload, String.class, String.class); + } + + @Override + public Object getCurrentContext() { + return current.get(); + } + + @Override + public void setCurrentContext(Object context) { + current.set((String) context); + } + } + + private static final class DestinationCodec implements PayloadCodec { + static final String KEY = "test-destination"; + private static final ByteString BATCH_ENCODING = ByteString.copyFromUtf8("test/batch"); + private final String destination; + private final boolean packBatches; + + DestinationCodec(String destination, boolean packBatches) { + this.destination = destination; + this.packBatches = packBatches; + } + + @Nonnull + @Override + public PayloadCodec withContext(@Nonnull SerializationContext context) { + if (!(context instanceof WorkflowSerializationContext)) return this; + WorkflowSerializationContext workflow = (WorkflowSerializationContext) context; + return new DestinationCodec( + workflow.getNamespace() + "/" + workflow.getWorkflowId(), packBatches); + } + + @Nonnull + @Override + public List encode(@Nonnull List payloads) { + List encoded = + payloads.stream() + .map( + payload -> { + rejectEnvelope(payload); + assertFalse("Payload encoded twice", payload.containsMetadata(KEY)); + return destination == null + ? payload + : payload.toBuilder() + .putMetadata(KEY, ByteString.copyFromUtf8(destination)) + .build(); + }) + .collect(Collectors.toList()); + if (!packBatches || encoded.size() <= 1) return encoded; + Payload.Builder batch = + Payload.newBuilder() + .putMetadata("encoding", BATCH_ENCODING) + .setData(Payloads.newBuilder().addAllPayloads(encoded).build().toByteString()); + if (destination != null) batch.putMetadata(KEY, ByteString.copyFromUtf8(destination)); + return Collections.singletonList(batch.build()); + } + + @Nonnull + @Override + public List decode(@Nonnull List payloads) { + if (payloads.size() == 1 + && BATCH_ENCODING.equals(payloads.get(0).getMetadataMap().get("encoding"))) { + try { + payloads = Payloads.parseFrom(payloads.get(0).getData()).getPayloadsList(); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw new IllegalArgumentException("Invalid batch payload", e); + } + } + return payloads.stream() + .map( + payload -> { + rejectEnvelope(payload); + if (!payload.containsMetadata(KEY)) return payload; + assertEquals(destination, payload.getMetadataOrThrow(KEY).toStringUtf8()); + return payload.toBuilder().removeMetadata(KEY).build(); + }) + .collect(Collectors.toList()); + } + + private static void rejectEnvelope(Payload payload) { + assertFalse( + "System envelope passed to the user codec", SystemNexusPayloads.isSystemPayload(payload)); + ByteString type = payload.getMetadataMap().get("messageType"); + assertFalse( + "Unmarked system response passed to the user codec", + type != null + && type.toStringUtf8() + .startsWith("temporal.api.workflowservice.v1.SignalWithStartWorkflowExecution")); + } + } + + @WorkflowInterface + public interface Target { + @WorkflowMethod(name = "SystemSignalTarget") + @io.temporal.common.MethodRetry(initialIntervalSeconds = 1, maximumAttempts = 3) + @io.temporal.common.CronSchedule("0 * * * *") + String run(String initial, String nullable, String extra); + + @SignalMethod + void notifySignal(String value); + } + + public static class TargetImpl implements Target { + private final java.util.List signals = new java.util.ArrayList<>(); + + @Override + public String run(String initial, String nullable, String extra) { + assertNull(nullable); + assertEquals("extra", extra); + assertEquals("legacy-context", LEGACY.getCurrentContext()); + assertEquals("encoded-context", ENCODED.getCurrentContext()); + Workflow.await(() -> signals.size() == 2); + return initial + ":" + String.join(":", signals); + } + + @Override + public void notifySignal(String value) { + assertEquals("legacy-context", LEGACY.getCurrentContext()); + assertEquals("encoded-context", ENCODED.getCurrentContext()); + signals.add(value); + } + } + + @WorkflowInterface + public interface Caller { + @WorkflowMethod + String run(); + } + + public static class CallerImpl implements Caller { + @Override + public String run() { + installCallerContext(); + String id = Workflow.getInfo().getWorkflowId() + "-target"; + SignalWithStartWorkflowOptions options = + SignalWithStartWorkflowOptions.newBuilder() + .setCronSchedule("") + .setWorkflowIdConflictPolicy( + WorkflowIdConflictPolicy.WORKFLOW_ID_CONFLICT_POLICY_USE_EXISTING) + .build(); + Target target = Workflow.newExternalWorkflowStub(Target.class, id); + ExternalWorkflowStub external = + Workflow.signalWithStartWorkflow( + target::run, "start", (String) null, "extra", target::notifySignal, "first", options); + assertEquals(id, external.getExecution().getWorkflowId()); + Workflow.signalWithStartWorkflow( + "SystemSignalTarget", + new Object[] {"ignored", null, "extra"}, + "notifySignal", + new Object[] {"second"}, + options.toBuilder().setWorkflowId(id).build()); + return id; + } + } +} diff --git a/temporal-serviceclient/build.gradle b/temporal-serviceclient/build.gradle index b698e1dbe6..b665f61721 100644 --- a/temporal-serviceclient/build.gradle +++ b/temporal-serviceclient/build.gradle @@ -149,15 +149,19 @@ sourceSets { dependencies { payloadGeneratorsImplementation "com.google.protobuf:protobuf-java:$protoVersion" + testImplementation sourceSets.payloadGenerators.output } def generatedPayloadVisitorDir = layout.buildDirectory.dir('generated/payloadvisitor/java') def generatePayloadVisitor = tasks.register('generatePayloadVisitor', JavaExec) { dependsOn 'compilePayloadGeneratorsJava', 'generateProto' + mustRunAfter ':temporal-sdk:generateNexusSystemApi' classpath = sourceSets.payloadGenerators.runtimeClasspath mainClass = 'io.temporal.internal.payload.visitor.gen.PayloadVisitorGenerator' - args apiDescriptorSet.get().asFile.absolutePath, generatedPayloadVisitorDir.get().asFile.absolutePath + def systemRoots = project(':temporal-sdk').file('src/main/generated/io/temporal/workflow/system-nexus-roots.txt') + args apiDescriptorSet.get().asFile.absolutePath, generatedPayloadVisitorDir.get().asFile.absolutePath, systemRoots.absolutePath + inputs.file(systemRoots) inputs.file(apiDescriptorSet) inputs.files(sourceSets.payloadGenerators.runtimeClasspath) outputs.dir(generatedPayloadVisitorDir) diff --git a/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/SystemNexusPayloads.java b/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/SystemNexusPayloads.java new file mode 100644 index 0000000000..03eed8a3c6 --- /dev/null +++ b/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/SystemNexusPayloads.java @@ -0,0 +1,49 @@ +package io.temporal.internal.payload.visitor; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import io.temporal.api.common.v1.Payload; + +/** Fixed binary protobuf envelopes used by Temporal system Nexus operations. */ +public final class SystemNexusPayloads { + private static final String MARKER = "__temporal_system_payload"; + private static final ByteString TRUE = ByteString.copyFromUtf8("true"); + private static final ByteString ENCODING = ByteString.copyFromUtf8("binary/protobuf"); + + private SystemNexusPayloads() {} + + public static boolean isSystemPayload(Payload payload) { + return TRUE.equals(payload.getMetadataMap().get(MARKER)); + } + + public static Payload pack(Message message) { + return Payload.newBuilder() + .putMetadata(MARKER, TRUE) + .putMetadata("encoding", ENCODING) + .putMetadata( + "messageType", ByteString.copyFromUtf8(message.getDescriptorForType().getFullName())) + .setData(message.toByteString()) + .build(); + } + + public static Message.Builder unpack(Payload payload) { + // The marker controls generic visitation. Server responses use the same binary envelope + // without the marker and are decoded in the system operation's known converter scope. + if (!ENCODING.equals(payload.getMetadataMap().get("encoding"))) { + throw new VisitorException("Invalid Temporal system payload encoding"); + } + ByteString type = payload.getMetadataMap().get("messageType"); + String name = type == null ? "" : type.toStringUtf8(); + MessageRegistryEntry entry = GeneratedPayloadVisitor.SYSTEM_ROOTS.get(name); + if (entry == null) { + throw new VisitorException("Unknown Temporal system payload: " + name); + } + Message.Builder builder = entry.newBuilder.get(); + try { + return builder.mergeFrom(payload.getData()); + } catch (InvalidProtocolBufferException e) { + throw new VisitorException("Failed to unpack Temporal system payload: " + name, e); + } + } +} diff --git a/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/Traversal.java b/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/Traversal.java index ffbdd712ce..570d8bd7c0 100644 --- a/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/Traversal.java +++ b/temporal-serviceclient/src/main/java/io/temporal/internal/payload/visitor/Traversal.java @@ -82,7 +82,27 @@ void exit(Object previous) { /** Record a visit of a payload sequence (a {@code Payloads} or {@code repeated Payload}). */ void payloads(List batch, Consumer> writeBack) { + if (batch.stream().anyMatch(SystemNexusPayloads::isSystemPayload)) { + List result = new ArrayList<>(); + // Keep ordinary sequences batched: codecs may change their cardinality. + int start = 0; + for (int i = 0; i < batch.size(); i++) { + if (SystemNexusPayloads.isSystemPayload(batch.get(i))) { + if (start < i) { + payloads(batch.subList(start, i), result::addAll); + } + systemPayload(batch.get(i), result::add); + start = i + 1; + } + } + if (start < batch.size()) { + payloads(batch.subList(start, batch.size()), result::addAll); + } + deferWriteBack(() -> writeBack.accept(result)); + return; + } if (payloadVisitor == null) { + deferWriteBack(() -> writeBack.accept(batch)); return; } LeafJob job = new LeafJob(batch, currentContext, false); @@ -92,6 +112,10 @@ void payloads(List batch, Consumer> writeBack) { /** The visitor must return exactly one payload (checked in {@link #record}). */ void singlePayload(Payload value, Consumer writeBack) { + if (SystemNexusPayloads.isSystemPayload(value)) { + systemPayload(value, writeBack); + return; + } if (payloadVisitor == null) { return; } @@ -100,6 +124,13 @@ void singlePayload(Payload value, Consumer writeBack) { writeBacks.add(() -> writeBack.accept(job.result.get(0))); } + private void systemPayload(Payload value, Consumer writeBack) { + Message.Builder inner = SystemNexusPayloads.unpack(value); + dispatch(inner); + deferWriteBack( + () -> writeBack.accept(value.toBuilder().setData(inner.build().toByteString()).build())); + } + /** Applied after all visits, single-threaded, in walk order. */ void deferWriteBack(Runnable writeBack) { writeBacks.add(writeBack); diff --git a/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/gen/ProtoClosure.java b/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/gen/ProtoClosure.java index 9d71f8e16c..c7597fd6eb 100644 --- a/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/gen/ProtoClosure.java +++ b/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/gen/ProtoClosure.java @@ -48,7 +48,27 @@ public boolean reaches(Descriptor d) { /** Builds the closure and payload-reachability set from the given seed file descriptors. */ public static ProtoClosure of(List seeds) { + return of(seeds, java.util.Collections.emptyList()); + } + + /** + * Adds message roots and their reachable fields without requiring their files to be service + * seeds. + */ + public static ProtoClosure of(List seeds, List roots) { List all = collectMessages(fileClosure(seeds)); + Set seen = new HashSet<>(); + for (Descriptor descriptor : all) seen.add(descriptor.getFullName()); + Deque queue = new ArrayDeque<>(roots); + while (!queue.isEmpty()) { + Descriptor descriptor = queue.remove(); + if (!seen.add(descriptor.getFullName())) continue; + if (!descriptor.getOptions().getMapEntry()) all.add(descriptor); + for (FieldDescriptor field : descriptor.getFields()) { + if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) + queue.add(field.getMessageType()); + } + } return new ProtoClosure(all, computeReachability(all)); } diff --git a/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/visitor/gen/PayloadVisitorGenerator.java b/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/visitor/gen/PayloadVisitorGenerator.java index bbe19c1594..87e807ed0c 100644 --- a/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/visitor/gen/PayloadVisitorGenerator.java +++ b/temporal-serviceclient/src/payloadGenerators/java/io/temporal/internal/payload/visitor/gen/PayloadVisitorGenerator.java @@ -87,29 +87,55 @@ public static void main(String[] args) throws Exception { throw new IllegalArgumentException( "usage: PayloadVisitorGenerator "); } - new PayloadVisitorGenerator().run(Paths.get(args[0]), Paths.get(args[1])); + new PayloadVisitorGenerator() + .run(Paths.get(args[0]), Paths.get(args[1]), args.length > 2 ? Paths.get(args[2]) : null); } private ProtoClosure closure; + private final java.util.Set systemRoots = new java.util.TreeSet<>(); void run(Path descriptorSetFile, Path outputRoot) throws IOException, DescriptorValidationException { + run(descriptorSetFile, outputRoot, null); + } + + void run(Path descriptorSetFile, Path outputRoot, Path systemRootsFile) + throws IOException, DescriptorValidationException { Map files = ProtoDescriptorSets.load(descriptorSetFile); + if (systemRootsFile != null) { + for (String line : Files.readAllLines(systemRootsFile, StandardCharsets.UTF_8)) { + if (!line.trim().isEmpty()) systemRoots.add(line.trim()); + } + } List seeds = Arrays.asList( ProtoDescriptorSets.require(files, WORKFLOW_SERVICE_PROTO), ProtoDescriptorSets.require(files, OPERATOR_SERVICE_PROTO)); - this.closure = ProtoClosure.of(seeds); + Map messages = new TreeMap<>(); + for (FileDescriptor file : files.values()) { + for (Descriptor descriptor : file.getMessageTypes()) indexMessages(descriptor, messages); + } + List roots = new ArrayList<>(); + for (String name : systemRoots) { + Descriptor root = messages.get(name); + if (root == null) throw new IllegalStateException("Unknown system Nexus root: " + name); + roots.add(root); + } + this.closure = ProtoClosure.of(seeds, roots); // Deterministic output order, keyed by descriptor full name. Map emitted = new TreeMap<>(); for (Descriptor d : closure.allMessages) { - if (reaches(d)) { + if (reaches(d) || systemRoots.contains(d.getFullName())) { emitted.put(d.getFullName(), d); } } + for (String root : systemRoots) { + if (!emitted.containsKey(root)) + throw new IllegalStateException("Unknown system Nexus root: " + root); + } String source = emit(emitted); Path dir = outputRoot; @@ -122,6 +148,11 @@ void run(Path descriptorSetFile, Path outputRoot) System.out.println("PayloadVisitorGenerator: wrote " + emitted.size() + " visitors to " + out); } + private static void indexMessages(Descriptor descriptor, Map messages) { + messages.put(descriptor.getFullName(), descriptor); + for (Descriptor nested : descriptor.getNestedTypes()) indexMessages(nested, messages); + } + // --- Reachability + classification --- /** Whether {@code d} can transitively contain a payload; delegates to the shared closure. */ @@ -186,9 +217,22 @@ private String emit(Map emitted) { sb.append("final class ").append(OUTPUT_CLASS).append(" {\n"); sb.append(" private ").append(OUTPUT_CLASS).append("() {}\n\n"); + sb.append(" private static Map buildSystemRoots() {\n"); + sb.append(" Map m = new HashMap<>();\n"); + for (String root : systemRoots) { + sb.append(" m.put(\"") + .append(root) + .append("\", REGISTRY.get(\"") + .append(root) + .append("\"));\n"); + } + sb.append(" return m;\n }\n"); + List list = new ArrayList<>(emitted.values()); sb.append(" static final Map REGISTRY = buildRegistry();\n\n"); + sb.append( + " static final Map SYSTEM_ROOTS = buildSystemRoots();\n"); sb.append(" private static Map buildRegistry() {\n"); sb.append(" Map m = new HashMap<>(") .append(Math.max(16, list.size() * 2)) diff --git a/temporal-serviceclient/src/test/java/io/temporal/internal/payload/gen/ProtoClosureRootTest.java b/temporal-serviceclient/src/test/java/io/temporal/internal/payload/gen/ProtoClosureRootTest.java new file mode 100644 index 0000000000..f5913e59bf --- /dev/null +++ b/temporal-serviceclient/src/test/java/io/temporal/internal/payload/gen/ProtoClosureRootTest.java @@ -0,0 +1,54 @@ +package io.temporal.internal.payload.gen; + +import static org.junit.Assert.*; + +import com.google.protobuf.DescriptorProtos.*; +import com.google.protobuf.Descriptors.*; +import io.temporal.api.common.v1.Payload; +import java.util.Arrays; +import java.util.Collections; +import org.junit.Test; + +public class ProtoClosureRootTest { + @Test + public void explicitRootsDiscoverTheirChildrenWithoutServiceSeeds() throws Exception { + String payloadFile = Payload.getDescriptor().getFile().getName(); + FileDescriptor file = + FileDescriptor.buildFrom( + FileDescriptorProto.newBuilder() + .setName("explicit-roots.proto") + .setPackage("temporal.api.test.v1") + .setSyntax("proto3") + .addDependency(payloadFile) + .addMessageType(DescriptorProto.newBuilder().setName("EmptyResponse")) + .addMessageType( + DescriptorProto.newBuilder() + .setName("Request") + .addField( + FieldDescriptorProto.newBuilder() + .setName("child") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".temporal.api.test.v1.Child"))) + .addMessageType( + DescriptorProto.newBuilder() + .setName("Child") + .addField( + FieldDescriptorProto.newBuilder() + .setName("payload") + .setNumber(1) + .setType(FieldDescriptorProto.Type.TYPE_MESSAGE) + .setTypeName(".temporal.api.common.v1.Payload"))) + .build(), + new FileDescriptor[] {Payload.getDescriptor().getFile()}); + Descriptor request = file.findMessageTypeByName("Request"); + Descriptor empty = file.findMessageTypeByName("EmptyResponse"); + Descriptor child = file.findMessageTypeByName("Child"); + ProtoClosure closure = ProtoClosure.of(Collections.emptyList(), Arrays.asList(request, empty)); + assertTrue(closure.allMessages.contains(empty)); + assertTrue(closure.allMessages.contains(child)); + assertTrue(closure.reaches(request)); + assertTrue(closure.reaches(child)); + assertFalse(closure.reaches(empty)); + } +} diff --git a/temporal-serviceclient/src/test/java/io/temporal/internal/payload/visitor/SystemNexusPayloadTest.java b/temporal-serviceclient/src/test/java/io/temporal/internal/payload/visitor/SystemNexusPayloadTest.java new file mode 100644 index 0000000000..92def6ebc1 --- /dev/null +++ b/temporal-serviceclient/src/test/java/io/temporal/internal/payload/visitor/SystemNexusPayloadTest.java @@ -0,0 +1,96 @@ +package io.temporal.internal.payload.visitor; + +import static org.junit.Assert.*; + +import com.google.protobuf.ByteString; +import io.temporal.api.common.v1.Payload; +import io.temporal.api.common.v1.Payloads; +import io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionRequest; +import io.temporal.api.workflowservice.v1.SignalWithStartWorkflowExecutionResponse; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import org.junit.Test; + +public class SystemNexusPayloadTest { + private static Payload payload(String value) { + return Payload.newBuilder().setData(ByteString.copyFromUtf8(value)).build(); + } + + @Test + public void visitsNestedSequencesBeforeRepacking() throws Exception { + SignalWithStartWorkflowExecutionRequest request = + SignalWithStartWorkflowExecutionRequest.newBuilder() + .setInput(Payloads.newBuilder().addPayloads(payload("workflow"))) + .setSignalInput(Payloads.newBuilder().addPayloads(payload("signal"))) + .build(); + CompletableFuture> workflow = new CompletableFuture<>(); + Payloads outer = Payloads.newBuilder().addPayloads(SystemNexusPayloads.pack(request)).build(); + CompletableFuture result = + PayloadVisitors.visit( + outer, + PayloadVisitorOptions.newBuilder( + (context, values) -> { + if (values.get(0).getData().toStringUtf8().equals("workflow")) { + return workflow; + } + return CompletableFuture.completedFuture( + Collections.singletonList(payload("SIGNAL"))); + }) + .build()); + assertFalse(result.isDone()); + workflow.complete(Arrays.asList(payload("ONE"), payload("TWO"))); + SignalWithStartWorkflowExecutionRequest decoded = + SignalWithStartWorkflowExecutionRequest.parseFrom(result.join().getPayloads(0).getData()); + assertEquals(2, decoded.getInput().getPayloadsCount()); + assertEquals("SIGNAL", decoded.getSignalInput().getPayloads(0).getData().toStringUtf8()); + assertEquals( + outer.getPayloads(0).getMetadataMap(), result.join().getPayloads(0).getMetadataMap()); + } + + @Test + public void handlesPayloadFreeResponses() { + Payload response = + SystemNexusPayloads.pack( + SignalWithStartWorkflowExecutionResponse.newBuilder().setRunId("run").build()); + Payloads outer = Payloads.newBuilder().addPayloads(response).build(); + assertEquals( + outer, + PayloadVisitors.visit( + outer, + PayloadVisitorOptions.newBuilder( + (context, values) -> { + throw new AssertionError("Outer envelope was visited"); + }) + .build()) + .join()); + } + + @Test + public void rejectsUnknownAndMalformedMarkedPayloads() { + Payload unknown = + SystemNexusPayloads.pack(SignalWithStartWorkflowExecutionRequest.getDefaultInstance()) + .toBuilder() + .putMetadata("messageType", ByteString.copyFromUtf8("unknown.Message")) + .build(); + Payload malformed = + SystemNexusPayloads.pack(SignalWithStartWorkflowExecutionRequest.getDefaultInstance()) + .toBuilder() + .setData(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + for (Payload value : Arrays.asList(unknown, malformed)) { + CompletionException error = + assertThrows( + CompletionException.class, + () -> + PayloadVisitors.visit( + Payloads.newBuilder().addPayloads(value).build(), + PayloadVisitorOptions.newBuilder( + (context, values) -> CompletableFuture.completedFuture(values)) + .build()) + .join()); + assertTrue(error.getCause() instanceof VisitorException); + } + } +} diff --git a/temporal-testing/src/main/java/io/temporal/testing/TestActivityEnvironmentInternal.java b/temporal-testing/src/main/java/io/temporal/testing/TestActivityEnvironmentInternal.java index 1329f4b8a2..4749a9f852 100644 --- a/temporal-testing/src/main/java/io/temporal/testing/TestActivityEnvironmentInternal.java +++ b/temporal-testing/src/main/java/io/temporal/testing/TestActivityEnvironmentInternal.java @@ -269,7 +269,9 @@ public void close() { mockServer.awaitTermination(5, TimeUnit.SECONDS); } - private class TestActivityExecutor implements WorkflowOutboundCallsInterceptor { + private class TestActivityExecutor + extends io.temporal.workflow.SystemNexusWorkflowOutboundInterceptor.Terminal + implements WorkflowOutboundCallsInterceptor { @Override public ActivityOutput executeActivity(ActivityInput i) { @@ -367,6 +369,21 @@ public ChildWorkflowOutput executeChildWorkflow(ChildWorkflowInput inp throw new UnsupportedOperationException("not implemented"); } + @Override + protected Map propagateSystemNexusHeaders( + Map headers, + io.temporal.payload.context.SerializationContext context) { + throw new UnsupportedOperationException( + "Workflow operations are not available in activities"); + } + + @Override + protected ExecuteNexusOperationOutput executeSystemNexusOperation( + ExecuteNexusOperationInput input) { + throw new UnsupportedOperationException( + "Workflow operations are not available in activities"); + } + @Override public ExecuteNexusOperationOutput executeNexusOperation( ExecuteNexusOperationInput input) { diff --git a/temporal-testing/src/main/java/io/temporal/testing/internal/TracingWorkerInterceptor.java b/temporal-testing/src/main/java/io/temporal/testing/internal/TracingWorkerInterceptor.java index d4b54cb33f..6a1bf5ecd4 100644 --- a/temporal-testing/src/main/java/io/temporal/testing/internal/TracingWorkerInterceptor.java +++ b/temporal-testing/src/main/java/io/temporal/testing/internal/TracingWorkerInterceptor.java @@ -172,6 +172,14 @@ public ChildWorkflowOutput executeChildWorkflow(ChildWorkflowInput inp return next.executeChildWorkflow(input); } + @Override + public ExecuteNexusOperationOutput + executeSignalWithStartWorkflow( + ExecuteNexusOperationInput + input) { + return next.executeSignalWithStartWorkflow(input); + } + @Override public ExecuteNexusOperationOutput executeNexusOperation( ExecuteNexusOperationInput input) { diff --git a/temporal-testing/src/main/java/io/temporal/testing/internal/devserver/SdkJavaTestServerProfile.java b/temporal-testing/src/main/java/io/temporal/testing/internal/devserver/SdkJavaTestServerProfile.java index decae29151..ed4b33eae8 100644 --- a/temporal-testing/src/main/java/io/temporal/testing/internal/devserver/SdkJavaTestServerProfile.java +++ b/temporal-testing/src/main/java/io/temporal/testing/internal/devserver/SdkJavaTestServerProfile.java @@ -112,6 +112,8 @@ private static List repositoryServerArguments() { "--dynamic-config-value", "history.enableRequestIdRefLinks=true", "--dynamic-config-value", + "history.enableSignalWithStartFromWorkflow=true", + "--dynamic-config-value", "frontend.WorkerHeartbeatsEnabled=true", "--dynamic-config-value", "frontend.ListWorkersEnabled=true",