How to pass workflow.Context to the Cadence activity

Issue

I would like to put workflow.Sleep call in one of my Cadence activities to be able to test it properly (and simulate error result coming from Sleep function).

Two important things which I noticed before implementing:

My tries:

1. First try

import "go.uber.org/cadence/workflow"

// Activity:    
func (s *MyActivities) WorkflowSleep(_ context.Context, workflowCtx workflow.Context, duration time.Duration) error {
    return workflow.Sleep(workflowCtx, duration)
}

// In workflow; ctx has type workflow.Context:
    err := workflow.ExecuteActivity(ctx, myActivities.WorkflowSleep, ctx, duration).Get(ctx, nil)

Error:

"error":"unable to decode the activity function input bytes with error: unable to decode argument: 0, *internal.Context, with json error: json: cannot unmarshal object into Go value of type internal.Context for function

2. Second try

import "go.uber.org/cadence/workflow"

// Activity:    
func (s *MyActivities) WorkflowSleep(workflowCtx workflow.Context, duration time.Duration) error {
    return workflow.Sleep(workflowCtx, duration)
}

// In workflow; ctx has type workflow.Context:
    err := workflow.ExecuteActivity(ctx, myActivities.WorkflowSleep, duration).Get(ctx, nil)

Error:

"PanicError":"reflect: Call with too few input arguments"

Question

Is it possible to use workflow.Sleep inside any activity?

Solution

Is it possible to use workflow.Sleep inside any activity?

No, it’s NOT allowed to use workflow.Sleep in activity code.

Workflow.Sleep is only allowed in workflow code.
More general, all the APIs in workflow package are ONLY allowed in workflow code.

The workflow code will be executed within decision task, and the workflow threads/coroutines(special kind of goroutines) are managed by Cadence. This is how those APIs in workflow package works. Without decision tasks and workflow threads/coroutines, those API won’t work properly.

The activity code on the other hand, is just purely normal code that you should use regular native library or dependency to implement the logic. For example, you can use time.Sleep in activity code.

Answered By – Long Quanzheng

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.