Skip to content
Open
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
47 changes: 47 additions & 0 deletions new_samples/consistentquery/consistentquery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"time"

"go.uber.org/cadence/workflow"
"go.uber.org/zap"
)

// ConsistentQueryWorkflow demonstrates query handlers with signal handling.
func ConsistentQueryWorkflow(ctx workflow.Context) error {
queryResult := 0
logger := workflow.GetLogger(ctx)
logger.Info("ConsistentQueryWorkflow started")

// Setup query handler for "state" query type
err := workflow.SetQueryHandler(ctx, "state", func(input []byte) (int, error) {
return queryResult, nil
})
if err != nil {
logger.Info("SetQueryHandler failed: " + err.Error())
return err
}

signalChan := workflow.GetSignalChannel(ctx, "increase")

s := workflow.NewSelector(ctx)
s.AddReceive(signalChan, func(c workflow.Channel, more bool) {
c.Receive(ctx, nil)
queryResult += 1
workflow.GetLogger(ctx).Info("Received signal!", zap.String("signal", "increase"))
})

workflow.Go(ctx, func(ctx workflow.Context) {
for {
s.Select(ctx)
}
})

// Wait for timer before completing
workflow.NewTimer(ctx, time.Minute*2).Get(ctx, nil)
logger.Info("Timer fired")

logger.Info("ConsistentQueryWorkflow completed")
return nil
}

23 changes: 23 additions & 0 deletions new_samples/consistentquery/generator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!-- THIS IS A GENERATED FILE -->
<!-- PLEASE DO NOT EDIT -->

# Sample Generator

This folder is NOT part of the actual sample. It exists only for contributors who work on this sample. Please disregard it if you are trying to learn about Cadence.

To create a better learning experience for Cadence users, each sample folder is designed to be self contained. Users can view every part of writing and running workflows, including:

* Cadence client initialization
* Worker with workflow and activity registrations
* Workflow starter
* and the workflow code itself

Some samples may have more or fewer parts depending on what they need to demonstrate.

In most cases, the workflow code (e.g. `workflow.go`) is the part that users care about. The rest is boilerplate needed to run that workflow. For each sample folder, the workflow code should be written by hand. The boilerplate can be generated. Keeping all parts inside one folder gives early learners more value because they can see everything together rather than jumping across directories.

## Contributing

* When creating a new sample, follow the steps mentioned in the README file in the main samples folder.
* To update the sample workflow code, edit the workflow file directly.
* To update the worker, client, or other boilerplate logic, edit the generator file. If your change applies to all samples, update the common generator file inside the `template` folder. Edit the generator file in this folder only when the change should affect this sample alone.
53 changes: 53 additions & 0 deletions new_samples/consistentquery/generator/README_specific.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
## Consistent Query Sample

This sample demonstrates **consistent queries** with signal handling.

### Start the Workflow

```bash
cadence --env development \
--domain cadence-samples \
workflow start \
--tl cadence-samples-worker \
--et 180 \
--workflow_type cadence_samples.ConsistentQueryWorkflow
```

### Query the Workflow

```bash
cadence --env development \
--domain cadence-samples \
workflow query \
--wid <workflow_id> \
--qt state
```

### Send Signals to Update State

```bash
cadence --env development \
--domain cadence-samples \
workflow signal \
--wid <workflow_id> \
--name increase
```

Each signal increments the counter. Query to see the updated value.

### Key Concept: Query + Signal

```go
queryResult := 0

// Register query handler
workflow.SetQueryHandler(ctx, "state", func() (int, error) {
return queryResult, nil
})

// Handle signals that modify state
signalChan := workflow.GetSignalChannel(ctx, "increase")
signalChan.Receive(ctx, nil)
queryResult += 1 // State changes are visible to queries
```

13 changes: 13 additions & 0 deletions new_samples/consistentquery/generator/generate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package main

import "github.com/uber-common/cadence-samples/new_samples/template"

func main() {
data := template.TemplateData{
SampleName: "Consistent Query",
Workflows: []string{"ConsistentQueryWorkflow"},
Activities: []string{},
}
template.GenerateAll(data)
}

20 changes: 20 additions & 0 deletions new_samples/consistentquery/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// THIS IS A GENERATED FILE
// PLEASE DO NOT EDIT

package main

import (
"fmt"
"os"
"os/signal"
"syscall"
)

func main() {
StartWorker()

done := make(chan os.Signal, 1)
signal.Notify(done, syscall.SIGINT)
fmt.Println("Cadence worker started, press ctrl+c to terminate...")
<-done
}
100 changes: 100 additions & 0 deletions new_samples/consistentquery/worker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// THIS IS A GENERATED FILE
// PLEASE DO NOT EDIT

// Package worker implements a Cadence worker with basic configurations.
package main

import (
"github.com/uber-go/tally"
apiv1 "github.com/uber/cadence-idl/go/proto/api/v1"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"

"go.uber.org/cadence/compatibility"
"go.uber.org/cadence/worker"
"go.uber.org/cadence/workflow"
"go.uber.org/yarpc"
"go.uber.org/yarpc/peer"
yarpchostport "go.uber.org/yarpc/peer/hostport"
"go.uber.org/yarpc/transport/grpc"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

const (
HostPort = "127.0.0.1:7833"
Domain = "cadence-samples"
// TaskListName identifies set of client workflows, activities, and workers.
// It could be your group or client or application name.
TaskListName = "cadence-samples-worker"
ClientName = "cadence-samples-worker"
CadenceService = "cadence-frontend"
)

// StartWorker creates and starts a basic Cadence worker.
func StartWorker() {
logger, cadenceClient := BuildLogger(), BuildCadenceClient()
workerOptions := worker.Options{
Logger: logger,
MetricsScope: tally.NewTestScope(TaskListName, nil),
}

w := worker.New(
cadenceClient,
Domain,
TaskListName,
workerOptions)
// HelloWorld workflow registration
w.RegisterWorkflowWithOptions(ConsistentQueryWorkflow, workflow.RegisterOptions{Name: "cadence_samples.ConsistentQueryWorkflow"})

err := w.Start()
if err != nil {
panic("Failed to start worker: " + err.Error())
}
logger.Info("Started Worker.", zap.String("worker", TaskListName))

}

func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowserviceclient.Interface {
grpcTransport := grpc.NewTransport()
// Create a single peer chooser that identifies the host/port and configures
// a gRPC dialer with TLS credentials
myChooser := peer.NewSingle(
yarpchostport.Identify(HostPort),
grpcTransport.NewDialer(dialOptions...),
)
outbound := grpcTransport.NewOutbound(myChooser)

dispatcher := yarpc.NewDispatcher(yarpc.Config{
Name: ClientName,
Outbounds: yarpc.Outbounds{
CadenceService: {Unary: outbound},
},
})
if err := dispatcher.Start(); err != nil {
panic("Failed to start dispatcher: " + err.Error())
}

clientConfig := dispatcher.ClientConfig(CadenceService)

// Create a compatibility adapter that wraps proto-based YARPC clients
// to provide a unified interface for domain, workflow, worker, and visibility APIs
return compatibility.NewThrift2ProtoAdapter(
apiv1.NewDomainAPIYARPCClient(clientConfig),
apiv1.NewWorkflowAPIYARPCClient(clientConfig),
apiv1.NewWorkerAPIYARPCClient(clientConfig),
apiv1.NewVisibilityAPIYARPCClient(clientConfig),
)
}

func BuildLogger() *zap.Logger {
config := zap.NewDevelopmentConfig()
config.Level.SetLevel(zapcore.InfoLevel)

var err error
logger, err := config.Build()
if err != nil {
panic("Failed to setup logger: " + err.Error())
}

return logger
}
73 changes: 73 additions & 0 deletions new_samples/crossdomain/crossdomain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"context"
"time"

"github.com/google/uuid"
"go.uber.org/cadence/activity"
"go.uber.org/cadence/workflow"
"go.uber.org/zap"
)

// Configuration for cross-domain execution
const (
ChildDomain = "child-domain" // Must be registered separately
ChildTaskList = "child-task-list"
)

// CrossDomainData is passed between workflows
type CrossDomainData struct {
Value string
}

// CrossDomainWorkflow demonstrates executing child workflows in different domains.
func CrossDomainWorkflow(ctx workflow.Context) error {
logger := workflow.GetLogger(ctx)
logger.Info("CrossDomainWorkflow started")

// Execute child workflow in a different domain
childCtx := workflow.WithChildOptions(ctx, workflow.ChildWorkflowOptions{
Domain: ChildDomain,
WorkflowID: "child-wf-" + uuid.New().String(),
TaskList: ChildTaskList,
ExecutionStartToCloseTimeout: time.Minute,
})

err := workflow.ExecuteChildWorkflow(childCtx, ChildDomainWorkflow, CrossDomainData{Value: "test"}).Get(ctx, nil)
if err != nil {
logger.Error("Child workflow failed", zap.Error(err))
return err
}

logger.Info("CrossDomainWorkflow completed")
return nil
}

// ChildDomainWorkflow runs in the child domain.
func ChildDomainWorkflow(ctx workflow.Context, data CrossDomainData) error {
logger := workflow.GetLogger(ctx)
logger.Info("ChildDomainWorkflow started", zap.String("value", data.Value))

ao := workflow.ActivityOptions{
ScheduleToStartTimeout: time.Minute,
StartToCloseTimeout: time.Minute,
}
ctx = workflow.WithActivityOptions(ctx, ao)

err := workflow.ExecuteActivity(ctx, ChildDomainActivity).Get(ctx, nil)
if err != nil {
return err
}

logger.Info("ChildDomainWorkflow completed")
return nil
}

// ChildDomainActivity runs in the child domain.
func ChildDomainActivity(ctx context.Context) (string, error) {
logger := activity.GetLogger(ctx)
logger.Info("ChildDomainActivity running")
return "Hello from child domain!", nil
}

23 changes: 23 additions & 0 deletions new_samples/crossdomain/generator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!-- THIS IS A GENERATED FILE -->
<!-- PLEASE DO NOT EDIT -->

# Sample Generator

This folder is NOT part of the actual sample. It exists only for contributors who work on this sample. Please disregard it if you are trying to learn about Cadence.

To create a better learning experience for Cadence users, each sample folder is designed to be self contained. Users can view every part of writing and running workflows, including:

* Cadence client initialization
* Worker with workflow and activity registrations
* Workflow starter
* and the workflow code itself

Some samples may have more or fewer parts depending on what they need to demonstrate.

In most cases, the workflow code (e.g. `workflow.go`) is the part that users care about. The rest is boilerplate needed to run that workflow. For each sample folder, the workflow code should be written by hand. The boilerplate can be generated. Keeping all parts inside one folder gives early learners more value because they can see everything together rather than jumping across directories.

## Contributing

* When creating a new sample, follow the steps mentioned in the README file in the main samples folder.
* To update the sample workflow code, edit the workflow file directly.
* To update the worker, client, or other boilerplate logic, edit the generator file. If your change applies to all samples, update the common generator file inside the `template` folder. Edit the generator file in this folder only when the change should affect this sample alone.
Loading
Loading