본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

How to: 워크플로 작성하기 (Author workflows)

원문 보기 위키 갱신

Dapr Workflow 엔진이 실행하는 워크플로를 개발하고 작성하는 방법을 배워 봐요. 이 글은 Dapr Workflow 엔진이 실행하는 워크플로를 작성하는 방법에 대한 높은 수준의 개요를 제공합니다.

참고 (Note)

아직 하지 않았다면, workflow quickstart를 통해 워크플로를 사용하는 방법을 빠르게 둘러보는 것을 추천해요.

출처: Dapr 문서

본문

워크플로를 코드로 작성하기 (Author workflows as code)

Dapr Workflow 로직은 범용 프로그래밍 언어로 구현되므로, 다음과 같은 것이 가능해요.

  • 선호하는 프로그래밍 언어를 사용할 수 있어요 (새 DSL이나 YAML 스키마를 배울 필요가 없어요).
  • 언어의 표준 라이브러리에 접근할 수 있어요.
  • 자신만의 라이브러리와 추상화를 만들 수 있어요.
  • 디버거를 사용하고 로컬 변수를 검사할 수 있어요.
  • 애플리케이션 로직의 다른 부분처럼 워크플로에 대한 단위 테스트를 작성할 수 있어요.

Dapr 사이드카는 어떤 워크플로 정의도 로드하지 않습니다. 대신 사이드카는 단순히 워크플로의 실행을 구동하며, 모든 워크플로 액티비티를 애플리케이션의 일부로 남겨둡니다.

워크플로 액티비티 작성하기 (Write the workflow activities)

워크플로 액티비티는 워크플로에서 작업의 기본 단위이자, 비즈니스 프로세스에서 오케스트레이션되는 태스크입니다.

  • Python
  • JavaScript
  • .NET
  • Java
  • Go

워크플로가 수행하길 원하는 액티비티를 정의하세요. 액티비티는 함수 정의이며 입력과 출력을 가질 수 있어요. 다음 예제는 hello_act라는 카운터(액티비티)를 만들고, 사용자에게 현재 카운터 값을 알려줍니다. hello_act는 WorkflowActivityContext라는 클래스에서 파생된 함수입니다.

@wfr.activity(name='hello_act')
def hello_act(ctx: WorkflowActivityContext, wf_input):
global counter
counter += wf_input
print(f'New counter value is: {counter}!', flush=True)

컨텍스트에서 task chaining 워크플로 액티비티를 확인하세요.

워크플로가 수행하길 원하는 액티비티를 정의하세요. 액티비티는 WorkflowActivityContext 클래스에 감싸여 있으며, 이 클래스가 워크플로 액티비티를 구현합니다.

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;
}
}

컨텍스트에서 워크플로 액티비티를 확인하세요.

워크플로가 수행하길 원하는 액티비티를 정의하세요. 액티비티는 클래스 정의이며 입력과 출력을 가질 수 있습니다. 액티비티는 Dapr 클라이언트에 바인딩하는 것 같은 의존성 주입에도 참여해요. 아래 예제에서 호출되는 액티비티는 다음과 같습니다.

  • NotifyActivity: 새 주문에 대한 알림을 받습니다.
  • ReserveInventoryActivity: 새 주문을 충족할 충분한 재고가 있는지 확인합니다.
  • ProcessPaymentActivity: 주문에 대한 결제를 처리합니다. 주문 성공 알림을 보내기 위해 NotifyActivity를 포함합니다.

NotifyActivity

public class NotifyActivity : WorkflowActivity<Notification, object>
{
//...

public NotifyActivity(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger<NotifyActivity>();
}

//...
}

전체 NotifyActivity.cs 워크플로 액티비티 예제를 확인하세요.

ReserveInventoryActivity

public class ReserveInventoryActivity : WorkflowActivity<InventoryRequest, InventoryResult>
{
//...

public ReserveInventoryActivity(ILoggerFactory loggerFactory, DaprClient client)
{
this.logger = loggerFactory.CreateLogger<ReserveInventoryActivity>();
this.client = client;
}

//...

}

전체 ReserveInventoryActivity.cs 워크플로 액티비티 예제를 확인하세요.

ProcessPaymentActivity

public class ProcessPaymentActivity : WorkflowActivity<PaymentRequest, object>
{
//...
public ProcessPaymentActivity(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger<ProcessPaymentActivity>();
}

//...

}

전체 ProcessPaymentActivity.cs 워크플로 액티비티 예제를 확인하세요.

