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] Update for JavaScript SDK #3896

Merged
merged 19 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ The Dapr sidecar doesn’t load any workflow definitions. Rather, the sidecar si

[Workflow activities]({{< ref "workflow-features-concepts.md#workflow-activites" >}}) are the basic unit of work in a workflow and are the tasks that get orchestrated in the business process.

{{< tabs Python ".NET" Java >}}
{{< tabs Python JavaScript ".NET" Java >}}

{{% codetab %}}

Expand All @@ -52,6 +52,37 @@ def hello_act(ctx: WorkflowActivityContext, input):
[See the `hello_act` workflow activity in context.](https://github.com/dapr/python-sdk/blob/master/examples/demo_workflow/app.py#LL40C1-L43C59)


{{% /codetab %}}

{{% codetab %}}

<!--javascript-->

Define the workflow activities you'd like your workflow to perform. Activities are wrapped in the `WorkflowActivityContext` class, which implements the workflow activities.

```javascript
export default class WorkflowActivityContext {
private readonly _innerContext: ActivityContext;
constructor(innerContext: ActivityContext) {
if (!innerContext) {
throw new Error("ActivityContext cannot be undefined");
}
this._innerContext = innerContext;
}

public getWorkflowInstanceId(): string {
return this._innerContext.orchestrationId;
}

public getWorkflowActivityId(): number {
return this._innerContext.taskId;
}
}
```

[See the workflow activity in context.](todo)


{{% /codetab %}}

{{% codetab %}}
Expand Down Expand Up @@ -172,7 +203,7 @@ public class DemoWorkflowActivity implements WorkflowActivity {

Next, register and call the activites in a workflow.

{{< tabs Python ".NET" Java >}}
{{< tabs Python JavaScript ".NET" Java >}}

{{% codetab %}}

Expand All @@ -193,6 +224,51 @@ def hello_world_wf(ctx: DaprWorkflowContext, input):
[See the `hello_world_wf` workflow in context.](https://github.com/dapr/python-sdk/blob/master/examples/demo_workflow/app.py#LL32C1-L38C51)
hhunter-ms marked this conversation as resolved.
Show resolved Hide resolved


{{% /codetab %}}

{{% codetab %}}

<!--javascript-->

Next, register the workflow with the `WorkflowRuntime` class and start the workflow runtime.

```javascript
export default class WorkflowRuntime {

//..
// Register workflow
public registerWorkflow(workflow: TWorkflow): WorkflowRuntime {
const name = getFunctionName(workflow);
const workflowWrapper = (ctx: OrchestrationContext, input: any): any => {
const workflowContext = new WorkflowContext(ctx);
return workflow(workflowContext, input);
};
this.worker.addNamedOrchestrator(name, workflowWrapper);
return this;
}

// Register workflow activities
public registerActivity(fn: TWorkflowActivity<TInput, TOutput>): WorkflowRuntime {
const name = getFunctionName(fn);
const activityWrapper = (ctx: ActivityContext, intput: TInput): TOutput => {
const wfActivityContext = new WorkflowActivityContext(ctx);
return fn(wfActivityContext, intput);
};
this.worker.addNamedActivity(name, activityWrapper);
return this;
}

// Start the workflow runtime processing items and block.
public async start() {
await this.worker.start();
}

}
```

[See the `hello_world_wf` workflow in context.](todo)


{{% /codetab %}}

{{% codetab %}}
Expand Down Expand Up @@ -275,7 +351,7 @@ public class DemoWorkflowWorker {

Finally, compose the application using the workflow.

{{< tabs Python ".NET" Java >}}
{{< tabs Python JavaScript ".NET" Java >}}

{{% codetab %}}

Expand Down Expand Up @@ -364,6 +440,191 @@ if __name__ == '__main__':
```


{{% /codetab %}}

{{% codetab %}}

<!--javascript-->

[In the following example](todo), for a basic JavaScript hello world application using the Go SDK, your project code would include:

- A JavaScript package called `todo` to receive the Go SDK capabilities.
hhunter-ms marked this conversation as resolved.
Show resolved Hide resolved
- A builder with extensions called:
- `WorkflowRuntime`: Allows you to register workflows and workflow activities
- `DaprWorkflowContext`: Allows you to [create workflows]({{< ref "#write-the-workflow" >}})
- `WorkflowActivityContext`: Allows you to [create workflow activities]({{< ref "#write-the-workflow-activities" >}})
- API calls. In the example below, these calls start, pause, resume, purge, and terminate the workflow.

```javascript
import { TaskHubGrpcClient } from "kaibocai-durabletask-js";
import * as grpc from "@grpc/grpc-js";
import { WorkflowState } from "./WorkflowState";
import { generateInterceptors } from "../internal/ApiTokenClientInterceptor";
import { TWorkflow } from "../types/Workflow.type";
import { getFunctionName } from "../internal";

export default class WorkflowClient {
private readonly _innerClient: TaskHubGrpcClient;

/**
* Initializes a new instance of the DaprWorkflowClient.
* @param {string | undefined} hostAddress - The address of the Dapr runtime hosting the workflow services.
* @param {grpc.ChannelOptions | undefined} options - Additional options for configuring the gRPC channel.
*/
constructor(hostAddress?: string, options?: grpc.ChannelOptions) {
this._innerClient = this._buildInnerClient(hostAddress, options);
}

_buildInnerClient(hostAddress = "127.0.0.1:50001", options: grpc.ChannelOptions = {}): TaskHubGrpcClient {
const innerOptions = {
...options,
interceptors: [generateInterceptors(), ...(options?.interceptors ?? [])],
};
return new TaskHubGrpcClient(hostAddress, innerOptions);
}

/**
* Schedules a new workflow using the DurableTask client.
*
* @param {TWorkflow | string} workflow - The Workflow or the name of the workflow to be scheduled.
* @return {Promise<string>} A Promise resolving to the unique ID of the scheduled workflow instance.
*/
public async scheduleNewWorkflow(
workflow: TWorkflow | string,
input?: any,
instanceId?: string,
startAt?: Date,
): Promise<string> {
if (typeof workflow === "string") {
return await this._innerClient.scheduleNewOrchestration(workflow, input, instanceId, startAt);
}
return await this._innerClient.scheduleNewOrchestration(getFunctionName(workflow), input, instanceId, startAt);
}

/**
* Terminates the workflow associated with the provided instance id.
*
* @param {string} workflowInstanceId - Workflow instance id to terminate.
* @param {any} output - The optional output to set for the terminated workflow instance.
*/
public async terminateWorkflow(workflowInstanceId: string, output: any) {
await this._innerClient.terminateOrchestration(workflowInstanceId, output);
}

/**
* Fetches workflow instance metadata from the configured durable store.
*
* @param {string} workflowInstanceId - The unique identifier of the workflow instance to fetch.
* @param {boolean} getInputsAndOutputs - Indicates whether to fetch the workflow instance's
* inputs, outputs, and custom status (true) or omit them (false).
* @returns {Promise<WorkflowState | undefined>} A Promise that resolves to a metadata record describing
* the workflow instance and its execution status, or undefined
* if the instance is not found.
*/
public async getWorkflowState(
workflowInstanceId: string,
getInputsAndOutputs: boolean,
): Promise<WorkflowState | undefined> {
const state = await this._innerClient.getOrchestrationState(workflowInstanceId, getInputsAndOutputs);
if (state !== undefined) {
return new WorkflowState(state);
}
}

/**
* Waits for a workflow to start running and returns a {@link WorkflowState} object
* containing metadata about the started instance, and optionally, its input, output,
* and custom status payloads.
*
* A "started" workflow instance refers to any instance not in the Pending state.
*
* If a workflow instance is already running when this method is called, it returns immediately.
*
* @param {string} workflowInstanceId - The unique identifier of the workflow instance to wait for.
* @param {boolean} fetchPayloads - Indicates whether to fetch the workflow instance's
* inputs, outputs (true) or omit them (false).
* @param {number} timeout - The amount of time, in seconds, to wait for the workflow instance to start.
* @returns {Promise<WorkflowState | undefined>} A Promise that resolves to the workflow instance metadata
* or undefined if no such instance is found.
*/
public async waitForWorkflowStart(
workflowInstanceId: string,
fetchPayloads?: boolean,
timeout?: number,
): Promise<WorkflowState | undefined> {
const state = await this._innerClient.waitForOrchestrationStart(workflowInstanceId, fetchPayloads, timeout);
if (state !== undefined) {
return new WorkflowState(state);
}
}

/**
* Waits for a workflow to complete running and returns a {@link WorkflowState} object
* containing metadata about the completed instance, and optionally, its input, output,
* and custom status payloads.
*
* A "completed" workflow instance refers to any instance in one of the terminal states.
* For example, the Completed, Failed, or Terminated states.
*
* If a workflow instance is already running when this method is called, it returns immediately.
*
* @param {string} workflowInstanceId - The unique identifier of the workflow instance to wait for.
* @param {boolean} fetchPayloads - Indicates whether to fetch the workflow instance's
* inputs, outputs (true) or omit them (false).
* @param {number} timeout - The amount of time, in seconds, to wait for the workflow instance to start.
* @returns {Promise<WorkflowState | undefined>} A Promise that resolves to the workflow instance metadata
* or undefined if no such instance is found.
*/
public async waitForWorkflowCompletion(
workflowInstanceId: string,
fetchPayloads = true,
timeout: number,
): Promise<WorkflowState | undefined> {
const state = await this._innerClient.waitForOrchestrationCompletion(workflowInstanceId, fetchPayloads, timeout);
if (state != undefined) {
return new WorkflowState(state);
}
}

/**
* Sends an event notification message to an awaiting workflow instance.
*
* This method triggers the specified event in a running workflow instance,
* allowing the workflow to respond to the event if it has defined event handlers.
*
* @param {string} workflowInstanceId - The unique identifier of the workflow instance that will handle the event.
* @param {string} eventName - The name of the event. Event names are case-insensitive.
* @param {any} [eventPayload] - An optional serializable data payload to include with the event.
*/
public async raiseEvent(workflowInstanceId: string, eventName: string, eventPayload?: any) {
this._innerClient.raiseOrchestrationEvent(workflowInstanceId, eventName, eventPayload);
}

/**
* Purges the workflow instance state from the workflow state store.
*
* This method removes the persisted state associated with a workflow instance from the state store.
*
* @param {string} workflowInstanceId - The unique identifier of the workflow instance to purge.
* @return {Promise<boolean>} A Promise that resolves to true if the workflow state was found and purged successfully, otherwise false.
*/
public async purgeWorkflow(workflowInstanceId: string): Promise<boolean> {
const purgeResult = await this._innerClient.purgeOrchestration(workflowInstanceId);
if (purgeResult !== undefined) {
return purgeResult.deletedInstanceCount > 0;
}
return false;
}

/**
* Closes the inner DurableTask client and shutdown the GRPC channel.
*/
public async stop() {
await this._innerClient.stop();
}
}
```

{{% /codetab %}}

{{% codetab %}}
Expand Down Expand Up @@ -504,5 +765,6 @@ Now that you've authored a workflow, learn how to manage it.
- [Workflow API reference]({{< ref workflow_api.md >}})
- Try out the full SDK examples:
- [Python example](https://github.com/dapr/python-sdk/tree/master/examples/demo_workflow)
- [JavaScript example](todo)
hhunter-ms marked this conversation as resolved.
Show resolved Hide resolved
- [.NET example](https://github.com/dapr/dotnet-sdk/tree/master/examples/Workflow)
- [Java example](https://github.com/dapr/java-sdk/tree/master/examples/src/main/java/io/dapr/examples/workflows)
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Dapr Workflow is currently in beta. [See known limitations for {{% dapr-latest-v

Now that you've [authored the workflow and its activities in your application]({{< ref howto-author-workflow.md >}}), you can start, terminate, and get information about the workflow using HTTP API calls. For more information, read the [workflow API reference]({{< ref workflow_api.md >}}).

{{< tabs Python ".NET" Java HTTP >}}
{{< tabs Python JavaScript ".NET" Java HTTP >}}

<!--Python-->
{{% codetab %}}
Expand Down Expand Up @@ -63,6 +63,24 @@ d.terminate_workflow(instance_id=instanceId, workflow_component=workflowComponen

{{% /codetab %}}

<!--JavaScript-->
{{% codetab %}}

Manage your workflow within your code. In the workflow example from the [Author a workflow]({{< ref "howto-author-workflow.md#write-the-application" >}}) guide, the workflow is registered in the code using the following APIs:
- **start_workflow**: Start an instance of a workflow
- **get_workflow**: Get information on the status of the workflow
- **pause_workflow**: Pauses or suspends a workflow instance that can later be resumed
- **resume_workflow**: Resumes a paused workflow instance
- **raise_workflow_event**: Raise an event on a workflow
- **purge_workflow**: Removes all metadata related to a specific workflow instance
- **terminate_workflow**: Terminate or stop a particular instance of a workflow

```javascript

```

{{% /codetab %}}

<!--NET-->
{{% codetab %}}

Expand Down Expand Up @@ -242,6 +260,7 @@ Learn more about these HTTP calls in the [workflow API reference guide]({{< ref
- [Try out the Workflow quickstart]({{< ref workflow-quickstart.md >}})
- Try out the full SDK examples:
- [Python example](https://github.com/dapr/python-sdk/blob/master/examples/demo_workflow/app.py)
- [JavaScript example](todo)
hhunter-ms marked this conversation as resolved.
Show resolved Hide resolved
- [.NET example](https://github.com/dapr/dotnet-sdk/tree/master/examples/Workflow)
- [Java example](https://github.com/dapr/java-sdk/tree/master/examples/src/main/java/io/dapr/examples/workflows)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,5 +195,6 @@ See the [Reminder usage and execution guarantees section]({{< ref "workflow-arch
- [Try out the Workflow quickstart]({{< ref workflow-quickstart.md >}})
- Try out the following examples:
- [Python](https://github.com/dapr/python-sdk/tree/master/examples/demo_workflow)
- [JavaScript example](todo)
- [.NET](https://github.com/dapr/dotnet-sdk/tree/master/examples/Workflow)
- [Java](https://github.com/dapr/java-sdk/tree/master/examples/src/main/java/io/dapr/examples/workflows)
Loading
Loading