Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example for tasks interaction #567

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Demo tasks interaction

This example demonstrates a generic implementation for "User Tasks" interaction with Temporal,
which can be easily implemented as follows:
- The main workflow [WorkflowWithTasks](./WorkflowWithTasks.java) have an activity (or local activity) that send the request to an external service.
The _external service_, for this example, is another workflow ([WorkflowTaskManager](WorkflowTaskManager.java)),
that takes care of the task life-cicle.
- The main workflow waits to receive a Signal.
- The _external service_ signal back the main
workflow to unblock it.

The two first steps mentioned above are encapsulated in the class [TaskService.java](./TaskService.java), to make it easily reusable.

## Run the sample

- Schedule the main workflow execution ([WorkflowWithTasks](./WorkflowWithTasks.java)), the one that contains the _User Tasks_

```bash
./gradlew -q execute -PmainClass=io.temporal.samples.taskinteraction.client.StartWorkflow
```

- Open other terminal and start the Worker

```bash
./gradlew -q execute -PmainClass=io.temporal.samples.taskinteraction.worker.Worker
```

You will notice, from the worker logs, that it start the main workflow and execute two activities, the
two activities register two tasks to the external service ([WorkflowTaskManagerImpl.java](WorkflowTaskManagerImpl.java))

```
07:19:39.528 {WorkflowWithTasks1714454371179 } [workflow[WorkflowWithTasks1714454371179]-1] INFO i.t.s.taskinteraction.TaskService - Before creating task : Task{token='WorkflowWithTasks1714454371179_1', title=TaskTitle{value='TODO 1'}}
07:19:39.563 {WorkflowWithTasks1714454371179 } [workflow[WorkflowWithTasks1714454371179]-2] INFO i.t.s.taskinteraction.TaskService - Before creating task : Task{token='WorkflowWithTasks1714454371179_2', title=TaskTitle{value='TODO 2'}}
07:19:39.683 {WorkflowWithTasks1714454371179 } [workflow[WorkflowWithTasks1714454371179]-1] INFO i.t.s.taskinteraction.TaskService - Task created: Task{token='WorkflowWithTasks1714454371179_1', title=TaskTitle{value='TODO 1'}}
07:19:39.684 {WorkflowWithTasks1714454371179 } [workflow[WorkflowWithTasks1714454371179]-2] INFO i.t.s.taskinteraction.TaskService - Task created: Task{token='WorkflowWithTasks1714454371179_2', title=TaskTit
```

- Now, we can start completing the tasks using the helper class [CompleteTask.java](./client/CompleteTask.java)

```bash
./gradlew -q execute -PmainClass=io.temporal.samples.taskinteraction.client.CompleteTask
```
You can see from the implementation that [WorkflowWithTasksImpl](./WorkflowWithTasksImpl.java) has three task.
- two in parallel using `Async.procedure`,
- one blocking task at the end.

This class needs to be run three times. After the three task are completed the main workflow completes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package io.temporal.samples.taskinteraction;

import java.util.Objects;

public class Task {

private String token;
private TaskTitle title;

public Task() {}

public Task(String token, TaskTitle title) {
this.token = token;
this.title = title;
}

public String getToken() {
return token;
}

public TaskTitle getTitle() {
return title;
}

@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof Task)) return false;
final Task task = (Task) o;
return Objects.equals(token, task.token) && Objects.equals(title, task.title);
}

@Override
public int hashCode() {
return Objects.hash(token, title);
}

@Override
public String toString() {
return "Task{" + "token='" + token + '\'' + ", title=" + title + '}';
}

public static class TaskTitle {
private String value;

public TaskTitle() {}

public TaskTitle(final String value) {

this.value = value;
}

public String getValue() {
return value;
}

public void setValue(final String value) {
this.value = value;
}

@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof TaskTitle)) return false;
final TaskTitle taskTitle = (TaskTitle) o;
return Objects.equals(value, taskTitle.value);
}

@Override
public int hashCode() {
return Objects.hash(value);
}

@Override
public String toString() {
return "TaskTitle{" + "value='" + value + '\'' + '}';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package io.temporal.samples.taskinteraction;

import io.temporal.workflow.SignalMethod;
import io.temporal.workflow.WorkflowInterface;

@WorkflowInterface
public interface TaskClient {

@SignalMethod
void completeTaskByToken(String taskToken);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package io.temporal.samples.taskinteraction;

import io.temporal.activity.ActivityOptions;
import io.temporal.samples.taskinteraction.activity.ActivityTask;
import io.temporal.workflow.CompletablePromise;
import io.temporal.workflow.Workflow;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;

/**
* This class responsibility is to register the task in the external system and waits for the
* external system to signal back.
*/
public class TaskService<R> {

private final ActivityTask activity =
Workflow.newActivityStub(
ActivityTask.class,
ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build());

private TaskManager tasksManager = new TaskManager();

private final Logger logger = Workflow.getLogger(TaskService.class);

public TaskService() {

// This listener exposes a signal method that clients use to notify the task has been completed
Workflow.registerListener(
new TaskClient() {
@Override
public void completeTaskByToken(final String taskToken) {
logger.info("Completing task with token: " + taskToken);
tasksManager.completeTask(taskToken);
}
});
}

public void executeTask(Task task) {

logger.info("Before creating task : " + task);

// Activity implementation is responsible for registering the task to the external service
// (which is responsible for managing the task life-cycle)
activity.createTask(task);

logger.info("Task created: " + task);

tasksManager.waitForTaskCompletion(task);

logger.info("Task completed: " + task);
}

private class TaskManager {

private final Map<String, CompletablePromise<R>> tasks = new HashMap<>();

public void waitForTaskCompletion(final Task task) {
final CompletablePromise<R> promise = Workflow.newPromise();
tasks.put(task.getToken(), promise);
// Wait promise to complete
promise.get();
}

public void completeTask(final String taskToken) {

final CompletablePromise<R> completablePromise = tasks.get(taskToken);
completablePromise.complete(null);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package io.temporal.samples.taskinteraction;

import io.temporal.workflow.*;
import java.util.List;

@WorkflowInterface
public interface WorkflowTaskManager {

String WORKFLOW_ID = WorkflowTaskManager.class.getSimpleName();

@WorkflowMethod
void execute(final WorkflowTaskManagerImpl.PendingTasks pendingTasks);

@UpdateMethod
void createTask(Task task);

@UpdateMethod
void completeTaskByToken(String taskToken);

@QueryMethod
List<Task> getPendingTask();
}
Loading
Loading