워크플로가 수행하길 원하는 액티비티를 정의하세요. 액티비티는 공개 DemoWorkflowActivity 클래스에 감싸여 있으며, 이 클래스가 워크플로 액티비티를 구현합니다.

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class DemoWorkflowActivity implements WorkflowActivity {

@Override
public DemoActivityOutput run(WorkflowActivityContext ctx) {
Logger logger = LoggerFactory.getLogger(DemoWorkflowActivity.class);
logger.info("Starting Activity: " + ctx.getName());

var message = ctx.getInput(DemoActivityInput.class).getMessage();
var newMessage = message + " World!, from Activity";
logger.info("Message Received from input: " + message);
logger.info("Sending message to output: " + newMessage);

logger.info("Sleeping for 5 seconds to simulate long running operation...");

try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

logger.info("Activity finished");

var output = new DemoActivityOutput(message, newMessage);
logger.info("Activity returned: " + output);

return output;
}
}

컨텍스트에서 Java SDK 워크플로 액티비티 예제를 확인하세요.

워크플로 액티비티 정의하기 (Define workflow activities)

워크플로가 수행하길 원하는 각 워크플로 액티비티를 정의하세요. 액티비티 입력은 ctx.GetInput으로 컨텍스트에서 역직렬화할 수 있어요. 액티비티는 ctx workflow.ActivityContext 파라미터를 받고 인터페이스와 error를 반환하도록 정의해야 합니다.

func BusinessActivity(ctx workflow.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return "", err
}

// Do something here
return "result", nil
}

워크플로 정의하기 (Define the workflow)

ctx *workflow.WorkflowContext 파라미터로 워크플로 함수를 정의하고 any와 error를 반환하세요. 정의한 액티비티를 워크플로 안에서 호출합니다.

func BusinessWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
if err := ctx.CallActivity(BusinessActivity, workflow.ActivityInput(input)).Await(&output); err != nil {
return nil, err
}
if err := ctx.WaitForExternalEvent("businessEvent", time.Minute*60).Await(&output); err != nil {
return nil, err
}

if err := ctx.CreateTimer(time.Second).Await(nil); err != nil {
return nil, nil
}
return output, nil
}

워크플로와 액티비티 등록하기 (Register workflows and activities)

애플리케이션이 워크플로를 실행하려면, 워크플로 오케스트레이터와 그 액티비티를 모두 워크플로 레지스트리에 등록해야 합니다. 이렇게 해야 Dapr이 워크플로 실행 시 어떤 함수를 호출할지 알 수 있어요.

func main() {
// Create a workflow registry
r := workflow.NewRegistry()

// Register the workflow orchestrator
if err := r.AddWorkflow(BusinessWorkflow); err != nil {
log.Fatal(err)
}
fmt.Println("BusinessWorkflow registered")

// Register the workflow activities
if err := r.AddActivity(BusinessActivity); err != nil {
log.Fatal(err)
}
fmt.Println("BusinessActivity registered")

// Create workflow client and start worker
wclient, err := client.NewWorkflowClient()
if err != nil {
log.Fatal(err)
}
fmt.Println("Worker initialized")

ctx, cancel := context.WithCancel(context.Background())
if err = wclient.StartWorker(ctx, r); err != nil {
log.Fatal(err)
}
fmt.Println("runner started")

// Your application logic continues here...
// Example: Start a workflow
instanceID, err := wclient.ScheduleWorkflow(ctx, "BusinessWorkflow", workflow.WithInput(1))
if err != nil {
log.Fatalf("failed to start workflow: %v", err)
}
fmt.Printf("workflow started with id: %v\n", instanceID)

// Stop workflow worker when done
cancel()
fmt.Println("workflow worker successfully shutdown")
}

등록에 대한 핵심 포인트는 다음과 같습니다.

  • 워크플로 레지스트리를 만들려면 workflow.NewRegistry()를 사용하세요.
  • 워크플로 함수를 등록하려면 r.AddWorkflow()를 사용하세요.
  • 액티비티 함수를 등록하려면 r.AddActivity()를 사용하세요.
  • 워크플로 클라이언트를 만들려면 client.NewWorkflowClient()를 사용하세요.
  • 워크플로 처리를 시작하려면 wclient.StartWorker()를 호출하세요.
  • 이름 붙은 워크플로 인스턴스를 스케줄하려면 wclient.ScheduleWorkflow를 사용하세요.

컨텍스트에서 Go SDK 워크플로 액티비티 예제를 확인하세요.

워크플로 작성하기 (Write the workflow)

다음으로, 워크플로에서 액티비티를 등록하고 호출하세요.

  • Python
  • JavaScript
  • .NET
  • Java
  • Go

hello_world_wf 함수는 입력·출력 파라미터 타입을 가진 DaprWorkflowContext라는 클래스에서 파생된 함수입니다. 또한 워크플로의 무거운 작업을 수행하고 워크플로 액티비티를 호출하는 yield 문을 포함합니다.

@wfr.workflow(name='hello_world_wf')
def hello_world_wf(ctx: DaprWorkflowContext, wf_input):
print(f'{wf_input}')
yield ctx.call_activity(hello_act, input=1)
yield ctx.call_activity(hello_act, input=10)
yield ctx.call_activity(hello_retryable_act, retry_policy=retry_policy)
yield ctx.call_child_workflow(child_retryable_wf, retry_policy=retry_policy)


event = ctx.wait_for_external_event(event_name)
timeout = ctx.create_timer(timedelta(seconds=30))
winner = yield when_any([event, timeout])

if winner == timeout:
print('Workflow timed out waiting for event')
return 'Timeout'

yield ctx.call_activity(hello_act, input=100)
yield ctx.call_activity(hello_act, input=1000)
return 'Completed'

컨텍스트에서 hello_world_wf 워크플로를 확인하세요.

다음으로, WorkflowRuntime 클래스로 워크플로를 등록하고 워크플로 런타임을 시작하세요.

export default class WorkflowRuntime {

//..
// Register workflow implementation for handling orchestrations
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, input: TInput): TOutput => {
const wfActivityContext = new WorkflowActivityContext(ctx);
return fn(wfActivityContext, input);
};
this.worker.addNamedActivity(name, activityWrapper);
return this;
}

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

}

컨텍스트에서 WorkflowRuntime을 확인하세요.

OrderProcessingWorkflow 클래스는 입력·출력 파라미터 타입을 가진 Workflow라는 기본 클래스에서 파생됩니다. 또한 워크플로의 무거운 작업을 수행하고 워크플로 액티비티를 호출하는 RunAsync 메서드를 포함합니다.

class OrderProcessingWorkflow : Workflow<OrderPayload, OrderResult>
{
public override async Task<OrderResult> RunAsync(WorkflowContext context, OrderPayload order)
{
//...

await context.CallActivityAsync(
nameof(NotifyActivity),
new Notification($"Received order {orderId} for {order.Name} at {order.TotalCost:c}"));

//...

InventoryResult result = await context.CallActivityAsync<InventoryResult>(
nameof(ReserveInventoryActivity),
new InventoryRequest(RequestId: orderId, order.Name, order.Quantity));
//...

await context.CallActivityAsync(
nameof(ProcessPaymentActivity),
new PaymentRequest(RequestId: orderId, order.TotalCost, "USD"));

await context.CallActivityAsync(
nameof(NotifyActivity),
new Notification($"Order {orderId} processed successfully!"));

// End the workflow with a success result
return new OrderResult(Processed: true);
}
}

OrderProcessingWorkflow.cs에서 전체 워크플로 예제를 확인하세요.

다음으로, WorkflowRuntimeBuilder로 워크플로를 등록하고 워크플로 런타임을 시작하세요.

public class DemoWorkflowWorker {

public static void main(String[] args) throws Exception {

// Register the Workflow with the builder.
WorkflowRuntimeBuilder builder = new WorkflowRuntimeBuilder().registerWorkflow(DemoWorkflow.class);
builder.registerActivity(DemoWorkflowActivity.class);

// Build and then start the workflow runtime pulling and executing tasks
try (WorkflowRuntime runtime = builder.build()) {
System.out.println("Start workflow runtime");
runtime.start();
}

System.exit(0);
}
}

컨텍스트에서 Java SDK 워크플로를 확인하세요.

ctx *workflow.WorkflowContext 파라미터로 워크플로 함수를 정의하고 any와 error를 반환하세요. 정의한 액티비티를 워크플로 안에서 호출합니다.

func BusinessWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
if err := ctx.CallActivity(BusinessActivity, workflow.ActivityInput(input)).Await(&output); err != nil {
return nil, err
}
if err := ctx.WaitForExternalEvent("businessEvent", time.Minute*60).Await(&output); err != nil {
return nil, err
}

if err := ctx.CreateTimer(time.Second).Await(nil); err != nil {
return nil, nil
}
return output, nil
}

컨텍스트에서 Go SDK 워크플로를 확인하세요.

애플리케이션 작성하기 (Write the application)

마지막으로, 워크플로를 사용해 애플리케이션을 구성하세요.

  • Python
  • JavaScript
  • .NET
  • Java
  • Go

다음 예제에서는 Python SDK를 사용한 기본 Python hello world 애플리케이션의 경우, 프로젝트 코드에 다음이 포함됩니다.

  • Python SDK 기능을 받는 DaprClient라는 Python 패키지.
  • 확장이 있는 빌더: WorkflowRuntime — 워크플로 런타임 등록 허용.
  • DaprWorkflowContext — 워크플로 생성 허용.
  • WorkflowActivityContext — 워크플로 액티비티 생성 허용.
  • API 호출. 아래 예제에서 이 호출들은 워크플로를 시작·일시 중지·재개·퍼지·완료합니다.
from datetime import timedelta
from time import sleep
from dapr.ext.workflow import (
WorkflowRuntime,
DaprWorkflowContext,
WorkflowActivityContext,
RetryPolicy,
DaprWorkflowClient,
when_any,
)
from dapr.conf import Settings
from dapr.clients.exceptions import DaprInternalError

settings = Settings()

