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

Async Updates and the Poll API #4309

Merged
merged 6 commits into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
82 changes: 82 additions & 0 deletions service/history/api/pollupdate/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package pollupdate

import (
"context"
"fmt"

"go.temporal.io/api/serviceerror"
"go.temporal.io/api/workflowservice/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/service/history/api"
"go.temporal.io/server/service/history/workflow"
"go.temporal.io/server/service/history/workflow/update"
)

func Invoke(
ctx context.Context,
req *historyservice.PollWorkflowExecutionUpdateRequest,
ctxLookup api.WorkflowConsistencyChecker,
) (*historyservice.PollWorkflowExecutionUpdateResponse, error) {
updateRef := req.GetRequest().GetUpdateRef()
wfexec := updateRef.GetWorkflowExecution()
upd, ok, err := func() (*update.Update, bool, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this? To use defer?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, for defer.

wfctx, err := ctxLookup.GetWorkflowContext(
ctx,
nil,
api.BypassMutableStateConsistencyPredicate,
definition.NewWorkflowKey(
req.GetNamespaceId(),
wfexec.GetWorkflowId(),
wfexec.GetRunId(),
),
workflow.LockPriorityHigh,
)
if err != nil {
return nil, false, err
}
release := wfctx.GetReleaseFn()
defer release(nil)
upd, found := wfctx.GetUpdateRegistry(ctx).Find(ctx, updateRef.UpdateId)
return upd, found, nil
}()
if err != nil {
return nil, err
}
if !ok {
return nil, serviceerror.NewNotFound(fmt.Sprintf("update %q not found", updateRef.GetUpdateId()))
}
outcome, err := upd.WaitOutcome(ctx)
if err != nil {
return nil, err
}
return &historyservice.PollWorkflowExecutionUpdateResponse{
Response: &workflowservice.PollWorkflowExecutionUpdateResponse{
Outcome: outcome,
},
}, nil
}
184 changes: 184 additions & 0 deletions service/history/api/pollupdate/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package pollupdate_test

import (
"context"
"testing"
"time"

"github.com/stretchr/testify/require"
commonpb "go.temporal.io/api/common/v1"
failurepb "go.temporal.io/api/failure/v1"
"go.temporal.io/api/serviceerror"
updatepb "go.temporal.io/api/update/v1"
"go.temporal.io/api/workflowservice/v1"
clockspb "go.temporal.io/server/api/clock/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/service/history/api"
"go.temporal.io/server/service/history/api/pollupdate"
"go.temporal.io/server/service/history/workflow"
wcache "go.temporal.io/server/service/history/workflow/cache"
"go.temporal.io/server/service/history/workflow/update"
)

type (
mockWFConsistencyChecker struct {
api.WorkflowConsistencyChecker
GetWorkflowContextFunc func(
ctx context.Context,
reqClock *clockspb.VectorClock,
consistencyPredicate api.MutableStateConsistencyPredicate,
workflowKey definition.WorkflowKey,
lockPriority workflow.LockPriority,
) (api.WorkflowContext, error)
}

mockAPICtx struct {
api.WorkflowContext
GetUpdateRegistryFunc func(context.Context) update.Registry
GetReleaseFnFunc func() wcache.ReleaseCacheFunc
}

mockReg struct {
update.Registry
FindFunc func(context.Context, string) (*update.Update, bool)
}

mockUpdateEventStore struct {
update.EventStore
}
)

func (mockUpdateEventStore) OnAfterCommit(f func(context.Context)) { f(context.TODO()) }
func (mockUpdateEventStore) OnAfterRollback(f func(context.Context)) {}

func (m mockWFConsistencyChecker) GetWorkflowContext(
ctx context.Context,
clock *clockspb.VectorClock,
pred api.MutableStateConsistencyPredicate,
wfKey definition.WorkflowKey,
prio workflow.LockPriority,
) (api.WorkflowContext, error) {
return m.GetWorkflowContextFunc(ctx, clock, pred, wfKey, prio)
}

func (m mockAPICtx) GetReleaseFn() wcache.ReleaseCacheFunc {
return m.GetReleaseFnFunc()
}

func (m mockAPICtx) GetUpdateRegistry(ctx context.Context) update.Registry {
return m.GetUpdateRegistryFunc(ctx)
}

func (m mockReg) Find(ctx context.Context, updateID string) (*update.Update, bool) {
return m.FindFunc(ctx, updateID)
}

func TestPollOutcome(t *testing.T) {
reg := mockReg{}
apiCtx := mockAPICtx{
GetReleaseFnFunc: func() wcache.ReleaseCacheFunc { return func(error) {} },
GetUpdateRegistryFunc: func(context.Context) update.Registry {
return reg
},
}
wfcc := mockWFConsistencyChecker{
GetWorkflowContextFunc: func(
ctx context.Context,
reqClock *clockspb.VectorClock,
consistencyPredicate api.MutableStateConsistencyPredicate,
workflowKey definition.WorkflowKey,
lockPriority workflow.LockPriority,
) (api.WorkflowContext, error) {
return apiCtx, nil
},
}

updateID := t.Name() + "-update-id"
req := historyservice.PollWorkflowExecutionUpdateRequest{
Request: &workflowservice.PollWorkflowExecutionUpdateRequest{
UpdateRef: &updatepb.UpdateRef{
WorkflowExecution: &commonpb.WorkflowExecution{
WorkflowId: t.Name() + "-workflow-id",
RunId: t.Name() + "-run-id",
},
UpdateId: updateID,
},
},
}

t.Run("update not found", func(t *testing.T) {
reg.FindFunc = func(ctx context.Context, updateID string) (*update.Update, bool) {
return nil, false
}
_, err := pollupdate.Invoke(context.TODO(), &req, wfcc)
var notfound *serviceerror.NotFound
require.ErrorAs(t, err, &notfound)
})
t.Run("future timeout", func(t *testing.T) {
reg.FindFunc = func(ctx context.Context, updateID string) (*update.Update, bool) {
return update.New(updateID, func() {}), true
}
ctx, cncl := context.WithTimeout(context.Background(), 5*time.Millisecond)
defer cncl()
_, err := pollupdate.Invoke(ctx, &req, wfcc)
require.Error(t, err)
})
t.Run("get an outcome", func(t *testing.T) {
upd := update.New(updateID, func() {})
reg.FindFunc = func(ctx context.Context, updateID string) (*update.Update, bool) {
return upd, true
}
reqMsg := updatepb.Request{
Meta: &updatepb.Meta{UpdateId: updateID},
Input: &updatepb.Input{Name: "not_empty"},
}
fail := failurepb.Failure{Message: "intentional failure in " + t.Name()}
wantOutcome := updatepb.Outcome{Value: &updatepb.Outcome_Failure{Failure: &fail}}
rejMsg := updatepb.Rejection{
RejectedRequestMessageId: updateID + "/request",
RejectedRequest: &reqMsg,
Failure: &fail,
}

errCh := make(chan error, 1)
respCh := make(chan *historyservice.PollWorkflowExecutionUpdateResponse, 1)
go func() {
resp, err := pollupdate.Invoke(context.TODO(), &req, wfcc)
errCh <- err
respCh <- resp
}()

evStore := mockUpdateEventStore{}
require.NoError(t, upd.OnMessage(context.TODO(), &reqMsg, evStore))
require.NoError(t, upd.OnMessage(context.TODO(), &rejMsg, evStore))

require.NoError(t, <-errCh)
resp := <-respCh
require.Equal(t, &wantOutcome, resp.GetResponse().Outcome)
})
}
28 changes: 27 additions & 1 deletion service/history/api/updateworkflow/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@ package updateworkflow

