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

Workflow authoring support #563

Merged
merged 18 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions examples/workflow/authoring/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Examples - Dapr Workflow

## Running

### Activity Sequence example

```bash
# Install
npm install

# Run the example
npm run start:dapr:activity-sequence
```

### Fan out/Fan in example

```bash
# Install
npm install

# Run the example
npm run start:dapr:fanout-fanin
```

### Human Interaction in example

```bash
# Install
npm install

# Run the example
npm run start:dapr:human-interaction
```
33 changes: 33 additions & 0 deletions examples/workflow/authoring/components/redis.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#
# Copyright 2022 The Dapr Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.
#

# https://docs.dapr.io/reference/components-reference/supported-bindings/rabbitmq/
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: state-redis
namespace: default
spec:
type: state.redis
version: v1
metadata:
- name: redisHost
value: localhost:6379
- name: redisPassword
value: ""
- name: enableTLS
value: "false"
- name: failover
value: "false"
- name: actorStateStore
value: "true"

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions examples/workflow/authoring/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "dapr-example-workflow-authoring",
"version": "1.0.0",
"description": "An example utilizing the Dapr JS-SDK to manage workflow",
kaibocai marked this conversation as resolved.
Show resolved Hide resolved
"private": "true",
"scripts": {
"build": "npx tsc --outDir ./dist/",
"start:activity-sequence": "npm run build && node dist/activity-sequence.js",
"start:fanout-fanin": "npm run build && node dist/fanout-fanin.js",
"start:human-interaction": "npm run build && node dist/human-interaction.js",
"start:dapr:activity-sequence": "dapr run --app-id activity-sequence-workflow --app-protocol grpc --dapr-grpc-port 50001 --components-path ./components npm run start:activity-sequence",
"start:dapr:fanout-fanin": "dapr run --app-id activity-sequence-workflow --app-protocol grpc --dapr-grpc-port 50001 --components-path ./components npm run start:fanout-fanin",
"start:dapr:human-interaction": "dapr run --app-id activity-sequence-workflow --app-protocol grpc --dapr-grpc-port 50001 --components-path ./components npm run start:human-interaction"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-node": "^10.9.1",
"typescript": "^5.0.4"
},
"dependencies": {
"@dapr/dapr": "file:../../../build",
"@types/node": "^18.16.3"
}
}
63 changes: 63 additions & 0 deletions examples/workflow/authoring/src/activity-sequence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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.
*/

import { WorkflowClient, WorkflowActivityContext, WorkflowContext, WorkflowRuntime, TWorkflow } from "@dapr/dapr";

(async () => {
kaibocai marked this conversation as resolved.
Show resolved Hide resolved
const grpcEndpoint = "localhost:50001";
const workflowClient = new WorkflowClient(grpcEndpoint);
const workflowRuntime = new WorkflowRuntime(grpcEndpoint);

const hello = async (_: WorkflowActivityContext, name: string) => {
return `Hello ${name}!`;
};

const sequence: TWorkflow = async function* (ctx: WorkflowContext): any {
const cities: string[] = [];

const result1 = yield ctx.callActivity(hello, "Tokyo");
cities.push(result1);
const result2 = yield ctx.callActivity(hello, "Seattle");
cities.push(result2);
const result3 = yield ctx.callActivity(hello, "London");
cities.push(result3);

return cities;
};

workflowRuntime.registerWorkflow(sequence).registerActivity(hello);

// Wrap the worker startup in a try-catch block to handle any errors during startup
try {
await workflowRuntime.start();
console.log("Workflow runtime started successfully");
} catch (error) {
console.error("Error starting workflow runtime:", error);
}

// Schedule a new orchestration
try {
const id = await workflowClient.scheduleNewWorkflow(sequence);
console.log(`Orchestration scheduled with ID: ${id}`);

// Wait for orchestration completion
const state = await workflowClient.waitForWorkflowCompletion(id, undefined, 30);

console.log(`Orchestration completed! Result: ${state?.serializedOutput}`);
} catch (error) {
console.error("Error scheduling or waiting for orchestration:", error);
}

await workflowRuntime.stop();
await workflowClient.stop();
})();
89 changes: 89 additions & 0 deletions examples/workflow/authoring/src/fanout-fanin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
Copyright 2024 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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.
*/

import { Task, WorkflowClient, WorkflowActivityContext, WorkflowContext, WorkflowRuntime, TWorkflow } from "@dapr/dapr";

// Wrap the entire code in an immediately-invoked async function
(async () => {
// Update the gRPC client and worker to use a local address and port
const grpcServerAddress = "localhost:50001";
const workflowClient: WorkflowClient = new WorkflowClient(grpcServerAddress);
const workflowRuntime: WorkflowRuntime = new WorkflowRuntime(grpcServerAddress);

function getRandomInt(min: number, max: number): number {
shubham1172 marked this conversation as resolved.
Show resolved Hide resolved
return Math.floor(Math.random() * (max - min + 1)) + min;
}

async function getWorkItemsActivity(_: WorkflowActivityContext): Promise<string[]> {
const count: number = getRandomInt(2, 10);
console.log(`generating ${count} work items...`);

const workItems: string[] = Array.from({ length: count }, (_, i) => `work item ${i}`);
return workItems;
}

function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

async function processWorkItemActivity(context: WorkflowActivityContext, item: string): Promise<number> {
console.log(`processing work item: ${item}`);

// Simulate some work that takes a variable amount of time
const sleepTime = Math.random() * 5000;
await sleep(sleepTime);

// Return a result for the given work item, which is also a random number in this case
return Math.floor(Math.random() * 11);
}

const workflow: TWorkflow = async function* (ctx: WorkflowContext): any {
const tasks: Task<any>[] = [];
const workItems = yield ctx.callActivity(getWorkItemsActivity);
for (const workItem of workItems) {
tasks.push(ctx.callActivity(processWorkItemActivity, workItem));
}
const results: number[] = yield ctx.whenAll(tasks);
const sum: number = results.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
return sum;
};

workflowRuntime.registerWorkflow(workflow);
workflowRuntime.registerActivity(getWorkItemsActivity);
workflowRuntime.registerActivity(processWorkItemActivity);

// Wrap the worker startup in a try-catch block to handle any errors during startup
try {
await workflowRuntime.start();
console.log("Worker started successfully");
} catch (error) {
console.error("Error starting worker:", error);
}

// Schedule a new orchestration
try {
const id = await workflowClient.scheduleNewWorkflow(workflow);
console.log(`Orchestration scheduled with ID: ${id}`);

// Wait for orchestration completion
const state = await workflowClient.waitForWorkflowCompletion(id, undefined, 30);

console.log(`Orchestration completed! Result: ${state?.serializedOutput}`);
} catch (error) {
console.error("Error scheduling or waiting for orchestration:", error);
}

// stop worker and client
await workflowRuntime.stop();
await workflowClient.stop();
})();
Loading
Loading