counter = 0
retry_count = 0
child_orchestrator_count = 0
child_orchestrator_string = ''
child_act_retry_count = 0
instance_id = 'exampleInstanceID'
child_instance_id = 'childInstanceID'
workflow_name = 'hello_world_wf'
child_workflow_name = 'child_wf'
input_data = 'Hi Counter!'
event_name = 'event1'
event_data = 'eventData'
non_existent_id_error = 'no such instance exists'

retry_policy = RetryPolicy(
first_retry_interval=timedelta(seconds=1),
max_number_of_attempts=3,
backoff_coefficient=2,
max_retry_interval=timedelta(seconds=10),
retry_timeout=timedelta(seconds=100),
)

wfr = WorkflowRuntime()

@wfr.workflow(name='hello_world_wf')
def hello_world_wf(ctx: DaprWorkflowContext, wf_input):
print(f'{wf_input}')
yield ctx.call_activity(hello_act, input=1)
yield ctx.call_activity(hello_act, input=10)
yield ctx.call_activity(hello_retryable_act, retry_policy=retry_policy)
yield ctx.call_child_workflow(child_retryable_wf, retry_policy=retry_policy)


event = ctx.wait_for_external_event(event_name)
timeout = ctx.create_timer(timedelta(seconds=30))
winner = yield when_any([event, timeout])

if winner == timeout:
print('Workflow timed out waiting for event')
return 'Timeout'

yield ctx.call_activity(hello_act, input=100)
yield ctx.call_activity(hello_act, input=1000)
return 'Completed'

@wfr.activity(name='hello_act')
def hello_act(ctx: WorkflowActivityContext, wf_input):
global counter
counter += wf_input
print(f'New counter value is: {counter}!', flush=True)

@wfr.activity(name='hello_retryable_act')
def hello_retryable_act(ctx: WorkflowActivityContext):
global retry_count
if (retry_count % 2) == 0:
print(f'Retry count value is: {retry_count}!', flush=True)
retry_count += 1
raise ValueError('Retryable Error')
print(f'Retry count value is: {retry_count}! This print statement verifies retry', flush=True)
retry_count += 1

@wfr.workflow(name='child_retryable_wf')
def child_retryable_wf(ctx: DaprWorkflowContext):
global child_orchestrator_string, child_orchestrator_count
if not ctx.is_replaying:
child_orchestrator_count += 1
print(f'Appending {child_orchestrator_count} to child_orchestrator_string!', flush=True)
child_orchestrator_string += str(child_orchestrator_count)
yield ctx.call_activity(
act_for_child_wf, input=child_orchestrator_count, retry_policy=retry_policy
)
if child_orchestrator_count < 3:
raise ValueError('Retryable Error')

@wfr.activity(name='act_for_child_wf')
def act_for_child_wf(ctx: WorkflowActivityContext, inp):
global child_orchestrator_string, child_act_retry_count
inp_char = chr(96 + inp)
print(f'Appending {inp_char} to child_orchestrator_string!', flush=True)
child_orchestrator_string += inp_char
if child_act_retry_count % 2 == 0:
child_act_retry_count += 1
raise ValueError('Retryable Error')
child_act_retry_count += 1

def main():
wfr.start()
wf_client = DaprWorkflowClient()

print('==========Start Counter Increase as per Input:==========')
wf_client.schedule_new_workflow(
workflow=hello_world_wf, input=input_data, instance_id=instance_id
)

wf_client.wait_for_workflow_start(instance_id)


sleep(12)

assert counter == 11
assert retry_count == 2
assert child_orchestrator_string == '1aa2bb3cc'


wf_client.pause_workflow(instance_id=instance_id)
metadata = wf_client.get_workflow_state(instance_id=instance_id)
print(f'Get response from {workflow_name} after pause call: {metadata.runtime_status.name}')


wf_client.resume_workflow(instance_id=instance_id)
metadata = wf_client.get_workflow_state(instance_id=instance_id)
print(f'Get response from {workflow_name} after resume call: {metadata.runtime_status.name}')

sleep(2) # Give the workflow time to reach the event wait state
wf_client.raise_workflow_event(instance_id=instance_id, event_name=event_name, data=event_data)

print('========= Waiting for Workflow completion', flush=True)
try:
state = wf_client.wait_for_workflow_completion(instance_id, timeout_in_seconds=30)
if state.runtime_status.name == 'COMPLETED':
print('Workflow completed! Result: {}'.format(state.serialized_output.strip('"')))
else:
print(f'Workflow failed! Status: {state.runtime_status.name}')
except TimeoutError:
print('*** Workflow timed out!')

wf_client.purge_workflow(instance_id=instance_id)
try:
wf_client.get_workflow_state(instance_id=instance_id)
except DaprInternalError as err:
if non_existent_id_error in err._message:
print('Instance Successfully Purged')

sleep(10000)
wfr.shutdown()

if __name__ == '__main__':
main()

다음 예제는 JavaScript SDK를 사용한 기본 JavaScript 애플리케이션입니다. 이 예제처럼 프로젝트 코드에는 다음이 포함됩니다.

  • 확장이 있는 빌더: WorkflowRuntime — 워크플로와 워크플로 액티비티 등록 허용.
  • DaprWorkflowContext — 워크플로 생성 허용.
  • WorkflowActivityContext — 워크플로 액티비티 생성 허용.
  • API 호출. 다음 예제는 워크플로 API를 사용하는 간단한 프로젝트입니다.
mkdir my-wf && cd my-wf
npm init -y
npm i @dapr/dapr @microsoft/durabletask-js
npm i -D typescript ts-node @types/node

다음 tsconfig.json 파일을 만드세요.

{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "Node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src"]
}

다음 src/app.ts 파일을 만드세요.

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

const workflowClient = new DaprWorkflowClient();
const workflowRuntime = new WorkflowRuntime();

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

// simple workflow: call the activity 3 times
const sequence: TWorkflow = async function* (ctx: WorkflowContext): any {
const out: string[] = [];
out.push(yield ctx.callActivity(hello, "Tokyo"));
out.push(yield ctx.callActivity(hello, "Seattle"));
out.push(yield ctx.callActivity(hello, "London"));
out.push(yield ctx.waitForExternalEvent("continue"));
return out;
};

async function main() {
workflowRuntime.registerWorkflow(sequence).registerActivity(hello);
await workflowRuntime.start();

const id = await workflowClient.scheduleNewWorkflow(sequence);
console.log("Scheduled:", id);

workflowClient.raiseEvent(id, "continue", "Go go go!");

const state = await workflowClient.waitForWorkflowCompletion(id, undefined, 30);
console.log("Done:", state?.runtimeStatus, "output:", state?.serializedOutput);

await new Promise(f => setTimeout(f, 100000));

await workflowRuntime.stop();
await workflowClient.stop();

}

main().catch((e) => { console.error(e); });

다음 Program.cs 예제에서는 .NET SDK를 사용한 기본 ASP.NET 주문 처리 애플리케이션의 경우, 프로젝트 코드에 다음이 포함됩니다.

  • .NET SDK 기능을 받는 Dapr.Workflow라는 NuGet 패키지.
  • AddDaprWorkflow라는 확장 메서드가 있는 빌더. 이를 통해 워크플로와 워크플로 액티비티(워크플로가 스케줄할 수 있는 태스크)를 등록할 수 있어요.
  • HTTP API 호출 — 하나는 새 주문 제출용, 하나는 기존 주문 상태 확인용.
using Dapr.Workflow;
//...

// Dapr Workflows are registered as part of the service configuration
builder.Services.AddDaprWorkflow(options =>
{
// Note that it's also possible to register a lambda function as the workflow
// or activity implementation instead of a class.
options.RegisterWorkflow<OrderProcessingWorkflow>();

// These are the activities that get invoked by the workflow(s).
options.RegisterActivity<NotifyActivity>();
options.RegisterActivity<ReserveInventoryActivity>();
options.RegisterActivity<ProcessPaymentActivity>();
});

WebApplication app = builder.Build();

// POST starts new order workflow instance
app.MapPost("/orders", async (DaprWorkflowClient client, [FromBody] OrderPayload orderInfo) =>
{
if (orderInfo?.Name == null)
{
return Results.BadRequest(new
{
message = "Order data was missing from the request",
example = new OrderPayload("Paperclips", 99.95),
});
}

//...
});

// GET fetches state for order workflow to report status
app.MapGet("/orders/{orderId}", async (string orderId, DaprWorkflowClient client) =>
{
WorkflowState state = await client.GetWorkflowStateAsync(orderId, true);
if (!state.Exists)
{
return Results.NotFound($"No order with ID = '{orderId}' was found.");
}

var httpResponsePayload = new
{
details = state.ReadInputAs<OrderPayload>(),
status = state.RuntimeStatus.ToString(),
result = state.ReadOutputAs<OrderResult>(),
};

//...
}).WithName("GetOrderInfoEndpoint");

app.Run();

다음 예제처럼 Java SDK와 Dapr Workflow를 사용한 hello-world 애플리케이션에는 다음이 포함됩니다.

  • Java SDK 클라이언트 기능을 받는 io.dapr.workflows.client라는 Java 패키지.
  • io.dapr.workflows.Workflow 임포트.
  • Workflow를 확장하는 DemoWorkflow 클래스.
  • 입력과 출력으로 워크플로 생성.
  • API 호출. 아래 예제에서 이 호출들은 워크플로를 시작하고 워크플로 액티비티를 호출합니다.
package io.dapr.examples.workflows;

import com.microsoft.durabletask.CompositeTaskFailedException;
import com.microsoft.durabletask.Task;
import com.microsoft.durabletask.TaskCanceledException;
import io.dapr.workflows.Workflow;
import io.dapr.workflows.WorkflowStub;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

