|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "os" |
| 8 | + "os/signal" |
| 9 | + |
| 10 | + "github.com/cschleiden/go-workflows/backend" |
| 11 | + "github.com/cschleiden/go-workflows/client" |
| 12 | + "github.com/cschleiden/go-workflows/samples" |
| 13 | + "github.com/cschleiden/go-workflows/worker" |
| 14 | + "github.com/cschleiden/go-workflows/workflow" |
| 15 | + "github.com/google/uuid" |
| 16 | +) |
| 17 | + |
| 18 | +func main() { |
| 19 | + ctx := context.Background() |
| 20 | + |
| 21 | + b := samples.GetBackend("subworkflow-signal") |
| 22 | + |
| 23 | + // Run worker |
| 24 | + go RunWorker(ctx, b) |
| 25 | + |
| 26 | + // Start workflow via client |
| 27 | + c := client.New(b) |
| 28 | + |
| 29 | + startWorkflow(ctx, c) |
| 30 | + |
| 31 | + c2 := make(chan os.Signal, 1) |
| 32 | + signal.Notify(c2, os.Interrupt) |
| 33 | + <-c2 |
| 34 | +} |
| 35 | + |
| 36 | +func startWorkflow(ctx context.Context, c client.Client) { |
| 37 | + subID := uuid.NewString() |
| 38 | + |
| 39 | + wf, err := c.CreateWorkflowInstance(ctx, client.WorkflowInstanceOptions{ |
| 40 | + InstanceID: uuid.NewString(), |
| 41 | + }, Workflow1, "Hello world", subID) |
| 42 | + if err != nil { |
| 43 | + panic("could not start workflow") |
| 44 | + } |
| 45 | + |
| 46 | + log.Println("Started workflow", wf.InstanceID) |
| 47 | +} |
| 48 | + |
| 49 | +func RunWorker(ctx context.Context, mb backend.Backend) { |
| 50 | + w := worker.New(mb, nil) |
| 51 | + |
| 52 | + w.RegisterWorkflow(Workflow1) |
| 53 | + w.RegisterWorkflow(SubWorkflow1) |
| 54 | + |
| 55 | + if err := w.Start(ctx); err != nil { |
| 56 | + panic("could not start worker") |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +func Workflow1(ctx workflow.Context, msg string, subID string) (string, error) { |
| 61 | + logger := workflow.Logger(ctx) |
| 62 | + logger.Debug("Entering Workflow1") |
| 63 | + |
| 64 | + logger.Debug("Scheduling sub-workflow") |
| 65 | + fsw := workflow.CreateSubWorkflowInstance[string](ctx, workflow.SubWorkflowOptions{ |
| 66 | + InstanceID: subID, |
| 67 | + }, SubWorkflow1) |
| 68 | + |
| 69 | + if err := workflow.SignalWorkflow(ctx, subID, "sub-signal", 42); err != nil { |
| 70 | + return "", fmt.Errorf("could not signal sub-workflow: %w", err) |
| 71 | + } |
| 72 | + |
| 73 | + r, err := fsw.Get(ctx) |
| 74 | + if err != nil { |
| 75 | + return "", fmt.Errorf("could not get sub-workflow result: %w", err) |
| 76 | + } |
| 77 | + |
| 78 | + return r, nil |
| 79 | +} |
| 80 | + |
| 81 | +func SubWorkflow1(ctx workflow.Context) (string, error) { |
| 82 | + logger := workflow.Logger(ctx) |
| 83 | + logger.Debug("Waiting for signal in sub-workflow") |
| 84 | + |
| 85 | + c := workflow.NewSignalChannel[int](ctx, "sub-signal") |
| 86 | + c.Receive(ctx) |
| 87 | + |
| 88 | + logger.Debug("Received sub-workflow signal") |
| 89 | + |
| 90 | + return "World", nil |
| 91 | +} |
0 commit comments