import (
"context"
"fmt"
"time"

commonpb "go.temporal.io/api/common/v1"
"go.temporal.io/api/serviceerror"
updatepb "go.temporal.io/api/update/v1"
"go.temporal.io/api/workflowservice/v1"

enumspb "go.temporal.io/api/enums/v1"
enumsspb "go.temporal.io/server/api/enums/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/api/matchingservice/v1"
Expand All @@ -42,6 +45,7 @@ import (
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/shard"
"go.temporal.io/server/service/history/workflow"
"go.temporal.io/server/service/history/workflow/update"
)

func Invoke(
Expand All @@ -52,6 +56,28 @@ func Invoke(
matchingClient matchingservice.MatchingServiceClient,
) (_ *historyservice.UpdateWorkflowExecutionResponse, retErr error) {

var waitLifecycleStage func(ctx context.Context, u *update.Update) (*updatepb.Outcome, error)
waitStage := req.GetRequest().GetWaitPolicy().GetLifecycleStage()
switch waitStage {
case enumspb.UPDATE_WORKFLOW_EXECUTION_LIFECYCLE_STAGE_ACCEPTED:
waitLifecycleStage = func(
ctx context.Context,
u *update.Update,
) (*updatepb.Outcome, error) {
return u.WaitAccepted(ctx)
}
case enumspb.UPDATE_WORKFLOW_EXECUTION_LIFECYCLE_STAGE_COMPLETED:
waitLifecycleStage = func(
ctx context.Context,
u *update.Update,
) (*updatepb.Outcome, error) {
return u.WaitOutcome(ctx)
}
default:
return nil, serviceerror.NewUnimplemented(
fmt.Sprintf("%v is not implemented", waitStage))
}

weCtx, err := workflowConsistencyChecker.GetWorkflowContext(
ctx,
nil,
Expand Down Expand Up @@ -114,7 +140,7 @@ func Invoke(
weCtx.GetReleaseFn()(nil)
}

updOutcome, err := upd.WaitOutcome(ctx)
updOutcome, err := waitLifecycleStage(ctx, upd)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions service/history/historyEngine.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"go.opentelemetry.io/otel/trace"
commonpb "go.temporal.io/api/common/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"

"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/api/matchingservice/v1"
Expand All @@ -58,6 +57,7 @@ import (
"go.temporal.io/server/service/history/api/deleteworkflow"
"go.temporal.io/server/service/history/api/describemutablestate"
"go.temporal.io/server/service/history/api/describeworkflow"
"go.temporal.io/server/service/history/api/pollupdate"
"go.temporal.io/server/service/history/api/queryworkflow"
"go.temporal.io/server/service/history/api/reapplyevents"
"go.temporal.io/server/service/history/api/recordactivitytaskheartbeat"
Expand Down Expand Up @@ -549,7 +549,7 @@ func (e *historyEngineImpl) PollWorkflowExecutionUpdate(
ctx context.Context,
req *historyservice.PollWorkflowExecutionUpdateRequest,
) (*historyservice.PollWorkflowExecutionUpdateResponse, error) {
return nil, serviceerror.NewUnimplemented("PollWorkflowExecutionUpdate not implemented")
return pollupdate.Invoke(ctx, req, e.workflowConsistencyChecker)
}

// RemoveSignalMutableState remove the signal request id in signal_requested for deduplicate
Expand Down
10 changes: 7 additions & 3 deletions service/history/workflow/update/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"go.temporal.io/api/serviceerror"
updatepb "go.temporal.io/api/update/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
"go.temporal.io/server/common/future"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/metrics"
)
Expand Down Expand Up @@ -245,9 +246,12 @@ func (r *RegistryImpl) findLocked(ctx context.Context, id string) (*Update, bool
if info.GetCompletedPointer() != nil {
// Completed, create the Update object but do not add to registry. this
// should not happen often.
return newCompleted(id, func(ctx context.Context) (*updatepb.Outcome, error) {
return r.store.GetUpdateOutcome(ctx, id)
}, withInstrumentation(&r.instrumentation)), true
fut := future.NewReadyFuture(r.store.GetUpdateOutcome(ctx, id))
return newCompleted(
id,
fut,
withInstrumentation(&r.instrumentation),
), true
}
}
return nil, false
Expand Down
Loading