/**
* Implementation of the DemoWorkflow for the server side.
*/
public class DemoWorkflow extends Workflow {
@Override
public WorkflowStub create() {
return ctx -> {
ctx.getLogger().info("Starting Workflow: " + ctx.getName());
// ...
ctx.getLogger().info("Calling Activity...");
var input = new DemoActivityInput("Hello Activity!");
var output = ctx.callActivity(DemoWorkflowActivity.class.getName(), input, DemoActivityOutput.class).await();
// ...
};
}
}

컨텍스트에서 전체 Java SDK 워크플로 예제를 확인하세요.

다음 예제처럼 Go SDK와 Dapr Workflow를 사용한 hello-world 애플리케이션에는 다음이 포함됩니다.

  • Go SDK 클라이언트 기능을 받는 client라는 Go 패키지.
  • BusinessWorkflow 메서드.
  • 입력과 출력으로 워크플로 생성.
  • API 호출. 아래 예제에서 이 호출들은 워크플로를 시작하고 워크플로 액티비티를 호출합니다.
package main

import (
"context"
"errors"
"fmt"
"log"
"strconv"
"time"

"github.com/dapr/durabletask-go/workflow"
"github.com/dapr/go-sdk/client"
)

var stage = 0
var failActivityTries = 0

func main() {
r := workflow.NewRegistry()

if err := r.AddWorkflow(BusinessWorkflow); err != nil {
log.Fatal(err)
}
fmt.Println("BusinessWorkflow registered")

if err := r.AddActivity(BusinessActivity); err != nil {
log.Fatal(err)
}
fmt.Println("BusinessActivity registered")

if err := r.AddActivity(FailActivity); err != nil {
log.Fatal(err)
}
fmt.Println("FailActivity registered")

wclient, err := client.NewWorkflowClient()
if err != nil {
log.Fatal(err)
}
fmt.Println("Worker initialized")

ctx, cancel := context.WithCancel(context.Background())
if err = wclient.StartWorker(ctx, r); err != nil {
log.Fatal(err)
}
fmt.Println("runner started")

// Start workflow test
// Set the start time to the current time to not wait for the workflow to
// "start". This is useful for increasing the throughput of creating
// workflows.
// workflow.WithStartTime(time.Now())
instanceID, err := wclient.ScheduleWorkflow(ctx, "BusinessWorkflow", workflow.WithInstanceID("a7a4168d-3a1c-41da-8a4f-e7f6d9c718d9"), workflow.WithInput("1"))
if err != nil {
log.Fatalf("failed to start workflow: %v", err)
}
fmt.Printf("workflow started with id: %v\n", instanceID)

// Pause workflow test
err = wclient.SuspendWorkflow(ctx, instanceID, "")
if err != nil {
log.Fatalf("failed to pause workflow: %v", err)
}

respFetch, err := wclient.FetchWorkflowMetadata(ctx, instanceID, workflow.WithFetchPayloads(true))
if err != nil {
log.Fatalf("failed to fetch workflow: %v", err)
}

if respFetch.RuntimeStatus != workflow.StatusSuspended {
log.Fatalf("workflow not paused: %s: %v", respFetch.RuntimeStatus, respFetch)
}

fmt.Printf("workflow paused\n")

// Resume workflow test
err = wclient.ResumeWorkflow(ctx, instanceID, "")
if err != nil {
log.Fatalf("failed to resume workflow: %v", err)
}

respFetch, err = wclient.FetchWorkflowMetadata(ctx, instanceID, workflow.WithFetchPayloads(true))
if err != nil {
log.Fatalf("failed to get workflow: %v", err)
}

if respFetch.RuntimeStatus != workflow.StatusRunning {
log.Fatalf("workflow not running")
}

fmt.Println("workflow resumed")

fmt.Printf("stage: %d\n", stage)

// Raise Event
err = wclient.RaiseEvent(ctx, instanceID, "businessEvent", workflow.WithEventPayload("testData"))
if err != nil {
fmt.Printf("failed to raise event: %v", err)
}

fmt.Println("workflow event raised")

time.Sleep(time.Second) // allow workflow to advance

fmt.Printf("stage: %d\n", stage)

_, err = wclient.WaitForWorkflowCompletion(ctx, instanceID)
if err != nil {
log.Fatalf("failed to wait for workflow: %v", err)
}

fmt.Printf("fail activity executions: %d\n", failActivityTries)

respFetch, err = wclient.FetchWorkflowMetadata(ctx, instanceID, workflow.WithFetchPayloads(true))
if err != nil {
log.Fatalf("failed to get workflow: %v", err)
}

fmt.Printf("workflow status: %v\n", respFetch.String())

// Purge workflow test
err = wclient.PurgeWorkflowState(ctx, instanceID)
if err != nil {
log.Fatalf("failed to purge workflow: %v", err)
}

respFetch, err = wclient.FetchWorkflowMetadata(ctx, instanceID, workflow.WithFetchPayloads(true))
if err == nil || respFetch != nil {
log.Fatalf("failed to purge workflow: %v", err)
}

fmt.Println("workflow purged")

fmt.Printf("stage: %d\n", stage)

// Terminate workflow test
id, err := wclient.ScheduleWorkflow(ctx, "BusinessWorkflow", workflow.WithInstanceID("a7a4168d-3a1c-41da-8a4f-e7f6d9c718d9"), workflow.WithInput("1"))
if err != nil {
log.Fatalf("failed to start workflow: %v", err)
}
fmt.Printf("workflow started with id: %v\n", instanceID)

metadata, err := wclient.WaitForWorkflowStart(ctx, id)
if err != nil {
log.Fatalf("failed to get workflow: %v", err)
}
fmt.Printf("workflow status: %s\n", metadata.String())

err = wclient.TerminateWorkflow(ctx, id)
if err != nil {
log.Fatalf("failed to terminate workflow: %v", err)
}
fmt.Println("workflow terminated")

err = wclient.PurgeWorkflowState(ctx, id)
if err != nil {
log.Fatalf("failed to purge workflow: %v", err)
}
fmt.Println("workflow purged")

<-ctx.Done()
cancel()

fmt.Println("workflow worker successfully shutdown")
}

func BusinessWorkflow(ctx *workflow.WorkflowContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
if err := ctx.CallActivity(BusinessActivity, workflow.WithActivityInput(input)).Await(&output); err != nil {
return nil, err
}

err := ctx.WaitForExternalEvent("businessEvent", time.Minute*60).Await(&output)
if err != nil {
return nil, err
}

if err := ctx.CallActivity(BusinessActivity, workflow.WithActivityInput(input)).Await(&output); err != nil {
return nil, err
}

if err := ctx.CallActivity(FailActivity, workflow.WithActivityRetryPolicy(&workflow.RetryPolicy{
MaxAttempts: 3,
InitialRetryInterval: 100 * time.Millisecond,
BackoffCoefficient: 2,
MaxRetryInterval: 1 * time.Second,
})).Await(nil); err == nil {
return nil, fmt.Errorf("unexpected no error executing fail activity")
}

return output, nil
}

func BusinessActivity(ctx workflow.ActivityContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return "", err
}

iinput, err := strconv.Atoi(input)
if err != nil {
return "", err
}

stage += iinput

return fmt.Sprintf("Stage: %d", stage), nil
}

func FailActivity(ctx workflow.ActivityContext) (any, error) {
failActivityTries += 1
return nil, errors.New("dummy activity error")
}

컨텍스트에서 전체 Go SDK 워크플로 예제를 확인하세요.

중요 (Important)

리플레이 기반 워크플로의 실행 방식 때문에, I/O나 시스템 상호작용 같은 작업을 하는 로직은 액티비티 안에 작성하게 됩니다. 한편 워크플로 메서드는 그 액티비티들을 오케스트레이션하는 일만 합니다.

워크플로 실행 & Diagrid Dev Dashboard로 워크플로 실행 검사하기 (Run the workflow & inspect the workflow execution with the Diagrid Dev Dashboard)

IDE나 Dapr CLI(여러 애플리케이션을 시작하려면 Dapr multi-app run, 단일 애플리케이션이면 일반 Dapr run 명령)로 워크플로 애플리케이션을 시작하고, 새 워크플로 인스턴스를 스케줄하세요. 로컬 Diagrid Dev Dashboard로 워크플로 상태를 시각화·검사하고, 상세 워크플로 실행 히스토리를 들여다볼 수 있어요. 대시보드는 독립형 도구로 실행되며, Dapr 워크플로가 사용하는 상태 저장소(기본적으로 로컬 Redis 인스턴스)에 연결됩니다.

터미널에서 대시보드를 다운로드·설치하세요: - Linux/MacOS

  • Windows
curl -sSL https://raw.githubusercontent.com/diagridio/dev-dashboard/main/scripts/install.sh | sh
iwr -useb https://raw.githubusercontent.com/diagridio/dev-dashboard/main/scripts/install.ps1 | iex

Diagrid Dev Dashboard를 시작합니다.

diagrid-dev-dashboard

대시보드는 브라우저에서 http://localhost:9090에 열립니다. Workflows 페이지로 이동해 워크플로를 검사하세요.

Dapr CLI로 워크플로 테스트하기 (Testing the workflow via the Dapr CLI)

워크플로를 작성한 뒤 Dapr CLI로 테스트할 수 있습니다.

  • Python
  • Javascript
  • .NET
  • Java
  • Go

워크플로 애플리케이션 실행 (Run the workflow application)

dapr run --app-id workflow-app python3 app.py

애플리케이션이 실행 중인지 확인하세요.

dapr list

워크플로 실행 (Run the workflow)

dapr workflow run hello_world_wf --app-id workflow-app --input 'hello world' --instance-id test-run

워크플로 상태 확인 (Check the workflow status)

dapr workflow list --app-id workflow-app -o wide

완료된 워크플로 확인 (Check completed workflows)

dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

워크플로 히스토리 보기 (View workflow history)

dapr workflow history --app-id workflow-app test-run

워크플로 애플리케이션 실행 (Run the workflow application)

dapr run --app-id workflow-app npx ts-node src/app.ts

애플리케이션이 실행 중인지 확인하세요.

dapr list

워크플로 실행 (Run the workflow)

dapr workflow run sequence --app-id workflow-app --input 'hello world' --instance-id test-run

워크플로 상태 확인 (Check the workflow status)

dapr workflow list --app-id workflow-app -o wide

대기 중인 외부 이벤트 발생 (Raise the waiting external event)

dapr workflow raise-event --app-id workflow-app test-run/businessEvent

완료된 워크플로 확인 (Check completed workflows)

dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

워크플로 히스토리 보기 (View workflow history)

dapr workflow history --app-id workflow-app test-run

워크플로 애플리케이션 실행 (Run the workflow application)

dapr run --app-id workflow-app dotnet run

애플리케이션이 실행 중인지 확인하세요.

dapr list

워크플로 실행 (Run the workflow)

dapr workflow run OrderProcessingWorkflow --app-id workflow-app --instance-id test-run --input '{"name": "Paperclips", "totalCost": 99.95}'

워크플로 상태 확인 (Check the workflow status)

dapr workflow list --app-id workflow-app -o wide

대기 중인 외부 이벤트 발생 (Raise the waiting external event)

dapr workflow raise-event --app-id workflow-app test-run/incoming-purchase-order --input '{"name": "Paperclips", "totalCost": 99.95}'

완료된 워크플로 확인 (Check completed workflows)

dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

워크플로 히스토리 보기 (View workflow history)

dapr workflow history --app-id workflow-app test-run

워크플로 애플리케이션 실행 (Run the workflow application)

dapr run --app-id workflow-app -- java -jar target/WorkflowService-0.0.1-SNAPSHOT.jar

애플리케이션이 실행 중인지 확인하세요.

dapr list

워크플로 실행 (Run the workflow)

dapr workflow run DemoWorkflow --app-id workflow-app --instance-id test-run --input "input data"

워크플로 상태 확인 (Check the workflow status)

dapr workflow list --app-id workflow-app -o wide

대기 중인 외부 이벤트 발생 (Raise the waiting external event)

dapr workflow raise-event --app-id workflow-app test-run/TestEvent --input 'TestEventPayload'
dapr workflow raise-event --app-id workflow-app test-run/event1 --input 'TestEvent 1 Payload'
dapr workflow raise-event --app-id workflow-app test-run/event2 --input 'TestEvent 2 Payload'
dapr workflow raise-event --app-id workflow-app test-run/event3 --input 'TestEvent 3 Payload'

완료된 워크플로 확인 (Check completed workflows)

dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

워크플로 히스토리 보기 (View workflow history)

dapr workflow history --app-id workflow-app test-run

워크플로 애플리케이션 실행 (Run the workflow application)

dapr run --app-id workflow-app go run main.go

애플리케이션이 실행 중인지 확인하세요.

dapr list

워크플로 실행 (Run the workflow)

dapr workflow run BusinessWorkflow --app-id workflow-app --input '1' --instance-id test-run

워크플로 상태 확인 (Check the workflow status)

dapr workflow list --app-id workflow-app -o wide

대기 중인 외부 이벤트 발생 (Raise the waiting external event)

dapr workflow raise-event --app-id workflow-app test-run/businessEvent

완료된 워크플로 확인 (Check completed workflows)

dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

워크플로 히스토리 보기 (View workflow history)

dapr workflow history test-run --app-id workflow-app

워크플로 실행 모니터링 (Monitor Workflow Execution)

dapr workflow list --app-id workflow-app --filter-status RUNNING -o wide
dapr workflow list --app-id workflow-app --filter-status FAILED -o wide
dapr workflow list --app-id workflow-app --filter-status COMPLETED -o wide

외부 이벤트 테스트하기 (Test External Events)


dapr workflow raise-event <instance-id>/ApprovalReceived \
--app-id workflow-app \
--input '{"approved": true, "approver": "manager@company.com"}'

실패한 워크플로 디버깅 (Debug Failed Workflows)


dapr workflow list --app-id workflow-app --filter-status FAILED --output wide


dapr workflow history <failed-instance-id> --app-id workflow-app --output json


dapr workflow rerun <failed-instance-id> --app-id workflow-app --input '<new-input-json-data>'

다음 단계 (Next steps)

이제 워크플로를 작성했으니, 관리하는 방법을 배워 보세요. Manage workflows >>

  • Workflow 개요
  • 전체 SDK 예제 확인: Python 예제
  • JavaScript 예제
  • .NET 예제
  • Java 예제
  • Go 예제

더 알아보기 (Learn more)