• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

temporalio / sdk-java / #176

pending completion
#176

push

github-actions

web-flow
Do not add accepted/rejected request to messages (#1787)

Avoids including the full initial request in the Acceptance and
Rejection messages from the update protocol. Server has been updated to
not expect these fields.

6 of 6 new or added lines in 3 files covered. (100.0%)

18330 of 23696 relevant lines covered (77.35%)

0.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.01
/temporal-sdk/src/main/java/io/temporal/internal/worker/LocalActivityWorker.java
1
/*
2
 * Copyright (C) 2022 Temporal Technologies, Inc. All Rights Reserved.
3
 *
4
 * Copyright (C) 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
 *
6
 * Modifications copyright (C) 2017 Uber Technologies, Inc.
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this material except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *   http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20

21
package io.temporal.internal.worker;
22

23
import static io.temporal.internal.worker.LocalActivityResult.failed;
24
import static io.temporal.internal.worker.LocalActivityResult.processingFailed;
25

26
import com.google.common.base.Preconditions;
27
import com.uber.m3.tally.Scope;
28
import com.uber.m3.tally.Stopwatch;
29
import com.uber.m3.util.ImmutableMap;
30
import io.grpc.Deadline;
31
import io.temporal.api.enums.v1.RetryState;
32
import io.temporal.api.enums.v1.TimeoutType;
33
import io.temporal.api.failure.v1.Failure;
34
import io.temporal.api.failure.v1.TimeoutFailureInfo;
35
import io.temporal.api.workflowservice.v1.PollActivityTaskQueueResponse;
36
import io.temporal.api.workflowservice.v1.PollActivityTaskQueueResponseOrBuilder;
37
import io.temporal.common.RetryOptions;
38
import io.temporal.failure.ApplicationFailure;
39
import io.temporal.internal.common.ProtobufTimeUtils;
40
import io.temporal.internal.common.RetryOptionsUtils;
41
import io.temporal.internal.logging.LoggerTag;
42
import io.temporal.internal.statemachines.ExecuteLocalActivityParameters;
43
import io.temporal.serviceclient.MetricsTag;
44
import io.temporal.worker.MetricsType;
45
import io.temporal.worker.WorkerMetricsTag;
46
import io.temporal.workflow.Functions;
47
import java.time.Duration;
48
import java.util.Objects;
49
import java.util.concurrent.*;
50
import javax.annotation.Nonnull;
51
import javax.annotation.Nullable;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54
import org.slf4j.MDC;
55

56
final class LocalActivityWorker implements Startable, Shutdownable {
57
  private static final Logger log = LoggerFactory.getLogger(LocalActivityWorker.class);
1✔
58

59
  private final ActivityTaskHandler handler;
60
  private final String namespace;
61
  private final String taskQueue;
62

63
  private final SingleWorkerOptions options;
64

65
  private final LocalActivityDispatcherImpl laScheduler;
66

67
  private final PollerOptions pollerOptions;
68
  private final Scope workerMetricsScope;
69

70
  private ScheduledExecutorService scheduledExecutor;
71
  private PollTaskExecutor<LocalActivityAttemptTask> activityAttemptTaskExecutor;
72

73
  public LocalActivityWorker(
74
      @Nonnull String namespace,
75
      @Nonnull String taskQueue,
76
      @Nonnull SingleWorkerOptions options,
77
      @Nonnull ActivityTaskHandler handler) {
1✔
78
    this.namespace = Objects.requireNonNull(namespace);
1✔
79
    this.taskQueue = Objects.requireNonNull(taskQueue);
1✔
80
    this.handler = handler;
1✔
81
    this.laScheduler = new LocalActivityDispatcherImpl(2 * options.getTaskExecutorThreadPoolSize());
1✔
82
    this.options = Objects.requireNonNull(options);
1✔
83
    this.pollerOptions = getPollerOptions(options);
1✔
84
    this.workerMetricsScope =
1✔
85
        MetricsTag.tagged(
1✔
86
            options.getMetricsScope(), WorkerMetricsTag.WorkerType.LOCAL_ACTIVITY_WORKER);
1✔
87
  }
1✔
88

89
  private void submitRetry(
90
      @Nonnull LocalActivityExecutionContext executionContext,
91
      @Nonnull PollActivityTaskQueueResponse.Builder activityTask) {
92
    submitAttempt(executionContext, activityTask, null);
1✔
93
  }
1✔
94

95
  private void submitAttempt(
96
      @Nonnull LocalActivityExecutionContext executionContext,
97
      @Nonnull PollActivityTaskQueueResponse.Builder activityTask,
98
      @Nullable Functions.Proc leftQueueCallback) {
99
    @Nullable Duration scheduleToStartTimeout = executionContext.getScheduleToStartTimeout();
1✔
100
    @Nullable ScheduledFuture<?> scheduleToStartFuture = null;
1✔
101
    if (scheduleToStartTimeout != null) {
1✔
102
      scheduleToStartFuture =
1✔
103
          scheduledExecutor.schedule(
1✔
104
              new FinalTimeoutHandler(TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_START, executionContext),
105
              scheduleToStartTimeout.toMillis(),
1✔
106
              TimeUnit.MILLISECONDS);
107
    }
108

109
    activityTask.setCurrentAttemptScheduledTime(ProtobufTimeUtils.getCurrentProtoTime());
1✔
110
    LocalActivityAttemptTask task =
1✔
111
        new LocalActivityAttemptTask(
112
            executionContext, activityTask, leftQueueCallback, scheduleToStartFuture);
113
    activityAttemptTaskExecutor.process(task);
1✔
114
  }
1✔
115

116
  /**
117
   * @param executionContext execution context of the activity
118
   * @param activityTask activity task
119
   * @param attemptThrowable exception happened during the activity attempt. Can be null.
120
   * @return decision to retry or not with a retry state, backoff or delay to the next attempt if
121
   *     applicable
122
   */
123
  @Nonnull
124
  private RetryDecision shouldRetry(
125
      LocalActivityExecutionContext executionContext,
126
      PollActivityTaskQueueResponseOrBuilder activityTask,
127
      @Nullable Throwable attemptThrowable) {
128
    int currentAttempt = activityTask.getAttempt();
1✔
129

130
    if (isNonRetryableApplicationFailure(attemptThrowable)) {
1✔
131
      return new RetryDecision(RetryState.RETRY_STATE_NON_RETRYABLE_FAILURE, null);
1✔
132
    }
133

134
    if (attemptThrowable instanceof Error) {
1✔
135
      // TODO Error inside Local Activity shouldn't be failing the local activity call.
136
      //  Instead we should fail Workflow Task. Implement a special flag for that in the result.
137
      //          task.callback(executionFailed(activityHandlerResult,
138
      // RetryState.RETRY_STATE_MAXIMUM_ATTEMPTS_REACHED, currentAttempt));
139
      // don't just swallow Error from activities, propagate it to the top
140
      throw (Error) attemptThrowable;
1✔
141
    }
142

143
    if (isRetryPolicyNotSet(activityTask)) {
1✔
144
      return new RetryDecision(RetryState.RETRY_STATE_RETRY_POLICY_NOT_SET, null);
×
145
    }
146

147
    RetryOptions retryOptions = RetryOptionsUtils.toRetryOptions(activityTask.getRetryPolicy());
1✔
148

149
    if (RetryOptionsUtils.isNotRetryable(retryOptions, attemptThrowable)) {
1✔
150
      return new RetryDecision(RetryState.RETRY_STATE_NON_RETRYABLE_FAILURE, null);
×
151
    }
152

153
    if (RetryOptionsUtils.areAttemptsReached(retryOptions, currentAttempt)) {
1✔
154
      return new RetryDecision(RetryState.RETRY_STATE_MAXIMUM_ATTEMPTS_REACHED, null);
1✔
155
    }
156

157
    long sleepMillis = retryOptions.calculateSleepTime(currentAttempt);
1✔
158
    Duration sleep = Duration.ofMillis(sleepMillis);
1✔
159
    if (RetryOptionsUtils.isDeadlineReached(
1✔
160
        executionContext.getScheduleToCloseDeadline(), sleepMillis)) {
1✔
161
      return new RetryDecision(RetryState.RETRY_STATE_TIMEOUT, null);
1✔
162
    }
163

164
    if (sleep.compareTo(executionContext.getLocalRetryThreshold()) > 0) {
1✔
165
      // RETRY_STATE_IN_PROGRESS shows that it's not the end for this local activity execution from
166
      // the workflow point of view. It's also not conflicting with any other situations and
167
      // uniquely identifies the reach of the local retries and a need to schedule a timer.
168
      return new RetryDecision(RetryState.RETRY_STATE_IN_PROGRESS, sleep);
1✔
169
    }
170

171
    return new RetryDecision(sleep);
1✔
172
  }
173

174
  /**
175
   * @param executionContext execution context of the activity
176
   * @param backoff delay time in milliseconds to the next attempt
177
   * @param failure if supplied, it will be used to override {@link
178
   *     LocalActivityExecutionContext#getLastAttemptFailure()}
179
   */
180
  private void scheduleNextAttempt(
181
      LocalActivityExecutionContext executionContext,
182
      @Nonnull Duration backoff,
183
      @Nullable Failure failure) {
184
    PollActivityTaskQueueResponse.Builder nextActivityTask =
1✔
185
        executionContext.getNextAttemptActivityTask(failure);
1✔
186
    Deadline.after(backoff.toMillis(), TimeUnit.MILLISECONDS)
1✔
187
        .runOnExpiration(
1✔
188
            new LocalActivityRetryHandler(executionContext, nextActivityTask), scheduledExecutor);
189
  }
1✔
190

191
  private class LocalActivityDispatcherImpl implements LocalActivityDispatcher {
192
    /**
193
     * Retries always get a green light, but we have a backpressure for new tasks if the queue fills
194
     * up with not picked up new executions
195
     */
196
    private final Semaphore newExecutionsBackpressureSemaphore;
197

198
    public LocalActivityDispatcherImpl(int semaphorePermits) {
1✔
199
      // number of permits for this semaphore is not that important, because we allow submitter to
200
      // block and wait till the workflow task heartbeat to allow the worker to tolerate spikes of
201
      // short local activity executions.
202
      this.newExecutionsBackpressureSemaphore = new Semaphore(semaphorePermits);
1✔
203
    }
1✔
204

205
    @Override
206
    public boolean dispatch(
207
        @Nonnull ExecuteLocalActivityParameters params,
208
        @Nonnull Functions.Proc1<LocalActivityResult> resultCallback,
209
        @Nullable Deadline acceptanceDeadline) {
210
      WorkerLifecycleState lifecycleState = getLifecycleState();
1✔
211
      switch (lifecycleState) {
1✔
212
        case NOT_STARTED:
213
          throw new IllegalStateException(
×
214
              "Local Activity Worker is not started, no activities were registered");
215
        case SHUTDOWN:
216
          throw new IllegalStateException("Local Activity Worker is shutdown");
×
217
        case TERMINATED:
218
          throw new IllegalStateException("Local Activity Worker is terminated");
×
219
        case SUSPENDED:
220
          throw new IllegalStateException(
×
221
              "[BUG] Local Activity Worker is suspended. Suspension is not supported for Local Activity Worker");
222
      }
223

224
      Preconditions.checkArgument(
1✔
225
          handler.isTypeSupported(params.getActivityType().getName()),
1✔
226
          "Activity type %s is not supported by the local activity worker",
227
          params.getActivityType().getName());
1✔
228

229
      long passedFromOriginalSchedulingMs =
230
          System.currentTimeMillis() - params.getOriginalScheduledTimestamp();
1✔
231
      Duration scheduleToCloseTimeout = params.getScheduleToCloseTimeout();
1✔
232
      Deadline scheduleToCloseDeadline = null;
1✔
233
      if (scheduleToCloseTimeout != null) {
1✔
234
        scheduleToCloseDeadline =
1✔
235
            Deadline.after(
1✔
236
                scheduleToCloseTimeout.toMillis() - passedFromOriginalSchedulingMs,
1✔
237
                TimeUnit.MILLISECONDS);
238
      }
239

240
      LocalActivityExecutionContext executionContext =
1✔
241
          new LocalActivityExecutionContext(params, resultCallback, scheduleToCloseDeadline);
242

243
      PollActivityTaskQueueResponse.Builder activityTask = executionContext.getInitialTask();
1✔
244

245
      boolean retryIsNotAllowed =
1✔
246
          failIfRetryIsNotAllowedByNewPolicy(executionContext, activityTask);
1✔
247
      if (retryIsNotAllowed) {
1✔
248
        return true;
1✔
249
      }
250

251
      return submitANewExecution(executionContext, activityTask, acceptanceDeadline);
1✔
252
    }
253

254
    private boolean submitANewExecution(
255
        @Nonnull LocalActivityExecutionContext executionContext,
256
        @Nonnull PollActivityTaskQueueResponse.Builder activityTask,
257
        @Nullable Deadline acceptanceDeadline) {
258
      try {
259
        boolean accepted;
260
        if (acceptanceDeadline == null) {
1✔
261
          newExecutionsBackpressureSemaphore.acquire();
×
262
          accepted = true;
×
263
        } else {
264
          long acceptanceTimeoutMs = acceptanceDeadline.timeRemaining(TimeUnit.MILLISECONDS);
1✔
265
          if (acceptanceTimeoutMs > 0) {
1✔
266
            accepted =
1✔
267
                newExecutionsBackpressureSemaphore.tryAcquire(
1✔
268
                    acceptanceTimeoutMs, TimeUnit.MILLISECONDS);
269
          } else {
270
            accepted = newExecutionsBackpressureSemaphore.tryAcquire();
1✔
271
          }
272
          if (!accepted) {
1✔
273
            log.warn(
×
274
                "LocalActivity queue is full and submitting timed out for activity {} with acceptanceTimeoutMs: {}",
275
                activityTask.getActivityId(),
×
276
                acceptanceTimeoutMs);
×
277
          }
278
        }
279

280
        if (accepted) {
1✔
281
          // we should publish scheduleToClose before submission, so the handlers always see a full
282
          // state of executionContext
283
          @Nullable
284
          Deadline scheduleToCloseDeadline = executionContext.getScheduleToCloseDeadline();
1✔
285
          if (scheduleToCloseDeadline != null) {
1✔
286
            ScheduledFuture<?> scheduleToCloseFuture =
1✔
287
                scheduledExecutor.schedule(
1✔
288
                    new FinalTimeoutHandler(
289
                        TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE, executionContext),
290
                    scheduleToCloseDeadline.timeRemaining(TimeUnit.MILLISECONDS),
1✔
291
                    TimeUnit.MILLISECONDS);
292
            executionContext.setScheduleToCloseFuture(scheduleToCloseFuture);
1✔
293
          }
294
          submitAttempt(
1✔
295
              executionContext, activityTask, newExecutionsBackpressureSemaphore::release);
1✔
296
          log.trace("LocalActivity queued: {}", activityTask.getActivityId());
1✔
297
        }
298
        return accepted;
1✔
299
      } catch (InterruptedException e) {
×
300
        Thread.currentThread().interrupt();
×
301
        return false;
×
302
      }
303
    }
304

305
    /**
306
     * @param attemptTask local activity retry attempt task specifying the retry we are about to
307
     *     schedule
308
     * @return true if the retry attempt specified by {@code task} is not allowed by the current
309
     *     retry policy and the error was submitted in the callback, false otherwise
310
     */
311
    private boolean failIfRetryIsNotAllowedByNewPolicy(
312
        LocalActivityExecutionContext executionContext,
313
        PollActivityTaskQueueResponseOrBuilder attemptTask) {
314
      final Failure previousExecutionFailure = executionContext.getPreviousExecutionFailure();
1✔
315
      if (previousExecutionFailure != null) {
1✔
316
        // This is not an original local execution, it's a continuation using a workflow timer.
317
        // We should verify if the RetryOptions currently supplied in the workflow still allow the
318
        // retry.
319
        // If not, we need to recreate the same structure of an error like it would happen before we
320
        // started to sleep on the timer, at the end of the previous local execution.
321
        RetryState retryState =
1✔
322
            shouldStillRetry(executionContext, attemptTask, previousExecutionFailure);
1✔
323
        if (!RetryState.RETRY_STATE_IN_PROGRESS.equals(retryState)) {
1✔
324
          Failure failure;
325
          if (RetryState.RETRY_STATE_TIMEOUT.equals(retryState)) {
1✔
326
            if (previousExecutionFailure.hasTimeoutFailureInfo()
×
327
                && TimeoutType.TIMEOUT_TYPE_START_TO_CLOSE.equals(
×
328
                    previousExecutionFailure.getTimeoutFailureInfo().getTimeoutType())) {
×
329
              // This scenario should behave the same way as a startToClose timeout happening and
330
              // encountering
331
              // RetryState#TIMEOUT during calculation of the next attempt (which is effectively a
332
              // scheduleToClose
333
              // timeout).
334
              // See how StartToCloseTimeoutHandler or
335
              // io.temporal.internal.testservice.StateMachines#timeoutActivityTask
336
              // discard startToClose in this case and replaces it with scheduleToClose
337
              failure =
×
338
                  newTimeoutFailure(
×
339
                      TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE,
340
                      previousExecutionFailure.getCause());
×
341
            } else {
342
              failure =
×
343
                  newTimeoutFailure(
×
344
                      TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE, previousExecutionFailure);
345
            }
346
          } else {
347
            failure = previousExecutionFailure;
1✔
348
          }
349

350
          executionContext.callback(
1✔
351
              failed(
1✔
352
                  executionContext.getActivityId(),
1✔
353
                  attemptTask.getAttempt(),
1✔
354
                  retryState,
355
                  failure,
356
                  null));
357
          return true;
1✔
358
        }
359
      }
360
      return false;
1✔
361
    }
362

363
    /**
364
     * @param executionContext execution context of the activity
365
     * @param activityTask activity task
366
     * @param previousLocalExecutionFailure failure happened during previous local activity
367
     *     execution. Can be null.
368
     * @return decision to retry or not with a retry state, backoff or delay to the next attempt if
369
     *     applicable
370
     */
371
    @Nonnull
372
    private RetryState shouldStillRetry(
373
        LocalActivityExecutionContext executionContext,
374
        PollActivityTaskQueueResponseOrBuilder activityTask,
375
        @Nullable Failure previousLocalExecutionFailure) {
376
      int currentAttempt = activityTask.getAttempt();
1✔
377

378
      if (isRetryPolicyNotSet(activityTask)) {
1✔
379
        return RetryState.RETRY_STATE_RETRY_POLICY_NOT_SET;
×
380
      }
381

382
      RetryOptions retryOptions = RetryOptionsUtils.toRetryOptions(activityTask.getRetryPolicy());
1✔
383

384
      if (previousLocalExecutionFailure != null
1✔
385
          && previousLocalExecutionFailure.hasApplicationFailureInfo()
1✔
386
          && RetryOptionsUtils.isNotRetryable(
×
387
              retryOptions, previousLocalExecutionFailure.getApplicationFailureInfo().getType())) {
×
388
        return RetryState.RETRY_STATE_NON_RETRYABLE_FAILURE;
×
389
      }
390

391
      // The current attempt didn't happen yet in this check, that's why -1
392
      if (RetryOptionsUtils.areAttemptsReached(retryOptions, currentAttempt - 1)) {
1✔
393
        return RetryState.RETRY_STATE_MAXIMUM_ATTEMPTS_REACHED;
1✔
394
      }
395

396
      long sleepMillis = retryOptions.calculateSleepTime(currentAttempt);
1✔
397
      if (RetryOptionsUtils.isDeadlineReached(
1✔
398
          executionContext.getScheduleToCloseDeadline(), sleepMillis)) {
1✔
399
        return RetryState.RETRY_STATE_TIMEOUT;
×
400
      }
401

402
      return RetryState.RETRY_STATE_IN_PROGRESS;
1✔
403
    }
404
  }
405

406
  private class AttemptTaskHandlerImpl
407
      implements PollTaskExecutor.TaskHandler<LocalActivityAttemptTask> {
408

409
    private final ActivityTaskHandler handler;
410

411
    private AttemptTaskHandlerImpl(ActivityTaskHandler handler) {
1✔
412
      this.handler = handler;
1✔
413
    }
1✔
414

415
    @Override
416
    public void handle(LocalActivityAttemptTask attemptTask) throws Exception {
417
      attemptTask.markAsTakenFromQueue();
1✔
418

419
      // cancel scheduleToStart timeout if not already fired
420
      @Nullable ScheduledFuture<?> scheduleToStartFuture = attemptTask.getScheduleToStartFuture();
1✔
421
      boolean scheduleToStartFired =
1✔
422
          scheduleToStartFuture != null && !scheduleToStartFuture.cancel(false);
1✔
423

424
      LocalActivityExecutionContext executionContext = attemptTask.getExecutionContext();
1✔
425
      PollActivityTaskQueueResponseOrBuilder activityTask = attemptTask.getAttemptTask();
1✔
426

427
      // if an activity was already completed by any mean like scheduleToClose or scheduleToStart,
428
      // discard this attempt, this execution is completed.
429
      // The scheduleToStartFired check here is a bit overkill, but allows to catch an edge case
430
      // where
431
      // scheduleToStart is already fired, but didn't report a completion yet.
432
      boolean shouldDiscardTheAttempt = scheduleToStartFired || executionContext.isCompleted();
1✔
433
      if (shouldDiscardTheAttempt) {
1✔
434
        return;
×
435
      }
436

437
      Scope metricsScope =
1✔
438
          workerMetricsScope.tagged(
1✔
439
              ImmutableMap.of(
1✔
440
                  MetricsTag.ACTIVITY_TYPE,
441
                  activityTask.getActivityType().getName(),
1✔
442
                  MetricsTag.WORKFLOW_TYPE,
443
                  activityTask.getWorkflowType().getName()));
1✔
444

445
      MDC.put(LoggerTag.ACTIVITY_ID, activityTask.getActivityId());
1✔
446
      MDC.put(LoggerTag.ACTIVITY_TYPE, activityTask.getActivityType().getName());
1✔
447
      MDC.put(LoggerTag.WORKFLOW_ID, activityTask.getWorkflowExecution().getWorkflowId());
1✔
448
      MDC.put(LoggerTag.WORKFLOW_TYPE, activityTask.getWorkflowType().getName());
1✔
449
      MDC.put(LoggerTag.RUN_ID, activityTask.getWorkflowExecution().getRunId());
1✔
450
      try {
451
        ScheduledFuture<?> startToCloseTimeoutFuture = null;
1✔
452

453
        if (activityTask.hasStartToCloseTimeout()) {
1✔
454
          startToCloseTimeoutFuture =
1✔
455
              scheduledExecutor.schedule(
1✔
456
                  new StartToCloseTimeoutHandler(attemptTask),
457
                  ProtobufTimeUtils.toJavaDuration(
1✔
458
                          attemptTask.getAttemptTask().getStartToCloseTimeout())
1✔
459
                      .toMillis(),
1✔
460
                  TimeUnit.MILLISECONDS);
461
        }
462

463
        metricsScope.counter(MetricsType.LOCAL_ACTIVITY_TOTAL_COUNTER).inc(1);
1✔
464

465
        ActivityTaskHandler.Result activityHandlerResult;
466
        Stopwatch sw = metricsScope.timer(MetricsType.LOCAL_ACTIVITY_EXECUTION_LATENCY).start();
1✔
467
        try {
468
          activityHandlerResult =
1✔
469
              handler.handle(new ActivityTask(activityTask, () -> {}), metricsScope, true);
1✔
470
        } finally {
471
          sw.stop();
1✔
472
        }
473

474
        // Cancel startToCloseTimeoutFuture if it's not yet fired.
475
        boolean startToCloseTimeoutFired =
1✔
476
            startToCloseTimeoutFuture != null && !startToCloseTimeoutFuture.cancel(false);
1✔
477

478
        // We make sure that the result handling code following this statement is mutual exclusive
479
        // with the startToClose timeout handler.
480
        // If startToClose fired, scheduling of the next attempt is taken care by the
481
        // StartToCloseTimeoutHandler.
482
        // If execution is already completed, this attempt handling shouldn't proceed, nothing to do
483
        // with result. The typical scenario may be fired scheduleToClose.
484
        boolean shouldDiscardTheResult = startToCloseTimeoutFired || executionContext.isCompleted();
1✔
485
        if (shouldDiscardTheResult) {
1✔
486
          return;
1✔
487
        }
488

489
        handleResult(activityHandlerResult, attemptTask, metricsScope);
1✔
490
      } catch (Throwable ex) {
1✔
491
        // handleLocalActivity is expected to never throw an exception and return a result
492
        // that can be used for a workflow callback if this method throws, it's a bug.
493
        log.error("[BUG] Code that expected to never throw an exception threw an exception", ex);
1✔
494
        executionContext.callback(
1✔
495
            processingFailed(activityTask.getActivityId(), activityTask.getAttempt(), ex));
1✔
496
        throw ex;
1✔
497
      } finally {
498
        MDC.remove(LoggerTag.ACTIVITY_ID);
1✔
499
        MDC.remove(LoggerTag.ACTIVITY_TYPE);
1✔
500
        MDC.remove(LoggerTag.WORKFLOW_ID);
1✔
501
        MDC.remove(LoggerTag.WORKFLOW_TYPE);
1✔
502
        MDC.remove(LoggerTag.RUN_ID);
1✔
503
      }
504
    }
1✔
505

506
    private void handleResult(
507
        ActivityTaskHandler.Result activityHandlerResult,
508
        LocalActivityAttemptTask attemptTask,
509
        Scope metricsScope) {
510
      LocalActivityExecutionContext executionContext = attemptTask.getExecutionContext();
1✔
511
      PollActivityTaskQueueResponseOrBuilder activityTask = attemptTask.getAttemptTask();
1✔
512
      int currentAttempt = activityTask.getAttempt();
1✔
513

514
      // Success
515
      if (activityHandlerResult.getTaskCompleted() != null) {
1✔
516
        boolean completedByThisInvocation =
1✔
517
            executionContext.callback(
1✔
518
                LocalActivityResult.completed(activityHandlerResult, currentAttempt));
1✔
519
        if (completedByThisInvocation) {
1✔
520
          // We report this metric only if the execution was completed by us right now, not by any
521
          // timeout earlier.
522
          // Completion by another attempt is not possible by another attempt earlier where we
523
          // checked if startToClose fired.
524
          com.uber.m3.util.Duration e2eDuration =
525
              com.uber.m3.util.Duration.ofMillis(
1✔
526
                  System.currentTimeMillis() - executionContext.getOriginalScheduledTimestamp());
1✔
527
          metricsScope.timer(MetricsType.LOCAL_ACTIVITY_SUCCEED_E2E_LATENCY).record(e2eDuration);
1✔
528
        }
529
        return;
1✔
530
      }
531

532
      // Cancellation
533
      if (activityHandlerResult.getTaskCanceled() != null) {
1✔
534
        executionContext.callback(
×
535
            LocalActivityResult.cancelled(activityHandlerResult, currentAttempt));
×
536
        return;
×
537
      }
538

539
      // Failure
540
      Preconditions.checkState(
1✔
541
          activityHandlerResult.getTaskFailed() != null,
1✔
542
          "One of taskCompleted, taskCanceled or taskFailed must be set");
543

544
      Failure executionFailure =
1✔
545
          activityHandlerResult.getTaskFailed().getTaskFailedRequest().getFailure();
1✔
546
      Throwable executionThrowable = activityHandlerResult.getTaskFailed().getFailure();
1✔
547

548
      RetryDecision retryDecision =
1✔
549
          shouldRetry(
1✔
550
              executionContext, activityTask, activityHandlerResult.getTaskFailed().getFailure());
1✔
551

552
      if (retryDecision.doNextAttempt()) {
1✔
553
        scheduleNextAttempt(
1✔
554
            executionContext,
555
            Objects.requireNonNull(
1✔
556
                retryDecision.nextAttemptBackoff, "nextAttemptBackoff is expected to not be null"),
1✔
557
            executionFailure);
558
      } else if (retryDecision.failWorkflowTask()) {
1✔
559
        executionContext.callback(
×
560
            processingFailed(executionContext.getActivityId(), currentAttempt, executionThrowable));
×
561
      } else {
562
        executionContext.callback(
1✔
563
            failed(
1✔
564
                executionContext.getActivityId(),
1✔
565
                currentAttempt,
566
                retryDecision.retryState,
1✔
567
                executionFailure,
568
                retryDecision.nextAttemptBackoff));
1✔
569
      }
570
    }
1✔
571

572
    @Override
573
    public Throwable wrapFailure(LocalActivityAttemptTask task, Throwable failure) {
574
      return new RuntimeException("Failure processing local activity task.", failure);
1✔
575
    }
576
  }
577

578
  private class LocalActivityRetryHandler implements Runnable {
579
    private final @Nonnull LocalActivityExecutionContext executionContext;
580
    private final @Nonnull PollActivityTaskQueueResponse.Builder activityTask;
581

582
    private LocalActivityRetryHandler(
583
        @Nonnull LocalActivityExecutionContext executionContext,
584
        @Nonnull PollActivityTaskQueueResponse.Builder activityTask) {
1✔
585
      this.executionContext = Objects.requireNonNull(executionContext, "executionContext");
1✔
586
      this.activityTask = Objects.requireNonNull(activityTask, "activityTask");
1✔
587
    }
1✔
588

589
    @Override
590
    public void run() {
591
      submitRetry(executionContext, activityTask);
1✔
592
    }
1✔
593
  }
594

595
  /** Used to perform both scheduleToStart and scheduleToClose timeouts. */
596
  private static class FinalTimeoutHandler implements Runnable {
597
    private final LocalActivityExecutionContext executionContext;
598
    private final TimeoutType timeoutType;
599

600
    public FinalTimeoutHandler(
601
        TimeoutType timeoutType, LocalActivityExecutionContext executionContext) {
1✔
602
      this.executionContext = executionContext;
1✔
603
      this.timeoutType = timeoutType;
1✔
604
    }
1✔
605

606
    @Override
607
    public void run() {
608
      executionContext.callback(
1✔
609
          failed(
1✔
610
              executionContext.getActivityId(),
1✔
611
              executionContext.getCurrentAttempt(),
1✔
612
              RetryState.RETRY_STATE_TIMEOUT,
613
              newTimeoutFailure(timeoutType, executionContext.getLastAttemptFailure()),
1✔
614
              null));
615
    }
1✔
616
  }
617

618
  private class StartToCloseTimeoutHandler implements Runnable {
619
    private final LocalActivityAttemptTask attemptTask;
620

621
    private StartToCloseTimeoutHandler(LocalActivityAttemptTask attemptTask) {
1✔
622
      this.attemptTask = attemptTask;
1✔
623
    }
1✔
624

625
    @Override
626
    public void run() {
627
      LocalActivityExecutionContext executionContext = attemptTask.getExecutionContext();
1✔
628
      PollActivityTaskQueueResponseOrBuilder activityTask = attemptTask.getAttemptTask();
1✔
629
      String activityId = activityTask.getActivityId();
1✔
630

631
      int timingOutAttempt = activityTask.getAttempt();
1✔
632

633
      RetryDecision retryDecision = shouldRetry(executionContext, activityTask, null);
1✔
634
      if (retryDecision.doNextAttempt()) {
1✔
635
        scheduleNextAttempt(
1✔
636
            executionContext,
637
            Objects.requireNonNull(
1✔
638
                retryDecision.nextAttemptBackoff, "nextAttemptBackoff is expected to not be null"),
1✔
639
            newTimeoutFailure(TimeoutType.TIMEOUT_TYPE_START_TO_CLOSE, null));
1✔
640
      } else {
641
        // RetryState.RETRY_STATE_TIMEOUT happens only when scheduleToClose is fired
642
        // scheduleToClose timeout is effectively replacing the original startToClose
643
        TimeoutType timeoutType =
644
            RetryState.RETRY_STATE_TIMEOUT.equals(retryDecision.retryState)
1✔
645
                ? TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE
1✔
646
                : TimeoutType.TIMEOUT_TYPE_START_TO_CLOSE;
1✔
647
        executionContext.callback(
1✔
648
            failed(
1✔
649
                activityId,
650
                timingOutAttempt,
651
                retryDecision.retryState,
1✔
652
                newTimeoutFailure(timeoutType, executionContext.getLastAttemptFailure()),
1✔
653
                retryDecision.nextAttemptBackoff));
1✔
654
      }
655
    }
1✔
656
  }
657

658
  @Override
659
  public boolean start() {
660
    if (handler.isAnyTypeSupported()) {
1✔
661
      this.scheduledExecutor =
1✔
662
          Executors.newSingleThreadScheduledExecutor(
1✔
663
              r -> {
664
                Thread thread = new Thread(r);
1✔
665
                thread.setName(
1✔
666
                    WorkerThreadsNameHelper.getLocalActivitySchedulerThreadPrefix(
1✔
667
                        namespace, taskQueue));
668
                return thread;
1✔
669
              });
670

671
      this.activityAttemptTaskExecutor =
1✔
672
          new PollTaskExecutor<>(
673
              namespace,
674
              taskQueue,
675
              options.getIdentity(),
1✔
676
              new AttemptTaskHandlerImpl(handler),
677
              pollerOptions,
678
              options.getTaskExecutorThreadPoolSize(),
1✔
679
              workerMetricsScope,
680
              false);
681

682
      this.workerMetricsScope.counter(MetricsType.WORKER_START_COUNTER).inc(1);
1✔
683
      return true;
1✔
684
    } else {
685
      return false;
1✔
686
    }
687
  }
688

689
  @Override
690
  public CompletableFuture<Void> shutdown(ShutdownManager shutdownManager, boolean interruptTasks) {
691
    if (activityAttemptTaskExecutor != null && !activityAttemptTaskExecutor.isShutdown()) {
1✔
692
      return activityAttemptTaskExecutor
1✔
693
          .shutdown(shutdownManager, interruptTasks)
1✔
694
          .thenCompose(
1✔
695
              r ->
696
                  shutdownManager.shutdownExecutor(
1✔
697
                      scheduledExecutor, this + "#scheduledExecutor", Duration.ofSeconds(1)))
1✔
698
          .exceptionally(
1✔
699
              e -> {
700
                log.error("[BUG] Unexpected exception during shutdown", e);
×
701
                return null;
×
702
              });
703
    } else {
704
      return CompletableFuture.completedFuture(null);
1✔
705
    }
706
  }
707

708
  @Override
709
  public void awaitTermination(long timeout, TimeUnit unit) {
710
    long timeoutMillis = unit.toMillis(timeout);
1✔
711
    ShutdownManager.awaitTermination(scheduledExecutor, timeoutMillis);
1✔
712
  }
1✔
713

714
  @Override
715
  public boolean isShutdown() {
716
    return activityAttemptTaskExecutor != null && activityAttemptTaskExecutor.isShutdown();
×
717
  }
718

719
  @Override
720
  public boolean isTerminated() {
721
    return activityAttemptTaskExecutor != null
×
722
        && activityAttemptTaskExecutor.isTerminated()
×
723
        && scheduledExecutor.isTerminated();
×
724
  }
725

726
  @Override
727
  public WorkerLifecycleState getLifecycleState() {
728
    if (activityAttemptTaskExecutor == null) {
1✔
729
      return WorkerLifecycleState.NOT_STARTED;
×
730
    }
731
    if (activityAttemptTaskExecutor.isShutdown()) {
1✔
732
      // return TERMINATED only if both pollExecutor and taskExecutor are terminated
733
      if (activityAttemptTaskExecutor.isTerminated() && scheduledExecutor.isTerminated()) {
×
734
        return WorkerLifecycleState.TERMINATED;
×
735
      } else {
736
        return WorkerLifecycleState.SHUTDOWN;
×
737
      }
738
    }
739
    return WorkerLifecycleState.ACTIVE;
1✔
740
  }
741

742
  private PollerOptions getPollerOptions(SingleWorkerOptions options) {
743
    PollerOptions pollerOptions = options.getPollerOptions();
1✔
744
    if (pollerOptions.getPollThreadNamePrefix() == null) {
1✔
745
      pollerOptions =
1✔
746
          PollerOptions.newBuilder(pollerOptions)
1✔
747
              .setPollThreadNamePrefix(
1✔
748
                  WorkerThreadsNameHelper.getLocalActivityPollerThreadPrefix(namespace, taskQueue))
1✔
749
              .build();
1✔
750
    }
751
    return pollerOptions;
1✔
752
  }
753

754
  public LocalActivityDispatcher getLocalActivityScheduler() {
755
    return laScheduler;
1✔
756
  }
757

758
  private static Failure newTimeoutFailure(TimeoutType timeoutType, @Nullable Failure cause) {
759
    TimeoutFailureInfo.Builder info = TimeoutFailureInfo.newBuilder().setTimeoutType(timeoutType);
1✔
760
    Failure.Builder result = Failure.newBuilder().setTimeoutFailureInfo(info);
1✔
761
    if (cause != null) {
1✔
762
      result.setCause(cause);
1✔
763
    }
764
    return result.build();
1✔
765
  }
766

767
  private static boolean isRetryPolicyNotSet(
768
      PollActivityTaskQueueResponseOrBuilder pollActivityTask) {
769
    return !pollActivityTask.hasScheduleToCloseTimeout()
1✔
770
        && (!pollActivityTask.hasRetryPolicy()
1✔
771
            || pollActivityTask.getRetryPolicy().getMaximumAttempts() <= 0);
1✔
772
  }
773

774
  private static boolean isNonRetryableApplicationFailure(@Nullable Throwable executionThrowable) {
775
    return executionThrowable instanceof ApplicationFailure
1✔
776
        && ((ApplicationFailure) executionThrowable).isNonRetryable();
1✔
777
  }
778

779
  private static class RetryDecision {
780
    private final @Nullable RetryState retryState;
781
    private final @Nullable Duration nextAttemptBackoff;
782

783
    // No next local attempts
784
    public RetryDecision(@Nonnull RetryState retryState, @Nullable Duration nextAttemptBackoff) {
1✔
785
      this.retryState = retryState;
1✔
786
      this.nextAttemptBackoff = nextAttemptBackoff;
1✔
787
    }
1✔
788

789
    // Do the next attempt
790
    public RetryDecision(@Nonnull Duration nextAttemptBackoff) {
1✔
791
      this.retryState = null;
1✔
792
      this.nextAttemptBackoff = Objects.requireNonNull(nextAttemptBackoff);
1✔
793
    }
1✔
794

795
    public boolean doNextAttempt() {
796
      return retryState == null;
1✔
797
    }
798

799
    public boolean failWorkflowTask() {
800
      return RetryState.RETRY_STATE_INTERNAL_SERVER_ERROR.equals(retryState);
1✔
801
    }
802
  }
803
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc