Full Code of uber-common/cadence-samples for AI

master d3f3ec968d30 cached
233 files
617.6 KB
174.8k tokens
812 symbols
1 requests
Download .txt
Showing preview only (679K chars total). Download the full file or copy to clipboard to get everything.
Repository: uber-common/cadence-samples
Branch: master
Commit: d3f3ec968d30
Files: 233
Total size: 617.6 KB

Directory structure:
gitextract__zd9l1h0/

├── .gitar/
│   └── rules/
│       └── pr-description-quality.md
├── .github/
│   ├── dco.yml
│   ├── pull_request_guidance.md
│   ├── pull_request_template.md
│   └── workflows/
│       ├── build.yml
│       └── semantic-pr.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── NOTICE
├── README.md
├── cmd/
│   └── samples/
│       ├── advanced/
│       │   └── autoscaling-monitoring/
│       │       ├── Makefile
│       │       ├── README.md
│       │       ├── activities.go
│       │       ├── config/
│       │       │   └── autoscaling.yaml
│       │       ├── config.go
│       │       ├── config_test.go
│       │       ├── main.go
│       │       ├── worker_config.go
│       │       └── workflow.go
│       ├── common/
│       │   ├── factory.go
│       │   ├── sample_helper.go
│       │   └── util.go
│       ├── cron/
│       │   ├── cron_workflow.go
│       │   ├── cron_workflow_test.go
│       │   └── main.go
│       ├── dsl/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── workflow.go
│       │   ├── workflow1.yaml
│       │   ├── workflow2.yaml
│       │   └── workflow_test.go
│       ├── expense/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── server/
│       │   │   └── dummy.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── fileprocessing/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── pso/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── dataconverter.go
│       │   ├── functions.go
│       │   ├── main.go
│       │   ├── particle.go
│       │   ├── position.go
│       │   ├── settings.go
│       │   ├── swarm.go
│       │   ├── utils.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── recipes/
│       │   ├── branch/
│       │   │   ├── branch_workflow.go
│       │   │   ├── main.go
│       │   │   ├── parallel_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── cancelactivity/
│       │   │   ├── main.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── childworkflow/
│       │   │   ├── child_workflow.go
│       │   │   ├── main.go
│       │   │   └── parent_workflow.go
│       │   ├── choice/
│       │   │   ├── exclusive_choice_workflow.go
│       │   │   ├── main.go
│       │   │   ├── multi_choice_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── consistentquery/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   └── query_workflow.go
│       │   ├── crossdomain/
│       │   │   ├── main.go
│       │   │   └── wf.go
│       │   ├── ctxpropagation/
│       │   │   ├── README.md
│       │   │   ├── activities.go
│       │   │   ├── main.go
│       │   │   ├── propagator.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── delaystart/
│       │   │   ├── delaystart_workflow.go
│       │   │   ├── delaystart_workflow_test.go
│       │   │   └── main.go
│       │   ├── dynamic/
│       │   │   ├── dynamic_workflow.go
│       │   │   ├── main.go
│       │   │   └── workflow_test.go
│       │   ├── greetings/
│       │   │   ├── greetings.json
│       │   │   ├── greetings_workflow.go
│       │   │   ├── main.go
│       │   │   ├── replay_test.go
│       │   │   ├── shadow_test.go
│       │   │   └── workflow_test.go
│       │   ├── helloworld/
│       │   │   ├── activity_logger_test.go
│       │   │   ├── helloworld.json
│       │   │   ├── helloworld_workflow.go
│       │   │   ├── helloworld_workflow_test.go
│       │   │   ├── main.go
│       │   │   ├── replay_test.go
│       │   │   └── shadow_test.go
│       │   ├── localactivity/
│       │   │   ├── README.md
│       │   │   ├── local_activity_workflow.go
│       │   │   ├── local_activity_workflow_test.go
│       │   │   └── main.go
│       │   ├── mutex/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── mutex_workflow.go
│       │   │   └── mutex_workflow_test.go
│       │   ├── pickfirst/
│       │   │   ├── main.go
│       │   │   ├── pickfirst_workflow.go
│       │   │   └── pickfirst_workflow_test.go
│       │   ├── query/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── query_workflow.go
│       │   │   └── query_workflow_test.go
│       │   ├── retryactivity/
│       │   │   ├── main.go
│       │   │   ├── retry_activity_workflow.go
│       │   │   └── retry_activity_workflow_test.go
│       │   ├── searchattributes/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── searchattributes_workflow.go
│       │   │   └── searchattributes_workflow_test.go
│       │   ├── sideeffect/
│       │   │   └── sideeffect_workflow.go
│       │   ├── signalcounter/
│       │   │   ├── main.go
│       │   │   ├── signal_counter_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── sleep/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── sleep_workflow.go
│       │   │   └── sleep_workflow_test.go
│       │   ├── splitmerge/
│       │   │   ├── main.go
│       │   │   ├── splitmerge_workflow.go
│       │   │   └── splitmerge_workflow_test.go
│       │   ├── timer/
│       │   │   ├── main.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── tracing/
│       │   │   ├── helloworld_workflow.go
│       │   │   └── main.go
│       │   └── versioning/
│       │       ├── README.md
│       │       ├── main.go
│       │       └── versioned_workflow.go
│       └── recovery/
│           ├── README.md
│           ├── cache/
│           │   ├── cache.go
│           │   └── lru.go
│           ├── main.go
│           ├── recovery_workflow.go
│           └── trip_workflow.go
├── config/
│   └── development.yaml
├── go.mod
├── go.sum
├── k8s/
│   ├── README.md
│   ├── cadence-samples-pod.yaml
│   └── docker/
│       └── Dockerfile
├── new_samples/
│   ├── README.md
│   ├── activities/
│   │   ├── README.md
│   │   ├── dynamic_workflow.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── parallel_pick_first_workflow.go
│   │   └── worker.go
│   ├── client_tls/
│   │   ├── README.md
│   │   ├── cadence_client.go
│   │   ├── main.go
│   │   └── tls_config.go
│   ├── concurrency/
│   │   ├── README.md
│   │   ├── batch_workflow.go
│   │   ├── batch_workflow_test.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   └── worker.go
│   ├── data/
│   │   ├── README.md
│   │   ├── compressed_dataconverter_workflow.go
│   │   ├── compressed_dataconverter_workflow_test.go
│   │   ├── encrypted_dataconverter_workflow.go
│   │   ├── encrypted_dataconverter_workflow_test.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── s3_dataconverter_workflow.go
│   │   ├── s3_dataconverter_workflow_test.go
│   │   └── worker.go
│   ├── hello_world/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── worker.go
│   │   └── workflow.go
│   ├── operations/
│   │   ├── README.md
│   │   ├── cancel_workflow.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   └── worker.go
│   ├── query/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── lunch_vote_workflow.go
│   │   ├── main.go
│   │   ├── markdown_query.go
│   │   ├── order_fulfillment_workflow.go
│   │   └── worker.go
│   ├── signal/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── simple_signal_workflow.go
│   │   └── worker.go
│   └── template/
│       ├── README.tmpl
│       ├── README_generator.tmpl
│       ├── README_references.tmpl
│       ├── generator.go
│       ├── main.tmpl
│       └── worker.tmpl
└── python_sdk_samples/
    ├── .python-version
    ├── README.md
    ├── __init__.py
    ├── openai_samples/
    │   ├── __init__.py
    │   └── agent_handoffs/
    │       ├── README.md
    │       ├── __init__.py
    │       ├── book_trip_agent.py
    │       ├── main.py
    │       └── tools.py
    └── pyproject.toml

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitar/rules/pr-description-quality.md
================================================
---
title: PR Description Quality Standards
description: Ensures PR descriptions meet quality criteria for the cadence-samples (Go) repo using guidance from the PR template and .github/pull_request_guidance.md
when: PR description is created or updated
actions: Read PR template and guidance, then report requirement status
---

# PR Description Quality Standards

When evaluating a pull request description:

1. **Read the PR template guidance** at `.github/pull_request_guidance.md` to understand the expected guidance for each section
2. Apply that guidance to evaluate the current PR description
3. Provide recommendations for how to improve the description.

## Core Principle: Why Not How

From https://cbea.ms/git-commit/#why-not-how:
- **"A diff shows WHAT changed, but only the description can explain WHY"**
- Focus on: the problem being solved, the reasoning behind the solution, context
- The code itself documents HOW - the PR description documents WHY

## Evaluation Criteria

### Required Sections (must exist with substantive content per PR template guidance)

1. **Which sample(s) or area?** 
   - One line listing area(s) touched. This repo has two sample trees: **cmd/samples** (legacy; make + ./bin/…) and **new_samples** (per-folder; go run .). Identify which tree and area(s) are touched.
   - **cmd/samples:** e.g. cmd/samples/recipes/helloworld, cmd/samples/recipes/branch, cmd/samples/recipes/query, cmd/samples/batch, cmd/samples/cron, cmd/samples/expense, cmd/samples/fileprocessing, cmd/samples/dsl, cmd/samples/pso, cmd/samples/recovery, cmd/samples/recipes/cancelactivity, etc.
   - **new_samples:** hello_world, activities, query, signal, operations, client_tls, template.
   - **Other:** README, build, config, Makefile, common.
   - Helps reviewers route; skip flagging if area is obvious from paths

2. **What changed?**
   - 1-2 line summary of WHAT changed technically
   - Focus on key modification, not implementation details
   - Link to GitHub issue encouraged for non-trivial changes; optional for trivial doc/sample tweaks
   - Template has good/bad examples

3. **Why?**
   - Context and motivation (why not how)
   - Enough rationale for reviewers to understand the goal (e.g. improving clarity, fixing compatibility, aligning with docs)
   - Must explain WHY this approach was chosen

4. **How did you test it?**
   - Concrete, copyable commands with exact invocations
   - GOOD: `make`, `go test ./...`, `go test ./cmd/samples/recipes/helloworld/`, `cd new_samples/hello_world && go run .`, and Cadence CLI commands as in sample READMEs
   - BAD: "Tested locally" or "See tests"
   - Expect Go/make and/or sample execution commands; no canary or integration server setup required

5. **Potential risks**
   - Often N/A for sample-only or doc-only changes
   - Call out when relevant: dependency upgrades, behavior changes for someone copying the sample, build/config changes
   - Don't require lengthy text when N/A is appropriate

6. **Release notes**
   - Optional for this repo. Use when change is user-facing (e.g. new sample, notable README change)
   - Can be N/A for internal refactors or tiny fixes
   - Don't require lengthy text when N/A is appropriate

7. **Documentation Changes**
   - Often relevant when adding or changing samples (main README, cmd/samples READMEs, new_samples READMEs including generator-generated, links to cadence or cadence-docs)
   - Only mark N/A if certain no docs are affected

### Quality Checks

- **Skip obvious things** - Don't flag items clear from folder structure (e.g. area from paths)
- **Skip trivial refactors** - Minor formatting/style changes don't need deep rationale
- **Don't check automated items** - CI, linting are automated

## FORBIDDEN - Never Include

- "Issues Found", "Testing Evidence Quality", "Documentation Reasoning", "Summary" sections
- "Note:" paragraphs or explanatory text outside recommendations
- Grouping recommendations by type

## Section Names (Use EXACT Brackets)

- **[Which sample(s) or area?]**
- **[What changed?]**
- **[Why?]**
- **[How did you test it?]**
- **[Potential risks]**
- **[Release notes]**
- **[Documentation Changes]**


================================================
FILE: .github/dco.yml
================================================
require:
  members: false


================================================
FILE: .github/pull_request_guidance.md
================================================
<!-- List the area(s) touched so reviewers know where to look.
This repo has two sample trees: legacy samples under cmd/samples (built with make, run via ./bin/<name>) and newer samples under new_samples (per-folder, run with go run .). Naming the area helps reviewers.
Examples: cmd/samples/recipes/helloworld, cmd/samples/batch, cmd/samples/expense, new_samples/hello_world, new_samples/query, new_samples/operations, README, build, config, Makefile -->
**Which sample(s) or area?**


<!-- 1-2 line summary of WHAT changed technically.
- Link to a GitHub issue when applicable (encouraged for larger changes; optional for trivial doc/sample tweaks)
- Good: "Added CancelWorkflow sample in new_samples/operations" or "Updated README run instructions for Go 1.21"
- Bad: "updated code" or "fixed stuff" -->
**What changed?**


<!-- Provide context and motivation (see https://cbea.ms/git-commit/#why-not-how). Focus on WHY, not how.
- Lighter than core Cadence repo: e.g. "improving clarity for new users," "fixing sample broken on Go 1.21," "aligning with cadence-docs"
- Still give enough rationale for reviewers to understand the goal
- Good: "HelloWorld didn't show retry behavior; this sample demonstrates RetryOptions so users can copy-paste a working example."
- Bad: "Improves samples" -->
**Why?**


<!-- Include concrete, copy-paste commands so another maintainer can reproduce your test steps.
- Prefer: make, go test ./... (or a targeted test, e.g. go test ./cmd/samples/recipes/helloworld/)
- For cmd/samples: make then e.g. ./bin/helloworld -m worker and ./bin/helloworld -m trigger
- For new_samples: cd new_samples/<sample> && go run . and Cadence CLI commands as in the sample README
- Good: Full commands reviewers can copy-paste to verify
- Bad: "Tested locally" or "See tests" -->
**How did you test it?**


<!-- Often N/A for sample-only or doc-only changes. Call out when relevant:
- Dependency upgrades (e.g. cadence-client version)
- Behavior changes that could affect someone copying the sample
- Build or config changes
- If truly N/A, you can mark it as such -->
**Potential risks**


<!-- Optional for this repo. Use when the change is user-facing (e.g. new sample, notable README change).
- Can be N/A for internal refactors, tiny fixes, or incremental work -->
**Release notes**


<!-- Did you update the main README, a cmd/samples README, or a new_samples README (including generator-generated READMEs)?
- Any links to cadence or cadence-docs that need updating?
- Only mark N/A if you're certain no docs are affected -->
**Documentation Changes**



================================================
FILE: .github/pull_request_template.md
================================================
<!-- For guidance on each section, see the PR guidance doc:
     https://github.com/cadence-workflow/cadence-samples/blob/master/.github/pull_request_guidance.md -->
**Which sample(s) or area?**


**What changed?**


**Why?**


**How did you test it?**


**Potential risks**


**Release notes**


**Documentation Changes**



================================================
FILE: .github/workflows/build.yml
================================================
name: Build and test cadence-samples
on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - name: Setup Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.22.x'
      - name: Build and Test
        run: make



================================================
FILE: .github/workflows/semantic-pr.yml
================================================
name: Semantic Pull Request

on:
  pull_request:
    types:
      - opened
      - edited
      - synchronize

jobs:
  semantic-pr:
    name: Validate PR title follows conventional commit format
    runs-on: ubuntu-latest
    # TODO: Remove this once we commit to conventional commits
    continue-on-error: true

    steps:
      - name: Validate PR title
        id: lint_pr_title
        uses: amannn/action-semantic-pull-request@v5.4.0
        with:
          # Allow standard conventional commit types
          types: |
            fix
            feat
            docs
            style
            refactor
            perf
            test
            chore
            ci
            build
          # TODO: Remove this once we've decided on scopes
          requireScope: false
          # Skip validation for certain labels if needed
          ignoreLabels: |
            skip-commit-format
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Comment on PR if validation fails
        if: steps.lint_pr_title.outputs.error_message != null
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `⚠️ **Semantic PR Check Failed**

              **Error Details:**
              \`\`\`
              ${{ steps.lint_pr_title.outputs.error_message }}
              \`\`\`

              **Required Format:**
              \`\`\`
              <type>: <description>
              \`\`\`

              **Allowed types:** fix, feat, docs, style, refactor, perf, test, chore, ci, build

              **Examples:**
              - \`feat: add user authentication system\`
              - \`fix: resolve memory leak in worker pool\`
              - \`docs: update API documentation\`
              - \`test: add integration tests for auth flow\`

              This is currently a **warning only** and won't block your PR from being merged.`
            })


================================================
FILE: .gitignore
================================================
*.out
*.test
*.xml
*.swp
.idea/
.vscode/
*.iml
*.cov
*.html
.tmp/
.DS_Store
test
test.log
vendor/
# Executables produced by cadence-samples repo
bin/
# Binary from go build in new_samples/query
new_samples/query/query
docker-compose.yml

# Credentials
new_samples/client_samples/helloworld_tls/credentials/

# Python SDK Samples
__pycache__/


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Cadence Samples

This doc is intended for contributors to Cadence samples. Thanks for considering to contribute ❤️

> 📚 **New to contributing to Cadence?** Check out our [Contributing Guide](https://cadenceworkflow.io/community/how-to-contribute/getting-started) for an overview of the contribution process across all Cadence repositories. This document contains cadence-samples specific setup and development instructions.

Once you go through the rest of this doc and get familiar with local development setup, take a look at the list of issues labeled with
[good first issue](https://github.com/uber-common/cadence-samples/labels/good%20first%20issue).

Join our community on the CNCF Slack workspace at [cloud-native.slack.com](https://communityinviter.com/apps/cloud-native/cncf) in the **#cadence-users** channel to reach out and discuss issues with the team.

### Documentation

- Every sample must have a README.md
- Include:
  - What the sample demonstrates
  - Real-world use cases
  - How to run the sample
  - Expected output
  - Key concepts

### Getting Help

If you need help or have questions:

- Join [CNCF Slack #cadence-users](https://communityinviter.com/apps/cloud-native/cncf)
- Ask on [StackOverflow](https://stackoverflow.com/questions/tagged/cadence-workflow) with tag `cadence-workflow`
- Open a [GitHub Discussion](https://github.com/uber-common/cadence-samples/discussions)
- File an [issue](https://github.com/uber-common/cadence-samples/issues) for bugs

## Code of Conduct

Please be respectful and constructive in all interactions. We're all here to learn and help each other build better software.

## License

By contributing, you agree that your contributions will be licensed under the Apache 2.0 License.

---

Thank you for contributing to Cadence samples! Your efforts help the entire community. 🚀



================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!)  The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

================================================
FILE: Makefile
================================================
.PHONY: test bins clean run-generators
PROJECT_ROOT = github.com/uber-common/cadence-samples

export PATH := $(GOPATH)/bin:$(PATH)

# default target
default: test

PROGS = helloworld \
	versioning \
	delaystart \
	branch \
	childworkflow \
	crossdomain \
	choice \
	dynamic \
	greetings \
	pickfirst \
	retryactivity \
	splitmerge \
	timer \
	localactivity \
	query \
	consistentquery \
	cron \
	tracing \
	dsl \
	fileprocessing \
	expense_dummy \
	expense \
	recovery \
	cancelactivity \
	ctxpropagation \
	pso \
	signalcounter \
	sideeffect \
	sleep \
	autoscaling-monitoring \

TEST_ARG ?= -race -v -timeout 5m
BUILD := ./build
SAMPLES_DIR=./cmd/samples

export PATH := $(GOPATH)/bin:$(PATH)

# Automatically gather all srcs
ALL_SRC := $(shell find ./cmd/samples/common -name "*.go")

# all directories with *_test.go files in them
TEST_DIRS=./cmd/samples/cron \
	./cmd/samples/dsl \
	./cmd/samples/expense \
	./cmd/samples/fileprocessing \
	./cmd/samples/recipes/branch \
	./cmd/samples/recipes/choice \
	./cmd/samples/recipes/greetings \
	./cmd/samples/recipes/helloworld \
	./cmd/samples/recipes/delaystart \
	./cmd/samples/recipes/cancelactivity \
	./cmd/samples/recipes/pickfirst \
	./cmd/samples/recipes/mutex \
	./cmd/samples/recipes/retryactivity \
	./cmd/samples/recipes/splitmerge \
	./cmd/samples/recipes/timer \
	./cmd/samples/recipes/localactivity \
	./cmd/samples/recipes/query \
	./cmd/samples/recipes/consistentquery \
	./cmd/samples/recipes/ctxpropagation \
	./cmd/samples/recipes/searchattributes \
	./cmd/samples/recipes/sideeffect \
	./cmd/samples/recipes/signalcounter \
	./cmd/samples/recipes/sleep \
	./cmd/samples/recovery \
	./cmd/samples/pso \

cancelactivity:
	go build -o bin/cancelactivity cmd/samples/recipes/cancelactivity/*.go

helloworld:
	go build -o bin/helloworld cmd/samples/recipes/helloworld/*.go

delaystart:
	go build -o bin/delaystart cmd/samples/recipes/delaystart/*.go

sleep:
	go build -o bin/sleep cmd/samples/recipes/sleep/*.go

branch:
	go build -o bin/branch cmd/samples/recipes/branch/*.go

childworkflow:
	go build -o bin/childworkflow cmd/samples/recipes/childworkflow/*.go

choice:
	go build -o bin/choice cmd/samples/recipes/choice/*.go

dynamic:
	go build -o bin/dynamic cmd/samples/recipes/dynamic/*.go

greetings:
	go build -o bin/greetings cmd/samples/recipes/greetings/*.go

pickfirst:
	go build -o bin/pickfirst cmd/samples/recipes/pickfirst/*.go

mutex:
	go build -o bin/mutex cmd/samples/recipes/mutex/*.go

retryactivity:
	go build -o bin/retryactivity cmd/samples/recipes/retryactivity/*.go

splitmerge:
	go build -o bin/splitmerge cmd/samples/recipes/splitmerge/*.go

searchattributes:
	go build -o bin/searchattributes cmd/samples/recipes/searchattributes/*.go

timer:
	go build -o bin/timer cmd/samples/recipes/timer/*.go

localactivity:
	go build -o bin/localactivity cmd/samples/recipes/localactivity/*.go

query:
	go build -o bin/query cmd/samples/recipes/query/*.go

consistentquery:
	go build -o bin/consistentquery cmd/samples/recipes/consistentquery/*.go

ctxpropagation:
	go build -o bin/ctxpropagation cmd/samples/recipes/ctxpropagation/*.go

tracing:
	go build -o bin/tracing cmd/samples/recipes/tracing/*.go

cron:
	go build -o bin/cron cmd/samples/cron/*.go

dsl:
	go build -o bin/dsl cmd/samples/dsl/*.go

fileprocessing:
	go build -o bin/fileprocessing cmd/samples/fileprocessing/*.go

expense_dummy:
	go build -o bin/expense_dummy cmd/samples/expense/server/*.go

expense:
	go build -o bin/expense cmd/samples/expense/*.go

recovery:
	go build -o bin/recovery cmd/samples/recovery/*.go

pso:
	go build -o bin/pso cmd/samples/pso/*.go


signalcounter:
	go build -o bin/signalcounter cmd/samples/recipes/signalcounter/*.go

crossdomain:
	go build -o bin/crossdomain cmd/samples/recipes/crossdomain/*.go

crossdomain-setup:
	# use the ..cadence-server --env development_xdc_cluster0 ... to set up three
	cadence --ad 127.0.0.1:7933 --env development --do domain0 domain register --ac cluster0 --gd true --clusters cluster0 cluster1 # global domain required
	cadence --ad 127.0.0.1:7933 --env development --do domain1 domain register --ac cluster1 --gd true --clusters cluster0 cluster1
	cadence --ad 127.0.0.1:7933 --env development --do domain2 domain register --ac cluster0 --gd true --clusters cluster0 cluster1

crossdomain-run: crossdomain
	tmux split-window -h './bin/crossdomain -m "worker0"' \; \
		split-window -v './bin/crossdomain -m "worker1"' \; \
		split-window -v './bin/crossdomain -m "worker2"'

sideeffect:
	go build -o bin/sideeffect cmd/samples/recipes/sideeffect/*.go

versioning:
	go build -o bin/versioning cmd/samples/recipes/versioning/*.go

autoscaling-monitoring:
	go build -o bin/autoscaling-monitoring cmd/samples/advanced/autoscaling-monitoring/*.go

run-generators:
	@echo "Running generators in new_samples..."
	@for dir in new_samples/*/generator; do \
		if [ -d "$$dir" ]; then \
			echo "Running generator in $$dir"; \
			(cd $$dir && go run .); \
		fi; \
	done
	@echo "All generators completed"

test: bins
	@rm -f test
	@rm -f test.log
	@echo $(TEST_DIRS)
	@for dir in $(TEST_DIRS); do \
		go test -coverprofile=$@ "$$dir" | tee -a test.log; \
	done;

clean:
	rm -rf bin
	rm -Rf $(BUILD)

bins: helloworld \
	versioning \
	delaystart \
	branch \
	crossdomain \
	childworkflow \
	choice \
	dynamic \
	greetings \
	pickfirst \
	mutex \
	cancelactivity \
	retryactivity \
	splitmerge \
	searchattributes \
	timer \
	cron \
	tracing \
	dsl \
	fileprocessing \
	expense_dummy \
	expense \
	localactivity \
	query \
	consistentquery \
	recovery \
	ctxpropagation \
	pso \
	signalcounter \
	sideeffect \
	sleep \
	autoscaling-monitoring \


================================================
FILE: NOTICE
================================================
Copyright (c) 2025 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.


================================================
FILE: README.md
================================================
# Cadence Samples ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/uber-common/cadence-samples/build.yml)

Welcome to the Cadence Samples repository! This collection demonstrates the powerful capabilities of Cadence workflow orchestration through practical, real-world examples. Whether you're new to Cadence or looking to implement specific patterns, these samples will help you understand how to build reliable, scalable, and maintainable workflow applications.

## What is Cadence?

Cadence is a distributed, scalable, durable, and highly available orchestration engine that helps developers build reliable applications. It provides:

- **Reliability**: Automatic retry mechanisms, error handling, and fault tolerance
- **Scalability**: Distributed execution across multiple workers
- **Durability**: Persistent workflow state that survives failures
- **Observability**: Built-in monitoring, tracing, and querying capabilities

Learn more about Cadence at:
- [Documentation](https://cadenceworkflow.io)
- [Cadence Server](https://github.com/cadence-workflow/cadence)
- [Cadence Go Client](https://github.com/cadence-workflow/cadence-go-client)
- [CNCF Slack](https://communityinviter.com/apps/cloud-native/cncf) - Join **#cadence-users** channel on CNCF Slack

## 🚀 Quick Start

### Prerequisites

1. **Clone the Repository**:
```bash
git clone https://github.com/uber-common/cadence-samples.git && cd cadence-samples
```

2. **Start Cadence Server**
```bash
curl -LO https://raw.githubusercontent.com/cadence-workflow/cadence/refs/heads/master/docker/docker-compose.yml && docker-compose up --wait
```

This downloads and starts all required dependencies including Cadence server, database, and [Cadence Web UI](https://github.com/uber/cadence-web). You can view your sample workflows at [http://localhost:8088](http://localhost:8088).

3. **Build All Samples**:
```bash
make
```

### Docker Troubleshooting

The `docker-compose` command requires Docker daemon to be running. On macOS/Windows, open Docker Desktop. On Linux, run `sudo systemctl start docker`.

<details>
<summary>Port conflicts</summary>

If you see `Bind for 0.0.0.0:<port> failed: port is already allocated`, find the process using that port:

```bash
lsof -i tcp:<port>
```

To find which container is using it:
```bash
docker ps --format '{{.ID}}\t{{.Ports}}\t{{.Names}}' | grep <port>
```

Stop and remove the conflicting container:
```bash
docker stop <container_id> && docker rm <container_id>
```

Cadence uses these ports: `7833`, `7933`, `7939`, `8000-8003`, `8088` (Web UI), `9042` (Cassandra), `9090` (Prometheus), `3000` (Grafana).

</details>

<details>
<summary>Reset everything</summary>

```bash
docker-compose down
docker ps -a  # check for leftover containers
docker rm <container_id>  # remove if needed
```

Verify with `docker ps` and visit [http://localhost:8088](http://localhost:8088).

</details>

## 📚 Sample Categories

### Table of Contents
- [🎯 Basic Examples](#-basic-examples)
  - [Hello World](#hello-world)
  - [Greetings](#greetings)
  - [Cron](#cron)
  - [Timer](#timer)
  - [Delay Start](#delay-start)
  - [Branch](#branch)
  - [Split-Merge](#split-merge)
  - [Pick First](#pick-first)

- [🔧 Advanced Examples](#-advanced-examples)
  - [Choice](#choice)
  - [Retry Activity](#retry-activity)
  - [Cancel Activity](#cancel-activity)
  - [Mutex](#mutex)
  - [Query](#query)
  - [Consistent Query](#consistent-query)
  - [Child Workflow](#child-workflow)
  - [Dynamic](#dynamic)
  - [Local Activity](#local-activity)
  - [Versioning](#versioning)
  - [Search Attributes](#search-attributes)
  - [Context Propagation](#context-propagation)
  - [Tracing](#tracing)
  - [Side Effect](#side-effect)
  - [Recovery](#recovery)

- [🏢 Business Application Examples](#-business-application-examples)
  - [Expense](#expense)
  - [File Processing](#file-processing)
  - [DSL](#dsl)
  - [PSO (Particle Swarm Optimization)](#pso-particle-swarm-optimization)

---

### 🎯 **Basic Examples**

#### Hello World
* **Shows**: Basic Cadence workflow concepts and activity execution.
* **What it does**: Executes a single activity that returns a greeting message.
* **Real-world use case**: Foundation for understanding workflow structure, activity execution, and basic error handling.
* **Key concepts**: Workflow definition, activity execution, error handling, worker setup.
* **Source code**: [cmd/samples/recipes/helloworld/](cmd/samples/recipes/helloworld/)

##### How to run
Start Worker:
```bash
./bin/helloworld -m worker
```

Start Workflow:
```bash
./bin/helloworld -m trigger
```

#### Greetings
* **Shows**: Sequential activity execution and result passing between activities.
* **What it does**: Executes three activities in sequence: get greeting, get name, then combine them.
* **Real-world use case**: Multi-step processes like user registration, order processing, or data transformation pipelines.
* **Key concepts**: Sequential execution, activity chaining, result passing between activities.
* **Source code**: [cmd/samples/recipes/greetings/](cmd/samples/recipes/greetings/)

##### How to run
Start Worker:
```bash
./bin/greetings -m worker
```

Start Workflow:
```bash
./bin/greetings -m trigger
```

#### Cron
* **Shows**: Automated recurring tasks and cron scheduling.
* **What it does**: Executes a workflow based on cron expressions (e.g., every minute, daily at 2 AM).
* **Real-world use case**: Data backups, report generation, system maintenance, periodic data synchronization.
* **Key concepts**: Cron scheduling, workflow persistence, time-based execution.
* **Source code**: [cmd/samples/cron/](cmd/samples/cron/)

##### How to run
Start Worker:
```bash
./bin/cron -m worker
```

Start Workflow:
```bash
./bin/cron -m trigger -cron "* * * * *"  # Run every minute
```

#### Timer
* **Shows**: Timeout and delay handling with parallel execution.
* **What it does**: Starts a long-running process and sends a notification if it takes too long.
* **Real-world use case**: Order processing with SLA monitoring, payment processing with timeout alerts, API calls with fallback mechanisms.
* **Key concepts**: Timer creation, timeout handling, parallel execution with cancellation.
* **Source code**: [cmd/samples/recipes/timer/](cmd/samples/recipes/timer/)

##### How to run
Start Worker:
```bash
./bin/timer -m worker
```

Start Workflow:
```bash
./bin/timer -m trigger
```

#### Delay Start
* **Shows**: Deferred execution and delayed workflow execution.
* **What it does**: Waits for a specified duration before executing the main workflow logic.
* **Real-world use case**: Scheduled maintenance windows, delayed notifications, batch processing at specific times.
* **Key concepts**: Delayed execution, time-based workflow scheduling.
* **Source code**: [cmd/samples/recipes/delaystart/](cmd/samples/recipes/delaystart/)

##### How to run
Start Worker:
```bash
./bin/delaystart -m worker
```

Start Workflow:
```bash
./bin/delaystart -m trigger
```

### 🔄 **Parallel Execution Examples**

#### Branch
* **Shows**: Parallel activity execution and concurrent activity management.
* **What it does**: Executes multiple activities in parallel and waits for all to complete.
* **Real-world use case**: Processing multiple orders simultaneously, calling multiple APIs in parallel, batch data processing.
* **Key concepts**: Parallel execution, Future handling, concurrent activity management.
* **Source code**: [cmd/samples/recipes/branch/](cmd/samples/recipes/branch/)

##### How to run
Start Worker:
```bash
./bin/branch -m worker
```

Start Single Branch Workflow:
```bash
./bin/branch -m trigger -c branch
```

Start Parallel Branch Workflow:
```bash
./bin/branch -m trigger -c parallel
```

#### Split-Merge
* **Shows**: Divide and conquer pattern with parallel processing.
* **What it does**: Splits a large task into chunks, processes them in parallel, then merges results.
* **Real-world use case**: Large file processing, batch data analysis, image/video processing, ETL pipelines.
* **Key concepts**: Work splitting, parallel processing, result aggregation, worker coordination.
* **Source code**: [cmd/samples/recipes/splitmerge/](cmd/samples/recipes/splitmerge/)

##### How to run
Start Worker:
```bash
./bin/splitmerge -m worker
```

Start Workflow:
```bash
./bin/splitmerge -m trigger
```

#### Pick First
* **Shows**: Race condition handling and activity cancellation.
* **What it does**: Runs multiple activities in parallel and uses the result from whichever completes first.
* **Real-world use case**: Multi-provider API calls, redundant service calls, failover mechanisms, load balancing.
* **Key concepts**: Parallel execution, cancellation, race condition handling.
* **Source code**: [cmd/samples/recipes/pickfirst/](cmd/samples/recipes/pickfirst/)

##### How to run
Start Worker:
```bash
./bin/pickfirst -m worker
```

Start Workflow:
```bash
./bin/pickfirst -m trigger
```

### 🔧 **Advanced Examples**

#### Choice
* **Shows**: Conditional execution and decision-based activity routing.
* **What it does**: Executes different activities based on the result of a decision activity.
* **Real-world use case**: Order routing based on type, user authentication flows, approval workflows, conditional processing.
* **Key concepts**: Conditional logic, decision trees, workflow branching.
* **Source code**: [cmd/samples/recipes/choice/](cmd/samples/recipes/choice/)

##### How to run
Start Worker:
```bash
./bin/choice -m worker
```

Start Single Choice Workflow:
```bash
./bin/choice -m trigger -c single
```

Start Multi-Choice Workflow:
```bash
./bin/choice -m trigger -c multi
```

#### Retry Activity
* **Shows**: Resilient processing with retry policies and heartbeat tracking.
* **What it does**: Demonstrates activity retry policies with heartbeat progress tracking.
* **Real-world use case**: API calls with intermittent failures, database operations, external service integration.
* **Key concepts**: Retry policies, heartbeat mechanisms, progress tracking, failure recovery.
* **Source code**: [cmd/samples/recipes/retryactivity/](cmd/samples/recipes/retryactivity/)

##### How to run
Start Worker:
```bash
./bin/retryactivity -m worker
```

Start Workflow:
```bash
./bin/retryactivity -m trigger
```

#### Cancel Activity
* **Shows**: Graceful cancellation and cleanup operations.
* **What it does**: Shows how to cancel running activities and perform cleanup operations.
* **Real-world use case**: User-initiated cancellations, timeout handling, resource cleanup, emergency stops.
* **Key concepts**: Cancellation handling, cleanup operations, graceful shutdown.
* **Source code**: [cmd/samples/recipes/cancelactivity/](cmd/samples/recipes/cancelactivity/)

##### How to run
Start Worker:
```bash
./bin/cancelactivity -m worker
```

Start Workflow:
```bash
./bin/cancelactivity -m trigger
```

**Cancel Workflow:**
```bash
./bin/cancelactivity -m cancel -w <WorkflowID>
```

#### Mutex
* **Shows**: Resource locking and distributed locking patterns.
* **What it does**: Ensures only one workflow can access a specific resource at a time.
* **Real-world use case**: Database migrations, configuration updates, resource allocation, critical section protection.
* **Key concepts**: Distributed locking, resource coordination, mutual exclusion.
* **Source code**: [cmd/samples/recipes/mutex/](cmd/samples/recipes/mutex/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/mutex/README.md)** to run the sample

#### Query
* **Shows**: Workflow state inspection and custom query handlers.
* **What it does**: Demonstrates custom query handlers to inspect workflow state.
* **Real-world use case**: Progress monitoring, status dashboards, debugging running workflows, user interfaces.
* **Key concepts**: Query handlers, state inspection, workflow monitoring.
* **Source code**: [cmd/samples/recipes/query/](cmd/samples/recipes/query/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/query/README.md)** to run the sample

#### Consistent Query
* **Shows**: Consistent state queries and signal handling.
* **What it does**: Shows how to query workflow state consistently while handling signals.
* **Real-world use case**: Real-time dashboards, progress tracking, state synchronization.
* **Key concepts**: Consistent queries, signal handling, state management.
* **Source code**: [cmd/samples/recipes/consistentquery/](cmd/samples/recipes/consistentquery/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/consistentquery/README.md)** to run the sample

#### Child Workflow
* **Shows**: Workflow composition and parent-child workflow relationships.
* **What it does**: Demonstrates parent-child workflow relationships with ContinueAsNew pattern.
* **Real-world use case**: Complex business processes, workflow decomposition, modular workflow design.
* **Key concepts**: Child workflows, ContinueAsNew, workflow composition.
* **Source code**: [cmd/samples/recipes/childworkflow/](cmd/samples/recipes/childworkflow/)

##### How to run
Start Worker:
```bash
./bin/childworkflow -m worker
```

Start Workflow:
```bash
./bin/childworkflow -m trigger
```

#### Dynamic
* **Shows**: Dynamic activity invocation and string-based execution.
* **What it does**: Demonstrates calling activities using string names for dynamic behavior.
* **Real-world use case**: Plugin systems, dynamic workflow composition, configuration-driven workflows.
* **Key concepts**: Dynamic activity invocation, string-based execution, flexible workflow design.
* **Source code**: [cmd/samples/recipes/dynamic/](cmd/samples/recipes/dynamic/)

##### How to run
Start Worker:
```bash
./bin/dynamic -m worker
```

Start Workflow:
```bash
./bin/dynamic -m trigger
```

#### Local Activity
* **Shows**: High-performance local execution and lightweight operations.
* **What it does**: Shows how to use local activities for quick operations that don't need external execution.
* **Real-world use case**: Data validation, simple calculations, condition checking, fast decision making.
* **Key concepts**: Local activities, performance optimization, lightweight operations.
* **Source code**: [cmd/samples/recipes/localactivity/](cmd/samples/recipes/localactivity/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/localactivity/README.md)** to run the sample

#### Versioning
* **Shows**: Safe workflow evolution and backward compatibility.
* **What it does**: Shows workflow versioning with backward compatibility and safe rollbacks.
* **Real-world use case**: Production deployments, feature rollouts, backward compatibility, safe migrations.
* **Key concepts**: Workflow versioning, backward compatibility, safe deployments.
* **Source code**: [cmd/samples/recipes/versioning/](cmd/samples/recipes/versioning/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/versioning/README.md)** to run the sample

#### Search Attributes
* **Shows**: Workflow indexing and search for workflow discovery.
* **What it does**: Shows how to add searchable attributes to workflows and query them.
* **Real-world use case**: Workflow discovery, filtering, reporting, operational dashboards.
* **Key concepts**: Search attributes, workflow indexing, ElasticSearch integration.
* **Source code**: [cmd/samples/recipes/searchattributes/](cmd/samples/recipes/searchattributes/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/searchattributes/README.md)** to run the sample

#### Context Propagation
* **Shows**: Cross-workflow context and context propagation.
* **What it does**: Demonstrates passing context (like user info, trace IDs) through workflow execution.
* **Real-world use case**: Distributed tracing, user context propagation, audit trails, debugging.
* **Key concepts**: Context propagation, distributed tracing, cross-service context.
* **Source code**: [cmd/samples/recipes/ctxpropagation/](cmd/samples/recipes/ctxpropagation/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recipes/ctxpropagation/README.md)** to run the sample

#### Tracing
* **Shows**: Distributed tracing and integration with tracing systems.
* **What it does**: Shows how to add distributed tracing to Cadence workflows.
* **Real-world use case**: Performance monitoring, debugging, observability, APM integration.
* **Key concepts**: Distributed tracing, Jaeger integration, observability.
* **Source code**: [cmd/samples/recipes/tracing/](cmd/samples/recipes/tracing/)

##### How to run
Start Worker:
```bash
./bin/tracing -m worker
```

Start Workflow:
```bash
./bin/tracing -m trigger
```

#### Side Effect
* **Shows**: Non-deterministic operations and replay safety.
* **What it does**: Demonstrates the SideEffect API for handling non-deterministic operations.
* **Real-world use case**: ID generation, random number generation, external state queries.
* **Key concepts**: Side effects, non-deterministic operations, replay safety.
* **Source code**: [cmd/samples/recipes/sideeffect/](cmd/samples/recipes/sideeffect/)

##### How to run
Start Workflow:
```bash
./bin/sideeffect
```

#### Recovery
* **Shows**: Workflow recovery and failure handling.
* **What it does**: Shows how to restart failed workflows and replay signals.
* **Real-world use case**: Disaster recovery, workflow repair, system restoration.
* **Key concepts**: Workflow recovery, signal replay, failure handling.
* **Source code**: [cmd/samples/recovery/](cmd/samples/recovery/)

##### How to run
* Check **[Detailed Guide](cmd/samples/recovery/README.md)** to run the sample

### 🏢 **Business Application Examples**

#### Expense
* **Shows**: Human-in-the-loop workflows and approval workflows.
* **What it does**: Creates an expense report, waits for approval, then processes payment.
* **Real-world use case**: Expense approval, purchase orders, document review, approval workflows.
* **Key concepts**: Human-in-the-loop, async completion, approval workflows.
* **Source code**: [cmd/samples/expense/](cmd/samples/expense/)

##### How to run
* Check **[Detailed Guide](cmd/samples/expense/README.md)** to run the sample

#### File Processing
* **Shows**: Distributed file processing across multiple hosts.
* **What it does**: Downloads, processes, and uploads files with host-specific execution.
* **Real-world use case**: Large file processing, ETL pipelines, media processing, data transformation.
* **Key concepts**: File processing, host-specific execution, session management, retry policies.
* **Source code**: [cmd/samples/fileprocessing/](cmd/samples/fileprocessing/)

##### How to run
* Check **[Detailed Guide](cmd/samples/fileprocessing/README.md)** to run the sample

#### DSL
* **Shows**: Domain-specific language and custom workflow language creation.
* **What it does**: Implements a simple DSL for defining workflows using YAML configuration.
* **Real-world use case**: Business user workflow definition, configuration-driven workflows, workflow templates.
* **Key concepts**: DSL implementation, YAML parsing, dynamic workflow creation.
* **Source code**: [cmd/samples/dsl/](cmd/samples/dsl/)

##### How to run
* Check **[Detailed Guide](cmd/samples/dsl/README.md)** to run the sample

#### PSO (Particle Swarm Optimization)
* **Shows**: Complex mathematical workflows and long-running optimization workflows.
* **What it does**: Implements particle swarm optimization with child workflows and ContinueAsNew.
* **Real-world use case**: Mathematical optimization, machine learning training, complex calculations.
* **Key concepts**: Long-running workflows, ContinueAsNew, child workflows, custom data converters.
* **Source code**: [cmd/samples/pso/](cmd/samples/pso/)

##### How to run
* Check **[Detailed Guide](cmd/samples/pso/README.md)** to run the sample

## 🛠 **Development & Testing**

### Building Samples
```bash
make
```

### Running Tests
```bash
# Run all tests
go test ./...

# Run specific sample tests
go test ./cmd/samples/recipes/helloworld/
```

### Worker Modes
Most samples support these modes:
- `worker`: Start a worker to handle workflow execution
- `trigger`: Start a new workflow execution
- `query`: Query a running workflow (where applicable)
- `signal`: Send a signal to a workflow (where applicable)


## 🤝 **Contributing**

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📄 **License**

Apache 2.0 License - see [LICENSE](LICENSE) for details.

## 🆘 **Getting Help**

- **Documentation**: [Cadence Documentation](https://cadenceworkflow.io/docs/)
- **Community**: [Cadence Community](https://cadenceworkflow.io/community/)
- **Issues**: [GitHub Issues](https://github.com/uber-common/cadence-samples/issues)

---

**Happy Workflowing! 🚀**

================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/Makefile
================================================
# Makefile for autoscaling monitoring sample

.PHONY: build clean test

# Build the autoscaling monitoring sample
build:
	go build -o ../../../../bin/autoscaling-monitoring *.go

# Clean build artifacts
clean:
	rm -f ../../../../bin/autoscaling-monitoring

# Run tests
test:
	go test -v .

# Install dependencies
deps:
	go mod tidy

# Run the sample in different modes
run-worker: build
	../../../../bin/autoscaling-monitoring -m worker

run-trigger: build
	../../../../bin/autoscaling-monitoring -m trigger


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/README.md
================================================
# Autoscaling Monitoring Sample

This sample demonstrates three advanced Cadence worker features:

1. **Worker Poller Autoscaling** - Dynamic adjustment of worker poller goroutines based on workload
2. **Integrated Prometheus Metrics** - Real-time metrics collection using Tally with Prometheus reporter
3. **Autoscaling Metrics** - Comprehensive autoscaling behavior metrics exposed via HTTP endpoint

## Features

### Worker Poller Autoscaling
The worker uses `worker.NewV2` with `AutoScalerOptions` to enable true autoscaling behavior:
- **AutoScalerOptions.Enabled**: true - Enables the autoscaling feature
- **PollerMinCount**: 2 - Minimum number of poller goroutines
- **PollerMaxCount**: 8 - Maximum number of poller goroutines  
- **PollerInitCount**: 4 - Initial number of poller goroutines

The worker automatically adjusts the number of poller goroutines between the min and max values based on the current workload.

### Prometheus Metrics
The sample uses Tally with Prometheus reporter to expose comprehensive metrics:
- **Real-time autoscaling metrics** - Poller count changes, quota adjustments, wait times
- **Worker performance metrics** - Task processing rates, poller utilization, queue depths
- **Standard Cadence metrics** - All metrics automatically emitted by the Cadence Go client
- **Sanitized metric names** - Prometheus-compatible metric names and labels

### Monitoring Dashboards
When running the Cadence server locally with Grafana, you can access the client dashboards at:

**Client Dashboards**: http://localhost:3000/d/dehkspwgabvuoc/cadence-client

> **Note**: Make sure to select a Domain in Grafana for the dashboards to display data. The dashboards will be empty until a domain is selected from the dropdown.


## Prerequisites

1. **Cadence Server**: Running locally with Docker Compose.
2. **Prometheus**: Configured to scrape metrics from the sample.
3. **Grafana**: With Cadence dashboards (included with default Cadence server setup). Dashboards in the latest version of the server.

## Quick Start

### 1. Start the Worker
```bash
./bin/autoscaling-monitoring -m worker
```

The worker automatically exposes metrics at: http://127.0.0.1:8004/metrics

### 2. Generate Load
```bash
./bin/autoscaling-monitoring -m trigger
```

## Configuration

The sample uses a custom configuration system that extends the base Cadence configuration. You can specify a configuration file using the `-config` flag:

```bash
./bin/autoscaling-monitoring -m worker -config /path/to/config.yaml
```

### Configuration File Structure

```yaml
# Cadence connection settings
domain: "default"
service: "cadence-frontend"
host: "localhost:7833"

# Prometheus configuration
prometheus:
  listenAddress: "127.0.0.1:8004"

# Autoscaling configuration
autoscaling:
  # Worker autoscaling settings
  pollerMinCount: 2
  pollerMaxCount: 8
  pollerInitCount: 4
  
  # Load generation settings
  loadGeneration:
    # Workflow-level settings
    workflows: 10             # Number of workflows to start
    workflowDelay: 1000       # Delay between starting workflows (milliseconds)
    
    # Activity-level settings (per workflow)
    activitiesPerWorkflow: 30 # Number of activities per workflow
    batchDelay: 2000          # Delay between activity batches within workflow (milliseconds)
    
    # Activity processing time range (milliseconds)
    minProcessingTime: 1000
    maxProcessingTime: 6000
```

### Configuration Usage

The configuration values are used throughout the sample:

1. **Worker Configuration** (`worker_config.go`):
   - `pollerMinCount`, `pollerMaxCount`, `pollerInitCount` → `AutoScalerOptions`

2. **Workflow Configuration** (`workflow.go`):
   - `activitiesPerWorkflow` → Number of activities to execute per workflow
   - `batchDelay` → Delay between activity batches within workflow

3. **Activity Configuration** (`activities.go`):
   - `minProcessingTime`, `maxProcessingTime` → Activity processing time range

4. **Prometheus Configuration** (integrated):
   - `listenAddress` → Metrics endpoint port (default: 127.0.0.1:8004)

### Default Configuration

If no configuration file is provided or if the file cannot be read, the sample uses these defaults:

```yaml
domain: "default"
service: "cadence-frontend"
host: "localhost:7833"
prometheus:
  listenAddress: "127.0.0.1:8004"
autoscaling:
  pollerMinCount: 2
  pollerMaxCount: 8
  pollerInitCount: 4
  loadGeneration:
    workflows: 10
    workflowDelay: 1000
    activitiesPerWorkflow: 30
    batchDelay: 2000
    minProcessingTime: 1000
    maxProcessingTime: 6000
```

### Load Pattern Examples

The sample supports various load patterns for testing autoscaling behavior:

#### **1. Gradual Ramp-up (Default)**
```yaml
loadGeneration:
  workflows: 10
  workflowDelay: 1000
  activitiesPerWorkflow: 30
```
**Result**: 10 workflows starting 1 second apart, each with 30 activities (300 total activities)

#### **2. Burst Load**
```yaml
loadGeneration:
  workflows: 25
  workflowDelay: 0
  activitiesPerWorkflow: 60
```
**Result**: 25 workflows all starting immediately (1500 total activities)

#### **3. Sustained Load**
```yaml
loadGeneration:
  workflows: 50
  workflowDelay: 2000
  activitiesPerWorkflow: 100
```
**Result**: 5 long-running workflows with 2-second delays between starts (5000 total activities)

#### **4. Light Load**
```yaml
loadGeneration:
  workflows: 1
  workflowDelay: 0
  activitiesPerWorkflow: 20
```
**Result**: Single workflow with 20 activities for minimal load testing

## Monitoring

### Metrics Endpoints
- **Prometheus Metrics**: http://127.0.0.1:8004/metrics
  - Exposed automatically when running worker mode only
  - Real-time autoscaling and worker performance metrics
  - Prometheus-compatible format with sanitized names
  - **Note**: Metrics server is not started in trigger mode

### Grafana Dashboard
Access the Cadence client dashboard at: http://localhost:3000/d/dehkspwgabvuoc/cadence-client

### Key Metrics to Monitor

1. **Worker Performance Metrics**:
   - `cadence_worker_decision_poll_success_count` - Successful decision task polls
   - `cadence_worker_activity_poll_success_count` - Successful activity task polls
   - `cadence_worker_decision_poll_count` - Total decision task poll attempts
   - `cadence_worker_activity_poll_count` - Total activity task poll attempts

2. **Autoscaling Behavior Metrics**:
   - `cadence_worker_poller_count` - Number of active poller goroutines (key autoscaling indicator)
   - `cadence_concurrency_auto_scaler_poller_quota` - Current poller quota for autoscaling
   - `cadence_concurrency_auto_scaler_poller_wait_time` - Time pollers wait for tasks
   - `cadence_concurrency_auto_scaler_scale_up_count` - Number of scale-up events
   - `cadence_concurrency_auto_scaler_scale_down_count` - Number of scale-down events

## How It Works

### Load Generation
The sample creates multiple workflows that execute activities in parallel, with each workflow:
- Starting with configurable delays (`workflowDelay`) to create sustained load patterns
- Executing a configurable number of activities (`activitiesPerWorkflow`) per workflow
- Each activity taking 1-6 seconds to complete (configurable via `minProcessingTime`/`maxProcessingTime`)
- Recording metrics about execution time
- Creating varying load patterns with configurable batch delays within each workflow

### Autoscaling Demonstration
The worker uses `worker.NewV2` with `AutoScalerOptions` to:
- Start with configurable poller goroutines (`pollerInitCount`)
- Scale down to minimum pollers (`pollerMinCount`) when load is low
- Scale up to maximum pollers (`pollerMaxCount`) when load is high
- Automatically adjust based on task queue depth and processing time

### Metrics Collection
The sample uses Tally with Prometheus reporter for comprehensive metrics:
- **Real-time autoscaling metrics** - Poller count changes, quota adjustments, scale events
- **Worker performance metrics** - Task processing rates, poller utilization, queue depths
- **Standard Cadence metrics** - All metrics automatically emitted by the Cadence Go client
- **Sanitized metric names** - Prometheus-compatible format with proper character replacement

## Production Considerations

### Scaling
- Adjust `pollerMinCount`, `pollerMaxCount`, and `pollerInitCount` based on your workload
- Monitor worker performance and adjust autoscaling parameters
- Use multiple worker instances for high availability

### Monitoring
- Configure Prometheus to scrape metrics regularly (latest version of Cadence server is configured to do this)
- Set up alerts for worker performance issues
- Use Grafana dashboards to visualize autoscaling behavior
- Monitor poller count changes to verify autoscaling is working

### Security
- Secure the Prometheus endpoint in production
- Use authentication for metrics access
- Consider using HTTPS for metrics endpoints

## Testing

The sample includes unit tests for the configuration loading functionality. Run these tests if you make any changes to the config:

### Running Tests
```bash
# Run all tests
go test -v

# Run specific test
go test -v -run TestLoadConfiguration_SuccessfulLoading

# Run tests with coverage
go test -v -cover
```

### Test Coverage
The tests cover:
- **Successful configuration loading** - Complete YAML files with all fields
- **Missing file fallback** - Graceful handling when config file doesn't exist
- **Default value application** - Ensuring all fields have sensible defaults

### Configuration Testing
The tests validate that the improved configuration system:
- Handles embedded struct issues properly
- Applies defaults correctly for missing fields
- Provides clear error messages for configuration problems
- Maintains backward compatibility

## Troubleshooting

### Common Issues

1. **Worker Not Starting**:
   - Check Cadence server is running
   - Verify domain exists
   - Check configuration file
   - Ensure using compatible Cadence client version

2. **Autoscaling Not Working**:
   - Verify `worker.NewV2` is being used
   - Check `AutoScalerOptions.Enabled` is true
   - Monitor poller count changes in logs
   - Ensure sufficient load is being generated

3. **Configuration Issues**:
   - Verify configuration file path is correct
   - Check YAML syntax in configuration file
   - Review default values if config file is not found

4. **Metrics Not Appearing**:
   - Verify worker is running (metrics are exposed automatically)
   - Check metrics endpoint is accessible: http://127.0.0.1:8004/metrics
   - Ensure Prometheus is configured to scrape the endpoint
   - Check for metric name sanitization issues

5. **Dashboard Not Loading**:
   - Verify Grafana is running
   - Check dashboard URL is correct
   - Ensure Prometheus data source is configured


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/activities.go
================================================
package main

import (
	"context"
	"math/rand"
	"time"

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

const (
	loadGenerationActivityName = "loadGenerationActivity"
)

// LoadGenerationActivity simulates work that can be scaled
// It includes random delays to simulate real-world processing time
func LoadGenerationActivity(ctx context.Context, taskID int, minProcessingTime, maxProcessingTime int) error {
	startTime := time.Now()
	logger := activity.GetLogger(ctx)
	logger.Info("Load generation activity started", zap.Int("taskID", taskID))

	// Simulate variable processing time using configuration values
	processingTime := time.Duration(rand.Intn(maxProcessingTime - minProcessingTime) + minProcessingTime) * time.Millisecond
	time.Sleep(processingTime)

	duration := time.Since(startTime)

	logger.Info("Load generation activity completed",
		zap.Int("taskID", taskID),
		zap.Duration("processingTime", processingTime),
		zap.Duration("totalDuration", duration))

	return nil
}


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/config/autoscaling.yaml
================================================
# Configuration for autoscaling monitoring sample
domain: "default"
service: "cadence-frontend"
host: "localhost:7833"

# Prometheus configuration for metrics collection
prometheus:
  listenAddress: "127.0.0.1:8004"

# Autoscaling configuration
# These settings control the worker's concurrency and autoscaling behavior
autoscaling:
  # Worker autoscaling settings
  pollerMinCount: 2
  pollerMaxCount: 8
  pollerInitCount: 4
  
  # Worker load simulation settings
  loadGeneration:
    # Workflow-level settings
    workflows: 10             # Number of workflows to start
    workflowDelay: 1000       # Delay between starting workflows (milliseconds)
    
    # Activity-level settings (per workflow)
    activitiesPerWorkflow: 30 # Number of activities per workflow
    batchDelay: 750         # Delay between activity batches within workflow (milliseconds)
    
    # Activity processing time range (milliseconds)
    minProcessingTime: 1000
    maxProcessingTime: 6000


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/config.go
================================================
package main

import (
	"fmt"
	"os"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
	"github.com/uber-go/tally/prometheus"
	"gopkg.in/yaml.v3"
)

// AutoscalingConfiguration uses a flattened structure to avoid embedded struct issues
type AutoscalingConfiguration struct {
	// Base configuration fields (explicit, not embedded)
	DomainName      string                    `yaml:"domain"`
	ServiceName     string                    `yaml:"service"`
	HostNameAndPort string                    `yaml:"host"`
	Prometheus      *prometheus.Configuration `yaml:"prometheus"`

	// Autoscaling-specific fields
	Autoscaling AutoscalingSettings `yaml:"autoscaling"`
}

// AutoscalingSettings contains the autoscaling configuration
type AutoscalingSettings struct {
	// Worker autoscaling settings
	PollerMinCount  int `yaml:"pollerMinCount"`
	PollerMaxCount  int `yaml:"pollerMaxCount"`
	PollerInitCount int `yaml:"pollerInitCount"`

	// Load generation settings
	LoadGeneration LoadGenerationSettings `yaml:"loadGeneration"`
}

// LoadGenerationSettings contains the load generation configuration
type LoadGenerationSettings struct {
	// Workflow-level settings
	Workflows     int `yaml:"workflows"`
	WorkflowDelay int `yaml:"workflowDelay"`

	// Activity-level settings (per workflow)
	ActivitiesPerWorkflow int `yaml:"activitiesPerWorkflow"`
	BatchDelay            int `yaml:"batchDelay"`
	MinProcessingTime     int `yaml:"minProcessingTime"`
	MaxProcessingTime     int `yaml:"maxProcessingTime"`
}

// Default values as constants for easy maintenance
const (
	DefaultDomainName      = "default"
	DefaultServiceName     = "cadence-frontend"
	DefaultHostNameAndPort = "localhost:7833"
	DefaultPrometheusAddr  = "127.0.0.1:8004"

	DefaultPollerMinCount  = 2
	DefaultPollerMaxCount  = 8
	DefaultPollerInitCount = 4

	DefaultWorkflows             = 10
	DefaultWorkflowDelay         = 1000
	DefaultActivitiesPerWorkflow = 30
	DefaultBatchDelay            = 2000
	DefaultMinProcessingTime     = 1000
	DefaultMaxProcessingTime     = 6000
)

// DefaultAutoscalingConfiguration returns default configuration
func DefaultAutoscalingConfiguration() AutoscalingConfiguration {
	return AutoscalingConfiguration{
		DomainName:      DefaultDomainName,
		ServiceName:     DefaultServiceName,
		HostNameAndPort: DefaultHostNameAndPort,
		Prometheus: &prometheus.Configuration{
			ListenAddress: DefaultPrometheusAddr,
		},
		Autoscaling: AutoscalingSettings{
			PollerMinCount:  DefaultPollerMinCount,
			PollerMaxCount:  DefaultPollerMaxCount,
			PollerInitCount: DefaultPollerInitCount,
			LoadGeneration: LoadGenerationSettings{
				Workflows:             DefaultWorkflows,
				WorkflowDelay:         DefaultWorkflowDelay,
				ActivitiesPerWorkflow: DefaultActivitiesPerWorkflow,
				BatchDelay:            DefaultBatchDelay,
				MinProcessingTime:     DefaultMinProcessingTime,
				MaxProcessingTime:     DefaultMaxProcessingTime,
			},
		},
	}
}

// loadConfiguration loads the autoscaling configuration from file
func loadConfiguration(configFile string) AutoscalingConfiguration {
	// Start with defaults
	config := DefaultAutoscalingConfiguration()

	// Read config file
	configData, err := os.ReadFile(configFile)
	if err != nil {
		fmt.Printf("Failed to read config file: %v, using defaults\n", err)
		return config
	}

	// Unmarshal into the config struct
	if err := yaml.Unmarshal(configData, &config); err != nil {
		fmt.Printf("Error parsing configuration: %v, using defaults\n", err)
		return DefaultAutoscalingConfiguration()
	}

	// Apply defaults for any missing fields
	config.applyDefaults()

	return config
}

// applyDefaults ensures all fields have sensible values
func (c *AutoscalingConfiguration) applyDefaults() {
	// Base configuration defaults
	if c.DomainName == "" {
		c.DomainName = DefaultDomainName
	}
	if c.ServiceName == "" {
		c.ServiceName = DefaultServiceName
	}
	if c.HostNameAndPort == "" {
		c.HostNameAndPort = DefaultHostNameAndPort
	}
	if c.Prometheus == nil {
		c.Prometheus = &prometheus.Configuration{
			ListenAddress: DefaultPrometheusAddr,
		}
	}

	// Autoscaling defaults
	if c.Autoscaling.PollerMinCount == 0 {
		c.Autoscaling.PollerMinCount = DefaultPollerMinCount
	}
	if c.Autoscaling.PollerMaxCount == 0 {
		c.Autoscaling.PollerMaxCount = DefaultPollerMaxCount
	}
	if c.Autoscaling.PollerInitCount == 0 {
		c.Autoscaling.PollerInitCount = DefaultPollerInitCount
	}

	// Load generation defaults
	if c.Autoscaling.LoadGeneration.Workflows == 0 {
		c.Autoscaling.LoadGeneration.Workflows = DefaultWorkflows
	}
	if c.Autoscaling.LoadGeneration.WorkflowDelay == 0 {
		c.Autoscaling.LoadGeneration.WorkflowDelay = DefaultWorkflowDelay
	}
	if c.Autoscaling.LoadGeneration.ActivitiesPerWorkflow == 0 {
		c.Autoscaling.LoadGeneration.ActivitiesPerWorkflow = DefaultActivitiesPerWorkflow
	}
	if c.Autoscaling.LoadGeneration.BatchDelay == 0 {
		c.Autoscaling.LoadGeneration.BatchDelay = DefaultBatchDelay
	}
	if c.Autoscaling.LoadGeneration.MinProcessingTime == 0 {
		c.Autoscaling.LoadGeneration.MinProcessingTime = DefaultMinProcessingTime
	}
	if c.Autoscaling.LoadGeneration.MaxProcessingTime == 0 {
		c.Autoscaling.LoadGeneration.MaxProcessingTime = DefaultMaxProcessingTime
	}
}

// ToCommonConfiguration converts to the common.Configuration type for compatibility
func (c *AutoscalingConfiguration) ToCommonConfiguration() common.Configuration {
	return common.Configuration{
		DomainName:      c.DomainName,
		ServiceName:     c.ServiceName,
		HostNameAndPort: c.HostNameAndPort,
		Prometheus:      c.Prometheus,
	}
}


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/config_test.go
================================================
package main

import (
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// Test the improved configuration loader for regressions
func TestLoadConfiguration_SuccessfulLoading(t *testing.T) {
	// Create a temporary configuration file with all fields populated
	configContent := `
domain: "test-domain"
service: "test-service"
host: "test-host:7833"
prometheus:
  listenAddress: "127.0.0.1:9000"
autoscaling:
  pollerMinCount: 3
  pollerMaxCount: 10
  pollerInitCount: 5
  loadGeneration:
    workflows: 10
    workflowDelay: 1000
    activitiesPerWorkflow: 30
    batchDelay: 5
    minProcessingTime: 2000
    maxProcessingTime: 8000
`

	// Create temporary file
	tmpFile, err := os.CreateTemp("", "test-config-*.yaml")
	require.NoError(t, err)
	defer os.Remove(tmpFile.Name())

	_, err = tmpFile.WriteString(configContent)
	require.NoError(t, err)
	tmpFile.Close()

	// Load configuration
	config := loadConfiguration(tmpFile.Name())

	// Validate all fields are populated correctly
	assert.Equal(t, "test-domain", config.DomainName)
	assert.Equal(t, "test-service", config.ServiceName)
	assert.Equal(t, "test-host:7833", config.HostNameAndPort)
	require.NotNil(t, config.Prometheus)
	assert.Equal(t, "127.0.0.1:9000", config.Prometheus.ListenAddress)
	assert.Equal(t, 3, config.Autoscaling.PollerMinCount)
	assert.Equal(t, 10, config.Autoscaling.PollerMaxCount)
	assert.Equal(t, 5, config.Autoscaling.PollerInitCount)
	assert.Equal(t, 10, config.Autoscaling.LoadGeneration.Workflows)
	assert.Equal(t, 1000, config.Autoscaling.LoadGeneration.WorkflowDelay)
	assert.Equal(t, 30, config.Autoscaling.LoadGeneration.ActivitiesPerWorkflow)
	assert.Equal(t, 5, config.Autoscaling.LoadGeneration.BatchDelay)
	assert.Equal(t, 2000, config.Autoscaling.LoadGeneration.MinProcessingTime)
	assert.Equal(t, 8000, config.Autoscaling.LoadGeneration.MaxProcessingTime)
}

func TestLoadConfiguration_MissingFileFallback(t *testing.T) {
	// Use a non-existent file path
	config := loadConfiguration("/non/existent/path/config.yaml")

	// Validate that default configuration is returned
	assert.Equal(t, DefaultDomainName, config.DomainName)
	assert.Equal(t, DefaultServiceName, config.ServiceName)
	assert.Equal(t, DefaultHostNameAndPort, config.HostNameAndPort)
	assert.Equal(t, DefaultPollerMinCount, config.Autoscaling.PollerMinCount)
	assert.Equal(t, DefaultPollerMaxCount, config.Autoscaling.PollerMaxCount)
	assert.Equal(t, DefaultPollerInitCount, config.Autoscaling.PollerInitCount)
	assert.Equal(t, DefaultWorkflows, config.Autoscaling.LoadGeneration.Workflows)
	assert.Equal(t, DefaultWorkflowDelay, config.Autoscaling.LoadGeneration.WorkflowDelay)
	assert.Equal(t, DefaultActivitiesPerWorkflow, config.Autoscaling.LoadGeneration.ActivitiesPerWorkflow)
	assert.Equal(t, DefaultBatchDelay, config.Autoscaling.LoadGeneration.BatchDelay)
	assert.Equal(t, DefaultMinProcessingTime, config.Autoscaling.LoadGeneration.MinProcessingTime)
	assert.Equal(t, DefaultMaxProcessingTime, config.Autoscaling.LoadGeneration.MaxProcessingTime)
}

func TestDefaultAutoscalingConfiguration(t *testing.T) {
	config := DefaultAutoscalingConfiguration()

	// Validate all default values
	assert.Equal(t, DefaultDomainName, config.DomainName)
	assert.Equal(t, DefaultServiceName, config.ServiceName)
	assert.Equal(t, DefaultHostNameAndPort, config.HostNameAndPort)
	require.NotNil(t, config.Prometheus)
	assert.Equal(t, DefaultPrometheusAddr, config.Prometheus.ListenAddress)
	assert.Equal(t, DefaultPollerMinCount, config.Autoscaling.PollerMinCount)
	assert.Equal(t, DefaultPollerMaxCount, config.Autoscaling.PollerMaxCount)
	assert.Equal(t, DefaultPollerInitCount, config.Autoscaling.PollerInitCount)
	assert.Equal(t, DefaultWorkflows, config.Autoscaling.LoadGeneration.Workflows)
	assert.Equal(t, DefaultWorkflowDelay, config.Autoscaling.LoadGeneration.WorkflowDelay)
	assert.Equal(t, DefaultActivitiesPerWorkflow, config.Autoscaling.LoadGeneration.ActivitiesPerWorkflow)
	assert.Equal(t, DefaultBatchDelay, config.Autoscaling.LoadGeneration.BatchDelay)
	assert.Equal(t, DefaultMinProcessingTime, config.Autoscaling.LoadGeneration.MinProcessingTime)
	assert.Equal(t, DefaultMaxProcessingTime, config.Autoscaling.LoadGeneration.MaxProcessingTime)
}

func TestApplyDefaults(t *testing.T) {
	// Test with empty configuration
	config := AutoscalingConfiguration{}
	config.applyDefaults()

	// Validate that all defaults are applied
	assert.Equal(t, DefaultDomainName, config.DomainName)
	assert.Equal(t, DefaultServiceName, config.ServiceName)
	assert.Equal(t, DefaultHostNameAndPort, config.HostNameAndPort)
	require.NotNil(t, config.Prometheus)
	assert.Equal(t, DefaultPrometheusAddr, config.Prometheus.ListenAddress)
	assert.Equal(t, DefaultPollerMinCount, config.Autoscaling.PollerMinCount)
	assert.Equal(t, DefaultPollerMaxCount, config.Autoscaling.PollerMaxCount)
	assert.Equal(t, DefaultPollerInitCount, config.Autoscaling.PollerInitCount)
	assert.Equal(t, DefaultWorkflows, config.Autoscaling.LoadGeneration.Workflows)
	assert.Equal(t, DefaultWorkflowDelay, config.Autoscaling.LoadGeneration.WorkflowDelay)
	assert.Equal(t, DefaultActivitiesPerWorkflow, config.Autoscaling.LoadGeneration.ActivitiesPerWorkflow)
	assert.Equal(t, DefaultBatchDelay, config.Autoscaling.LoadGeneration.BatchDelay)
	assert.Equal(t, DefaultMinProcessingTime, config.Autoscaling.LoadGeneration.MinProcessingTime)
	assert.Equal(t, DefaultMaxProcessingTime, config.Autoscaling.LoadGeneration.MaxProcessingTime)
}


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/main.go
================================================
package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
	"github.com/uber-go/tally"
	"github.com/uber-go/tally/prometheus"
	"go.uber.org/zap"
)

const (
	ApplicationName = "autoscaling-monitoring"
)

// findConfigFile finds the config file relative to the executable location
func findConfigFile() string {
	// Get the directory where the executable is located
	execPath, err := os.Executable()
	if err != nil {
		// Fallback to current working directory if we can't determine executable path
		return "config/autoscaling.yaml"
	}
	execDir := filepath.Dir(execPath)

	// Try to find the config file relative to the executable
	// The executable is in bin/, so we need to go up to the repo root and then to the config
	configPath := filepath.Join(execDir, "..", "cmd", "samples", "advanced", "autoscaling-monitoring", "config", "autoscaling.yaml")

	// Check if the config file exists at this path
	if _, err := os.Stat(configPath); err == nil {
		return configPath
	}

	// Fallback to the original relative path (for development when running with go run)
	return "config/autoscaling.yaml"
}

func main() {
	// Parse command line arguments
	var mode string
	var configFile string
	flag.StringVar(&mode, "m", "worker", "Mode: worker or trigger")
	flag.StringVar(&configFile, "config", "", "Path to configuration file")
	flag.Parse()

	// Load configuration
	if configFile == "" {
		configFile = findConfigFile()
	}
	config := loadConfiguration(configFile)

	// Setup common helper with our configuration
	var h common.SampleHelper
	h.Config = config.ToCommonConfiguration()

	// Set up logging
	logger, err := zap.NewDevelopment()
	if err != nil {
		panic(fmt.Sprintf("Failed to setup logger: %v", err))
	}
	h.Logger = logger

	// Set up service client using our config
	h.Builder = common.NewBuilder(logger).
		SetHostPort(config.HostNameAndPort).
		SetDomain(config.DomainName)

	service, err := h.Builder.BuildServiceClient()
	if err != nil {
		panic(fmt.Sprintf("Failed to build service client: %v", err))
	}
	h.Service = service

	// Set up metrics scope with Tally Prometheus reporter
	var (
		safeCharacters  = []rune{'_'}
		sanitizeOptions = tally.SanitizeOptions{
			NameCharacters: tally.ValidCharacters{
				Ranges:     tally.AlphanumericRange,
				Characters: safeCharacters,
			},
			KeyCharacters: tally.ValidCharacters{
				Ranges:     tally.AlphanumericRange,
				Characters: safeCharacters,
			},
			ValueCharacters: tally.ValidCharacters{
				Ranges:     tally.AlphanumericRange,
				Characters: safeCharacters,
			},
			ReplacementCharacter: tally.DefaultReplacementCharacter,
		}
	)

	// Create Prometheus reporter
	reporter := prometheus.NewReporter(prometheus.Options{})

	// Create root scope with proper options
	scope, closer := tally.NewRootScope(tally.ScopeOptions{
		Tags:            map[string]string{"service": "autoscaling-monitoring"},
		SanitizeOptions: &sanitizeOptions,
		CachedReporter:  reporter,
	}, 10)
	defer closer.Close()

	// Set up metrics scope for helper
	h.WorkerMetricScope = scope
	h.ServiceMetricScope = scope

	switch mode {
	case "worker":
		// Start metrics server only in worker mode
		if config.Prometheus != nil {
			go func() {
				http.Handle("/metrics", reporter.HTTPHandler())
				logger.Info("Starting Prometheus metrics server",
					zap.String("port", config.Prometheus.ListenAddress))
				if err := http.ListenAndServe(config.Prometheus.ListenAddress, nil); err != nil {
					logger.Error("Failed to start metrics server", zap.Error(err))
				}
			}()
		}
		startWorkers(&h, &config)
	case "trigger":
		startWorkflow(&h, &config)
	default:
		fmt.Printf("Unknown mode: %s\n", mode)
		os.Exit(1)
	}
}

func startWorkers(h *common.SampleHelper, config *AutoscalingConfiguration) {
	startWorkersWithAutoscaling(h, config)
}

func startWorkflow(h *common.SampleHelper, config *AutoscalingConfiguration) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              fmt.Sprintf("autoscaling_%s", uuid.New()),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute * 10,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}

	// Use configuration values
	workflows := config.Autoscaling.LoadGeneration.Workflows
	workflowDelay := config.Autoscaling.LoadGeneration.WorkflowDelay
	activitiesPerWorkflow := config.Autoscaling.LoadGeneration.ActivitiesPerWorkflow
	batchDelay := config.Autoscaling.LoadGeneration.BatchDelay
	minProcessingTime := config.Autoscaling.LoadGeneration.MinProcessingTime
	maxProcessingTime := config.Autoscaling.LoadGeneration.MaxProcessingTime

	// Start multiple workflows with delays
	for i := 0; i < workflows; i++ {
		workflowOptions.ID = fmt.Sprintf("autoscaling_%d_%s", i, uuid.New())
		h.StartWorkflow(workflowOptions, autoscalingWorkflowName, activitiesPerWorkflow, batchDelay, minProcessingTime, maxProcessingTime)

		// Add delay between workflows (except for the last one)
		if i < workflows-1 {
			time.Sleep(time.Duration(workflowDelay) * time.Millisecond)
		}
	}

	fmt.Printf("Started %d autoscaling workflows with %d activities each\n", workflows, activitiesPerWorkflow)
	fmt.Println("Monitor the worker performance and autoscaling behavior in Grafana:")
	fmt.Println("http://localhost:3000/d/dehkspwgabvuoc/cadence-client")
}


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/worker_config.go
================================================
package main

import (
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"
	"go.uber.org/cadence/workflow"
	"go.uber.org/zap"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// startWorkersWithAutoscaling starts workers with autoscaling configuration
func startWorkersWithAutoscaling(h *common.SampleHelper, config *AutoscalingConfiguration) {
	// Configure worker options with autoscaling-friendly settings from config
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
		AutoScalerOptions: worker.AutoScalerOptions{
			Enabled:         true,
			PollerMinCount:  config.Autoscaling.PollerMinCount,
			PollerMaxCount:  config.Autoscaling.PollerMaxCount,
			PollerInitCount: config.Autoscaling.PollerInitCount,
		},
		FeatureFlags: client.FeatureFlags{
			WorkflowExecutionAlreadyCompletedErrorEnabled: true,
		},
	}

	h.Logger.Info("Starting workers with autoscaling configuration",
		zap.Bool("AutoScalerEnabled", workerOptions.AutoScalerOptions.Enabled),
		zap.Int("PollerMinCount", workerOptions.AutoScalerOptions.PollerMinCount),
		zap.Int("PollerMaxCount", workerOptions.AutoScalerOptions.PollerMaxCount),
		zap.Int("PollerInitCount", workerOptions.AutoScalerOptions.PollerInitCount))

	// Use worker.NewV2 for autoscaling support
	w, err := worker.NewV2(h.Service, h.Config.DomainName, ApplicationName, workerOptions)
	if err != nil {
		h.Logger.Fatal("Failed to create worker with autoscaling", zap.Error(err))
	}

	// Register workflows and activities
	registerWorkflowAndActivityForAutoscaling(w)

	// Start the worker
	err = w.Run()
	if err != nil {
		h.Logger.Fatal("Failed to run worker", zap.Error(err))
	}
}

// registerWorkflowAndActivityForAutoscaling registers the workflow and activities
func registerWorkflowAndActivityForAutoscaling(w worker.Worker) {
	w.RegisterWorkflowWithOptions(AutoscalingWorkflow, workflow.RegisterOptions{Name: autoscalingWorkflowName})
	w.RegisterActivityWithOptions(LoadGenerationActivity, activity.RegisterOptions{Name: loadGenerationActivityName})
}


================================================
FILE: cmd/samples/advanced/autoscaling-monitoring/workflow.go
================================================
package main

import (
	"time"

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

const (
	autoscalingWorkflowName = "autoscalingWorkflow"
)

// AutoscalingWorkflow demonstrates a workflow that can generate load
// to test worker poller autoscaling
func AutoscalingWorkflow(ctx workflow.Context, activitiesPerWorkflow int, batchDelay int, minProcessingTime, maxProcessingTime int) error {
	logger := workflow.GetLogger(ctx)
	logger.Info("Autoscaling workflow started", zap.Int("activitiesPerWorkflow", activitiesPerWorkflow))

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

	// Generate load by executing activities in parallel
	var futures []workflow.Future

	// Execute activities in batches to create varying load
	for i := 0; i < activitiesPerWorkflow; i++ {
		future := workflow.ExecuteActivity(ctx, LoadGenerationActivity, i, minProcessingTime, maxProcessingTime)
		futures = append(futures, future)

		// Add some delay between batches to simulate real-world patterns
		// Use batch delay from configuration
		if i > 0 && i % 10 == 0 {
			workflow.Sleep(ctx, time.Duration(batchDelay)*time.Millisecond)
		}
	}

	// Wait for all activities to complete
	for i, future := range futures {
		var result error
		if err := future.Get(ctx, &result); err != nil {
			logger.Error("Activity failed", zap.Int("taskID", i), zap.Error(err))
			return err
		}
	}

	logger.Info("Autoscaling workflow completed", zap.Int("totalActivities", len(futures)))
	return nil
}


================================================
FILE: cmd/samples/common/factory.go
================================================
package common

import (
	"errors"

	"github.com/opentracing/opentracing-go"
	"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/client"
	"go.uber.org/cadence/compatibility"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/workflow"
	"go.uber.org/yarpc"
	"go.uber.org/yarpc/transport/grpc"
	"go.uber.org/zap"
)

const (
	_cadenceClientName      = "cadence-client"
	_cadenceFrontendService = "cadence-frontend"
)

// WorkflowClientBuilder build client to cadence service
type WorkflowClientBuilder struct {
	hostPort       string
	dispatcher     *yarpc.Dispatcher
	domain         string
	clientIdentity string
	metricsScope   tally.Scope
	Logger         *zap.Logger
	ctxProps       []workflow.ContextPropagator
	dataConverter  encoded.DataConverter
	tracer         opentracing.Tracer
}

// NewBuilder creates a new WorkflowClientBuilder
func NewBuilder(logger *zap.Logger) *WorkflowClientBuilder {
	return &WorkflowClientBuilder{
		Logger: logger,
	}
}

// SetHostPort sets the hostport for the builder
func (b *WorkflowClientBuilder) SetHostPort(hostport string) *WorkflowClientBuilder {
	b.hostPort = hostport
	return b
}

// SetDomain sets the domain for the builder
func (b *WorkflowClientBuilder) SetDomain(domain string) *WorkflowClientBuilder {
	b.domain = domain
	return b
}

// SetClientIdentity sets the identity for the builder
func (b *WorkflowClientBuilder) SetClientIdentity(identity string) *WorkflowClientBuilder {
	b.clientIdentity = identity
	return b
}

// SetMetricsScope sets the metrics scope for the builder
func (b *WorkflowClientBuilder) SetMetricsScope(metricsScope tally.Scope) *WorkflowClientBuilder {
	b.metricsScope = metricsScope
	return b
}

// SetDispatcher sets the dispatcher for the builder
func (b *WorkflowClientBuilder) SetDispatcher(dispatcher *yarpc.Dispatcher) *WorkflowClientBuilder {
	b.dispatcher = dispatcher
	return b
}

// SetContextPropagators sets the context propagators for the builder
func (b *WorkflowClientBuilder) SetContextPropagators(ctxProps []workflow.ContextPropagator) *WorkflowClientBuilder {
	b.ctxProps = ctxProps
	return b
}

// SetDataConverter sets the data converter for the builder
func (b *WorkflowClientBuilder) SetDataConverter(dataConverter encoded.DataConverter) *WorkflowClientBuilder {
	b.dataConverter = dataConverter
	return b
}

// SetTracer sets the tracer for the builder
func (b *WorkflowClientBuilder) SetTracer(tracer opentracing.Tracer) *WorkflowClientBuilder {
	b.tracer = tracer
	return b
}

// BuildCadenceClient builds a client to cadence service
func (b *WorkflowClientBuilder) BuildCadenceClient() (client.Client, error) {
	service, err := b.BuildServiceClient()
	if err != nil {
		return nil, err
	}

	return client.NewClient(
		service,
		b.domain,
		&client.Options{
			Identity:           b.clientIdentity,
			MetricsScope:       b.metricsScope,
			DataConverter:      b.dataConverter,
			ContextPropagators: b.ctxProps,
			Tracer:             b.tracer,
			FeatureFlags: client.FeatureFlags{
				WorkflowExecutionAlreadyCompletedErrorEnabled: true,
			},
		}), nil
}

// BuildCadenceDomainClient builds a domain client to cadence service
func (b *WorkflowClientBuilder) BuildCadenceDomainClient() (client.DomainClient, error) {
	service, err := b.BuildServiceClient()
	if err != nil {
		return nil, err
	}

	return client.NewDomainClient(
		service,
		&client.Options{
			Identity:           b.clientIdentity,
			MetricsScope:       b.metricsScope,
			ContextPropagators: b.ctxProps,
			FeatureFlags: client.FeatureFlags{
				WorkflowExecutionAlreadyCompletedErrorEnabled: true,
			},
		},
	), nil
}

// BuildServiceClient builds a rpc service client to cadence service
func (b *WorkflowClientBuilder) BuildServiceClient() (workflowserviceclient.Interface, error) {
	if err := b.build(); err != nil {
		return nil, err
	}

	if b.dispatcher == nil {
		b.Logger.Fatal("No RPC dispatcher provided to create a connection to Cadence Service")
	}

	clientConfig := b.dispatcher.ClientConfig(_cadenceFrontendService)
	return compatibility.NewThrift2ProtoAdapter(
		apiv1.NewDomainAPIYARPCClient(clientConfig),
		apiv1.NewWorkflowAPIYARPCClient(clientConfig),
		apiv1.NewWorkerAPIYARPCClient(clientConfig),
		apiv1.NewVisibilityAPIYARPCClient(clientConfig),
	), nil
}

func (b *WorkflowClientBuilder) build() error {
	if b.dispatcher != nil {
		return nil
	}

	if len(b.hostPort) == 0 {
		return errors.New("HostPort is empty")
	}

	b.Logger.Debug("Creating RPC dispatcher outbound",
		zap.String("ServiceName", _cadenceFrontendService),
		zap.String("HostPort", b.hostPort))

	b.dispatcher = yarpc.NewDispatcher(yarpc.Config{
		Name: _cadenceClientName,
		Outbounds: yarpc.Outbounds{
			_cadenceFrontendService: {Unary: grpc.NewTransport().NewSingleOutbound(b.hostPort)},
		},
	})

	if b.dispatcher != nil {
		if err := b.dispatcher.Start(); err != nil {
			b.Logger.Fatal("Failed to create outbound transport channel: %v", zap.Error(err))
		}
	}

	return nil
}


================================================
FILE: cmd/samples/common/sample_helper.go
================================================
package common

import (
	"context"
	"fmt"
	"io/ioutil"
	"time"

	"github.com/opentracing/opentracing-go"
	"go.uber.org/cadence/.gen/go/shared"

	prom "github.com/m3db/prometheus_client_golang/prometheus"
	"github.com/uber-go/tally"
	"github.com/uber-go/tally/prometheus"
	"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/worker"
	"go.uber.org/cadence/workflow"
	"go.uber.org/zap"
	"gopkg.in/yaml.v2"
)

const (
	defaultConfigFile = "config/development.yaml"
)

type (
	// SampleHelper class for workflow sample helper.
	SampleHelper struct {
		Service            workflowserviceclient.Interface
		WorkerMetricScope  tally.Scope
		ServiceMetricScope tally.Scope
		Logger             *zap.Logger
		Config             Configuration
		Builder            *WorkflowClientBuilder
		DataConverter      encoded.DataConverter
		CtxPropagators     []workflow.ContextPropagator
		workflowRegistries []registryOption
		activityRegistries []registryOption
		Tracer             opentracing.Tracer

		configFile string
	}

	// Configuration for running samples.
	Configuration struct {
		DomainName      string                    `yaml:"domain"`
		ServiceName     string                    `yaml:"service"`
		HostNameAndPort string                    `yaml:"host"`
		Prometheus      *prometheus.Configuration `yaml:"prometheus"`
	}

	registryOption struct {
		registry interface{}
		alias    string
	}
)

var (
	safeCharacters = []rune{'_'}

	sanitizeOptions = tally.SanitizeOptions{
		NameCharacters: tally.ValidCharacters{
			Ranges:     tally.AlphanumericRange,
			Characters: safeCharacters,
		},
		KeyCharacters: tally.ValidCharacters{
			Ranges:     tally.AlphanumericRange,
			Characters: safeCharacters,
		},
		ValueCharacters: tally.ValidCharacters{
			Ranges:     tally.AlphanumericRange,
			Characters: safeCharacters,
		},
		ReplacementCharacter: tally.DefaultReplacementCharacter,
	}
)

// SetConfigFile sets the config file path
func (h *SampleHelper) SetConfigFile(configFile string) {
	h.configFile = configFile
}

// SetupServiceConfig setup the config for the sample code run
func (h *SampleHelper) SetupServiceConfig() {
	if h.Service != nil {
		return
	}

	if h.configFile == "" {
		h.configFile = defaultConfigFile
	}
	// Initialize developer config for running samples
	configData, err := ioutil.ReadFile(h.configFile)
	if err != nil {
		panic(fmt.Sprintf("Failed to log config file: %v, Error: %v", defaultConfigFile, err))
	}

	if err := yaml.Unmarshal(configData, &h.Config); err != nil {
		panic(fmt.Sprintf("Error initializing configuration: %v", err))
	}

	// Initialize logger for running samples
	logger, err := zap.NewDevelopment()
	if err != nil {
		panic(err)
	}

	logger.Info("Logger created.")
	h.Logger = logger
	h.ServiceMetricScope = tally.NoopScope
	h.WorkerMetricScope = tally.NoopScope

	if h.Config.Prometheus != nil {
		reporter, err := h.Config.Prometheus.NewReporter(
			prometheus.ConfigurationOptions{
				Registry: prom.NewRegistry(),
				OnError: func(err error) {
					logger.Warn("error in prometheus reporter", zap.Error(err))
				},
			},
		)
		if err != nil {
			panic(err)
		}

		h.WorkerMetricScope, _ = tally.NewRootScope(tally.ScopeOptions{
			Prefix:          "Worker_",
			Tags:            map[string]string{},
			CachedReporter:  reporter,
			Separator:       prometheus.DefaultSeparator,
			SanitizeOptions: &sanitizeOptions,
		}, 1*time.Second)

		// NOTE: this must be a different scope with different prefix, otherwise the metric will conflict
		h.ServiceMetricScope, _ = tally.NewRootScope(tally.ScopeOptions{
			Prefix:          "Service_",
			Tags:            map[string]string{},
			CachedReporter:  reporter,
			Separator:       prometheus.DefaultSeparator,
			SanitizeOptions: &sanitizeOptions,
		}, 1*time.Second)
	}
	h.Builder = NewBuilder(logger).
		SetHostPort(h.Config.HostNameAndPort).
		SetDomain(h.Config.DomainName).
		SetMetricsScope(h.ServiceMetricScope).
		SetDataConverter(h.DataConverter).
		SetTracer(h.Tracer).
		SetContextPropagators(h.CtxPropagators)
	service, err := h.Builder.BuildServiceClient()
	if err != nil {
		panic(err)
	}
	h.Service = service

	domainClient, _ := h.Builder.BuildCadenceDomainClient()
	_, err = domainClient.Describe(context.Background(), h.Config.DomainName)
	if err != nil {
		logger.Info("Domain doesn't exist", zap.String("Domain", h.Config.DomainName), zap.Error(err))
	} else {
		logger.Info("Domain successfully registered.", zap.String("Domain", h.Config.DomainName))
	}

	h.workflowRegistries = make([]registryOption, 0, 1)
	h.activityRegistries = make([]registryOption, 0, 1)
}

// StartWorkflow starts a workflow
func (h *SampleHelper) StartWorkflow(
	options client.StartWorkflowOptions,
	workflow interface{},
	args ...interface{},
) *workflow.Execution {
	return h.StartWorkflowWithCtx(context.Background(), options, workflow, args...)
}

// StartWorkflowWithCtx starts a workflow with the provided context
func (h *SampleHelper) StartWorkflowWithCtx(
	ctx context.Context,
	options client.StartWorkflowOptions,
	workflow interface{},
	args ...interface{},
) *workflow.Execution {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	we, err := workflowClient.StartWorkflow(ctx, options, workflow, args...)
	if err != nil {
		h.Logger.Error("Failed to create workflow", zap.Error(err))
		panic("Failed to create workflow.")
	} else {
		h.Logger.Info("Started Workflow", zap.String("WorkflowID", we.ID), zap.String("RunID", we.RunID))
		return we
	}
}

// SignalWithStartWorkflowWithCtx signals workflow and starts it if it's not yet started
func (h *SampleHelper) SignalWithStartWorkflowWithCtx(ctx context.Context, workflowID string, signalName string, signalArg interface{},
	options client.StartWorkflowOptions, workflow interface{}, workflowArgs ...interface{}) *workflow.Execution {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	we, err := workflowClient.SignalWithStartWorkflow(ctx, workflowID, signalName, signalArg, options, workflow, workflowArgs...)
	if err != nil {
		h.Logger.Error("Failed to signal with start workflow", zap.Error(err))
		panic("Failed to signal with start workflow.")

	} else {
		h.Logger.Info("Signaled and started Workflow", zap.String("WorkflowID", we.ID), zap.String("RunID", we.RunID))
	}
	return we
}

func (h *SampleHelper) RegisterWorkflow(workflow interface{}) {
	h.RegisterWorkflowWithAlias(workflow, "")
}

func (h *SampleHelper) RegisterWorkflowWithAlias(workflow interface{}, alias string) {
	registryOption := registryOption{
		registry: workflow,
		alias:    alias,
	}
	h.workflowRegistries = append(h.workflowRegistries, registryOption)
}

func (h *SampleHelper) RegisterActivity(activity interface{}) {
	h.RegisterActivityWithAlias(activity, "")
}

func (h *SampleHelper) RegisterActivityWithAlias(activity interface{}, alias string) {
	registryOption := registryOption{
		registry: activity,
		alias:    alias,
	}
	h.activityRegistries = append(h.activityRegistries, registryOption)
}

// StartWorkers starts workflow worker and activity worker based on configured options.
func (h *SampleHelper) StartWorkers(domainName string, groupName string, options worker.Options) worker.Worker {
	worker := worker.New(h.Service, domainName, groupName, options)
	h.registerWorkflowAndActivity(worker)

	err := worker.Start()
	if err != nil {
		h.Logger.Error("Failed to start workers.", zap.Error(err))
		panic("Failed to start workers")
	}

	return worker
}

func (h *SampleHelper) QueryWorkflow(workflowID, runID, queryType string, args ...interface{}) {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	resp, err := workflowClient.QueryWorkflow(context.Background(), workflowID, runID, queryType, args...)
	if err != nil {
		h.Logger.Error("Failed to query workflow", zap.Error(err))
		panic("Failed to query workflow.")
	}
	var result interface{}
	if err := resp.Get(&result); err != nil {
		h.Logger.Error("Failed to decode query result", zap.Error(err))
	}
	h.Logger.Info("Received query result", zap.Any("Result", result))
}

func (h *SampleHelper) ConsistentQueryWorkflow(
	valuePtr interface{},
	workflowID, runID, queryType string,
	args ...interface{},
) error {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	resp, err := workflowClient.QueryWorkflowWithOptions(context.Background(),
		&client.QueryWorkflowWithOptionsRequest{
			WorkflowID:            workflowID,
			RunID:                 runID,
			QueryType:             queryType,
			QueryConsistencyLevel: shared.QueryConsistencyLevelStrong.Ptr(),
			Args:                  args,
		})
	if err != nil {
		h.Logger.Error("Failed to query workflow", zap.Error(err))
		panic("Failed to query workflow.")
	}
	if err := resp.QueryResult.Get(&valuePtr); err != nil {
		h.Logger.Error("Failed to decode query result", zap.Error(err))
	}
	h.Logger.Info("Received consistent query result.", zap.Any("Result", valuePtr))
	return err
}

func (h *SampleHelper) SignalWorkflow(workflowID, signal string, data interface{}) {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	err = workflowClient.SignalWorkflow(context.Background(), workflowID, "", signal, data)
	if err != nil {
		h.Logger.Error("Failed to signal workflow", zap.Error(err))
		panic("Failed to signal workflow.")
	}
}

func (h *SampleHelper) CancelWorkflow(workflowID string) {
	workflowClient, err := h.Builder.BuildCadenceClient()
	if err != nil {
		h.Logger.Error("Failed to build cadence client.", zap.Error(err))
		panic(err)
	}

	err = workflowClient.CancelWorkflow(context.Background(), workflowID, "")
	if err != nil {
		h.Logger.Error("Failed to cancel workflow", zap.Error(err))
		panic("Failed to cancel workflow.")
	}
}

func (h *SampleHelper) registerWorkflowAndActivity(worker worker.Worker) {
	for _, w := range h.workflowRegistries {
		if len(w.alias) == 0 {
			worker.RegisterWorkflow(w.registry)
		} else {
			worker.RegisterWorkflowWithOptions(w.registry, workflow.RegisterOptions{Name: w.alias})
		}
	}
	for _, act := range h.activityRegistries {
		if len(act.alias) == 0 {
			worker.RegisterActivity(act.registry)
		} else {
			worker.RegisterActivityWithOptions(act.registry, activity.RegisterOptions{Name: act.alias})
		}
	}
}


================================================
FILE: cmd/samples/common/util.go
================================================
package common

// StringPtr returns pointer to a string
func StringPtr(v string) *string {
	return &v
}

// Int32Ptr returns pointer to a int32
func Int32Ptr(v int32) *int32 {
	return &v
}

// Int64Ptr returns pointer to a int64
func Int64Ptr(v int64) *int64 {
	return &v
}


================================================
FILE: cmd/samples/cron/cron_workflow.go
================================================
package main

import (
	"context"
	"time"

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

/**
 * This cron sample workflow will schedule job based on given schedule spec. The schedule spec in this sample demo is
 * very simple, but you could have more complicated scheduler logic that meet your needs.
 */

const (
	// timeout for activity task from put in queue to started
	activityScheduleToStartTimeout = time.Second * 10
	// timeout for activity from start to complete
	activityStartToCloseTimeout = time.Minute

	// WorkflowStartToCloseTimeout (from workflow start to workflow close)
	WorkflowStartToCloseTimeout = time.Minute * 20
	// DecisionTaskStartToCloseTimeout (from decision task started to decision task completed, usually very short)
	DecisionTaskStartToCloseTimeout = time.Second * 10
)

//
// Cron sample job activity.
//
func sampleCronActivity(ctx context.Context, beginTime, endTime time.Time) error {
	activity.GetLogger(ctx).Info("Cron job running.", zap.Time("beginTime_exclude", beginTime), zap.Time("endTime_include", endTime))
	// ...
	return nil
}

// SampleCronResult used to return data from one cron run to next cron run.
type SampleCronResult struct {
	EndTime time.Time
}

// sampleCronWorkflow workflow decider
func sampleCronWorkflow(ctx workflow.Context) (*SampleCronResult, error) {
	workflow.GetLogger(ctx).Info("Cron workflow started.", zap.Time("StartTime", workflow.Now(ctx)))

	ao := workflow.ActivityOptions{
		ScheduleToStartTimeout: activityScheduleToStartTimeout,
		StartToCloseTimeout:    activityStartToCloseTimeout,
	}
	ctx1 := workflow.WithActivityOptions(ctx, ao)

	startTime := time.Time{} // start from 0 time for first cron job
	if workflow.HasLastCompletionResult(ctx) {
		var lastResult SampleCronResult
		if err := workflow.GetLastCompletionResult(ctx, &lastResult); err == nil {
			startTime = lastResult.EndTime
		}
	}

	endTime := workflow.Now(ctx)

	err := workflow.ExecuteActivity(ctx1, sampleCronActivity, startTime, endTime).Get(ctx, nil)

	if err != nil {
		// cron job failed. but next cron should continue to be scheduled by Cadence server
		workflow.GetLogger(ctx).Error("Cron job failed.", zap.Error(err))
		return nil, err
	}

	return &SampleCronResult{EndTime: endTime}, nil
}


================================================
FILE: cmd/samples/cron/cron_workflow_test.go
================================================
package main

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/suite"
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/testsuite"
	"go.uber.org/cadence/workflow"
)

type UnitTestSuite struct {
	suite.Suite
	testsuite.WorkflowTestSuite

	env *testsuite.TestWorkflowEnvironment
}

func TestUnitTestSuite(t *testing.T) {
	suite.Run(t, new(UnitTestSuite))
}

func (s *UnitTestSuite) SetupTest() {
	s.env = s.NewTestWorkflowEnvironment()
	s.env.RegisterWorkflow(sampleCronWorkflow)
	s.env.RegisterActivity(sampleCronActivity)
}

func (s *UnitTestSuite) TearDownTest() {
	s.env.AssertExpectations(s.T())
}

func (s *UnitTestSuite) Test_CronWorkflow() {
	testWorkflow := func(ctx workflow.Context) error {
		ctx1 := workflow.WithChildOptions(ctx, workflow.ChildWorkflowOptions{
			ExecutionStartToCloseTimeout: time.Minute * 10,
			CronSchedule:                 "0 * * * *", // hourly
		})

		cronFuture := workflow.ExecuteChildWorkflow(ctx1, sampleCronWorkflow) // cron never stop so this future won't return

		// wait 2 hours for the cron (cron will execute 3 times)
		workflow.Sleep(ctx, time.Hour*2)
		s.False(cronFuture.IsReady())
		return nil
	}
	s.env.RegisterWorkflow(testWorkflow)

	s.env.OnActivity(sampleCronActivity, mock.Anything, mock.Anything, mock.Anything).Return(nil).Times(3)

	var startTimeList, endTimeList []time.Time
	s.env.SetOnActivityStartedListener(func(activityInfo *activity.Info, ctx context.Context, args encoded.Values) {
		var startTime, endTime time.Time
		err := args.Get(&startTime, &endTime)
		s.NoError(err)

		startTimeList = append(startTimeList, startTime)
		endTimeList = append(endTimeList, endTime)
	})

	startTime, _ := time.Parse(time.RFC3339, "2018-12-20T16:30:00-80:00")
	s.env.SetStartTime(startTime)

	s.env.ExecuteWorkflow(testWorkflow)

	s.True(s.env.IsWorkflowCompleted())
	err := s.env.GetWorkflowError()
	s.NoError(err)

	s.Equal(3, len(startTimeList))
	s.True(startTimeList[0].Equal(time.Time{}))
	s.True(endTimeList[0].Equal(startTime))

	s.True(startTimeList[1].Equal(startTime))
	s.True(endTimeList[1].Equal(startTime.Add(time.Minute * 30)))

	s.True(startTimeList[2].Equal(startTime.Add(time.Minute * 30)))
	s.True(endTimeList[2].Equal(startTime.Add(time.Minute * 90)))
}


================================================
FILE: cmd/samples/cron/main.go
================================================
package main

import (
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

const (
	// ApplicationName is the task list for this sample
	ApplicationName = "cronGroup"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
		FeatureFlags: client.FeatureFlags{
			WorkflowExecutionAlreadyCompletedErrorEnabled: true,
		},
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

//
// To start instance of the workflow.
//
func startWorkflow(h *common.SampleHelper, cron string) {
	// This workflow ID can be user business logic identifier as well.
	workflowID := "cron_" + uuid.New()
	workflowOptions := client.StartWorkflowOptions{
		ID:                              workflowID,
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute,
		DecisionTaskStartToCloseTimeout: time.Minute,
		CronSchedule:                    cron,
	}
	h.StartWorkflow(workflowOptions, sampleCronWorkflow)
}

func main() {
	var mode string
	var cron string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger.")
	flag.StringVar(&cron, "cron", "* * * * *", "Crontab schedule. Default \"* * * * *\"")
	flag.Parse()

	var h common.SampleHelper
	h.SetupServiceConfig()

	switch mode {
	case "worker":
		h.RegisterWorkflow(sampleCronWorkflow)
		h.RegisterActivity(sampleCronActivity)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":
		startWorkflow(&h, cron)
	}
}


================================================
FILE: cmd/samples/dsl/README.md
================================================
This sample demonstrates how to implement a DSL workflow. In this sample, we provide 2 sample yaml files each defines a custom workflow that can be processed by this dsl workflow sample code.

Steps to run this sample:
1) You need a cadence service running. See cmd/samples/README.md for more details.
2) Run "./bin/dsl -m worker" to start workers for dsl workflow.
3) Run "./bin/dsl -dslConfig cmd/samples/dsl/workflow1.yaml" to submit start request for workflow defined in workflow1.yaml file.

Next:
1) You can replace the dslConfig to workflow2.yaml to see the result.
2) You can also write your own yaml config to play with it.
3) You can replace the dummy activities to your own real activities to build real workflow based on this simple dsl workflow.


================================================
FILE: cmd/samples/dsl/activities.go
================================================
package main

import (
	"fmt"
)

func sampleActivity1(input []string) (string, error) {
	name := "sampleActivity1"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}

func sampleActivity2(input []string) (string, error) {
	name := "sampleActivity2"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}

func sampleActivity3(input []string) (string, error) {
	name := "sampleActivity3"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}

func sampleActivity4(input []string) (string, error) {
	name := "sampleActivity4"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}

func sampleActivity5(input []string) (string, error) {
	name := "sampleActivity5"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}


================================================
FILE: cmd/samples/dsl/main.go
================================================
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"
	"gopkg.in/yaml.v2"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflow(h *common.SampleHelper, w Workflow) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "dsl_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}
	h.StartWorkflow(workflowOptions, simpleDSLWorkflow, w)
}

func main() {
	var mode, dslConfig string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger.")
	flag.StringVar(&dslConfig, "dslConfig", "cmd/samples/dsl/workflow1.yaml", "dslConfig specify the yaml file for the dsl workflow.")
	flag.Parse()

	var h common.SampleHelper
	h.SetupServiceConfig()

	switch mode {
	case "worker":
		h.RegisterWorkflow(simpleDSLWorkflow)
		h.RegisterActivity(sampleActivity1)
		h.RegisterActivity(sampleActivity2)
		h.RegisterActivity(sampleActivity3)
		h.RegisterActivity(sampleActivity4)
		h.RegisterActivity(sampleActivity5)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":

		data, err := ioutil.ReadFile(dslConfig)
		if err != nil {
			panic(fmt.Sprintf("failed to load dsl config file %v", err))
		}
		var workflow Workflow
		if err := yaml.Unmarshal(data, &workflow); err != nil {
			panic(fmt.Sprintf("failed to unmarshal dsl config %v", err))
		}
		startWorkflow(&h, workflow)
	}
}


================================================
FILE: cmd/samples/dsl/workflow.go
================================================
package main

import (
	"time"

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

// ApplicationName is the task list for this sample
const ApplicationName = "dslGroup"

type (
	// Workflow is the type used to express the workflow definition. Variables are a map of valuables. Variables can be
	// used as input to Activity.
	Workflow struct {
		Variables map[string]string
		Root      Statement
	}

	// Statement is the building block of dsl workflow. A Statement can be a simple ActivityInvocation or it
	// could be a Sequence or Parallel.
	Statement struct {
		Activity *ActivityInvocation
		Sequence *Sequence
		Parallel *Parallel
	}

	// Sequence consist of a collection of Statements that runs in sequential.
	Sequence struct {
		Elements []*Statement
	}

	// Parallel can be a collection of Statements that runs in parallel.
	Parallel struct {
		Branches []*Statement
	}

	// ActivityInvocation is used to express invoking an Activity. The Arguments defined expected arguments as input to
	// the Activity, the result specify the name of variable that it will store the result as which can then be used as
	// arguments to subsequent ActivityInvocation.
	ActivityInvocation struct {
		Name      string
		Arguments []string
		Result    string
	}

	executable interface {
		execute(ctx workflow.Context, bindings map[string]string) error
	}
)

// simpleDSLWorkflow workflow decider
func simpleDSLWorkflow(ctx workflow.Context, dslWorkflow Workflow) ([]byte, error) {
	bindings := make(map[string]string)
	for k, v := range dslWorkflow.Variables {
		bindings[k] = v
	}

	ao := workflow.ActivityOptions{
		ScheduleToStartTimeout: time.Minute,
		StartToCloseTimeout:    time.Minute,
		HeartbeatTimeout:       time.Second * 20,
	}
	ctx = workflow.WithActivityOptions(ctx, ao)
	logger := workflow.GetLogger(ctx)

	err := dslWorkflow.Root.execute(ctx, bindings)
	if err != nil {
		logger.Error("DSL Workflow failed.", zap.Error(err))
		return nil, err
	}

	logger.Info("DSL Workflow completed.")
	return nil, err
}

func (b *Statement) execute(ctx workflow.Context, bindings map[string]string) error {
	if b.Parallel != nil {
		err := b.Parallel.execute(ctx, bindings)
		if err != nil {
			return err
		}
	}
	if b.Sequence != nil {
		err := b.Sequence.execute(ctx, bindings)
		if err != nil {
			return err
		}
	}
	if b.Activity != nil {
		err := b.Activity.execute(ctx, bindings)
		if err != nil {
			return err
		}
	}
	return nil
}

func (a ActivityInvocation) execute(ctx workflow.Context, bindings map[string]string) error {
	inputParam := makeInput(a.Arguments, bindings)
	var result string
	err := workflow.ExecuteActivity(ctx, a.Name, inputParam).Get(ctx, &result)
	if err != nil {
		return err
	}
	if a.Result != "" {
		bindings[a.Result] = result
	}
	return nil
}

func (s Sequence) execute(ctx workflow.Context, bindings map[string]string) error {
	for _, a := range s.Elements {
		err := a.execute(ctx, bindings)
		if err != nil {
			return err
		}
	}
	return nil
}

func (p Parallel) execute(ctx workflow.Context, bindings map[string]string) error {
	//
	// You can use the context passed in to activity as a way to cancel the activity like standard GO way.
	// Cancelling a parent context will cancel all the derived contexts as well.
	//

	// In the parallel block, we want to execute all of them in parallel and wait for all of them.
	// if one activity fails then we want to cancel all the rest of them as well.
	childCtx, cancelHandler := workflow.WithCancel(ctx)
	selector := workflow.NewSelector(ctx)
	var activityErr error
	for _, s := range p.Branches {
		f := executeAsync(s, childCtx, bindings)
		selector.AddFuture(f, func(f workflow.Future) {
			err := f.Get(ctx, nil)
			if err != nil {
				// cancel all pending activities
				cancelHandler()
				activityErr = err
			}
		})
	}

	for i := 0; i < len(p.Branches); i++ {
		selector.Select(ctx) // this will wait for one branch
		if activityErr != nil {
			return activityErr
		}
	}

	return nil
}

func executeAsync(exe executable, ctx workflow.Context, bindings map[string]string) workflow.Future {
	future, settable := workflow.NewFuture(ctx)
	workflow.Go(ctx, func(ctx workflow.Context) {
		err := exe.execute(ctx, bindings)
		settable.Set(nil, err)
	})
	return future
}

func makeInput(argNames []string, argsMap map[string]string) []string {
	var args []string
	for _, arg := range argNames {
		args = append(args, argsMap[arg])
	}
	return args
}


================================================
FILE: cmd/samples/dsl/workflow1.yaml
================================================
# This sample workflow execute 3 steps in sequence.
# 1) sampleActivity1, takes arg1 as input, and put result as result1.
# 2) sampleActivity2, takes result1 as input, and put result as result2.
# 3) sampleActivity3, takes args2 and result2 as input, and put result as result3.

variables:
  arg1: value1
  arg2: value2

root:
  sequence:
    elements:
     - activity:
        name: main.sampleActivity1
        arguments:
          - arg1
        result: result1
     - activity:
        name: main.sampleActivity2
        arguments:
          - result1
        result: result2
     - activity:
        name: main.sampleActivity3
        arguments:
          - arg2
          - result2
        result: result3


================================================
FILE: cmd/samples/dsl/workflow2.yaml
================================================
# This sample workflow execute 3 steps in sequence.
# 1) activity1, takes arg1 as input, and put result as result1.
# 2) it runs a parallel block which runs below sequence branches in parallel
#  2.1) sequence 1
#    2.1.1) activity2, takes result1 as input, and put result as result2
#    2.1.2) activity3, takes arg2 and result2 as input, and put result as result3
#  2.2) sequence 2
#    2.2.1) activity4, takes result1 as input, and put result as result4
#    2.2.2) activity5, takes arg3 and result4 as input, and put result as result5
# 3) activity1, takes result3 and result5 as input, and put result as result6.

variables:
  arg1: value1
  arg2: value2
  arg3: value3

root:
  sequence:
    elements:
      - activity:
         name: main.sampleActivity1
         arguments:
           - arg1
         result: result1
      - parallel:
          branches:
            - sequence:
                elements:
                 - activity:
                    name: main.sampleActivity2
                    arguments:
                      - result1
                    result: result2
                 - activity:
                    name: main.sampleActivity3
                    arguments:
                      - arg2
                      - result2
                    result: result3
            - sequence:
                elements:
                 - activity:
                    name: main.sampleActivity4
                    arguments:
                      - result1
                    result: result4
                 - activity:
                    name: main.sampleActivity5
                    arguments:
                      - arg3
                      - result4
                    result: result5
      - activity:
         name: main.sampleActivity1
         arguments:
           - result3
           - result5
         result: result6


================================================
FILE: cmd/samples/dsl/workflow_test.go
================================================
package main

import (
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/testsuite"
	"go.uber.org/cadence/workflow"
)

func TestActivitySequenceParallelStatements(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}

	tests := []struct {
		name     string
		fields   Statement
		bindings map[string]string
		wantErr  bool
	}{
		{
			name: "Test Activity Invocation",
			fields: Statement{
				Activity: &ActivityInvocation{
					Name:      "sampleActivity",
					Arguments: []string{"var1", "var2"},
					Result:    "resultVar",
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: false,
		},
		{
			name: "Test Sequence Execution",
			fields: Statement{
				Sequence: &Sequence{
					Elements: []*Statement{
						{
							Activity: &ActivityInvocation{
								Name:      "sampleActivity",
								Arguments: []string{"var1"},
								Result:    "resultVar1",
							},
						},
						{
							Activity: &ActivityInvocation{
								Name:      "sampleActivity",
								Arguments: []string{"var2"},
								Result:    "resultVar2",
							},
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: false,
		},
		{
			name: "Test Parallel Execution",
			fields: Statement{
				Parallel: &Parallel{
					Branches: []*Statement{
						{
							Activity: &ActivityInvocation{
								Name:      "sampleActivity",
								Arguments: []string{"var1"},
								Result:    "resultVar1",
							},
						},
						{
							Activity: &ActivityInvocation{
								Name:      "sampleActivity",
								Arguments: []string{"var2"},
								Result:    "resultVar2",
							},
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			env := testSuite.NewTestWorkflowEnvironment()
			env.RegisterActivityWithOptions(sampleActivity, activity.RegisterOptions{
				Name: "sampleActivity",
			})
			env.ExecuteWorkflow(func(ctx workflow.Context) error {
				ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
					ScheduleToStartTimeout: time.Minute,
					StartToCloseTimeout:    time.Minute,
				})
				return tt.fields.execute(ctx, tt.bindings)
			})

			require.True(t, env.IsWorkflowCompleted())
			if tt.wantErr {
				require.Error(t, env.GetWorkflowError())
			} else {
				require.NoError(t, env.GetWorkflowError())
			}
		})
	}
}

func TestSequenceFlow(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}

	tests := []struct {
		name     string
		fields   Sequence
		bindings map[string]string
		wantErr  bool
	}{
		{
			name: "Test Sequence Execution with Single Activity",
			fields: Sequence{
				Elements: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
			},
			wantErr: false,
		},
		{
			name: "Test Sequence Execution with Multiple Activities",
			fields: Sequence{
				Elements: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var2"},
							Result:    "resultVar2",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: false,
		},
		{
			name: "Test Sequence Execution with Error",
			fields: Sequence{
				Elements: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
					{
						Activity: &ActivityInvocation{
							Name:      "nonExistentActivity",
							Arguments: []string{"var2"},
							Result:    "resultVar2",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			env := testSuite.NewTestWorkflowEnvironment()
			env.RegisterActivityWithOptions(sampleActivity, activity.RegisterOptions{
				Name: "sampleActivity",
			})

			env.ExecuteWorkflow(func(ctx workflow.Context) error {
				ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
					ScheduleToStartTimeout: time.Minute,
					StartToCloseTimeout:    time.Minute,
				})
				return tt.fields.execute(ctx, tt.bindings)
			})

			require.True(t, env.IsWorkflowCompleted())
			if tt.wantErr {
				require.Error(t, env.GetWorkflowError())
			} else {
				require.NoError(t, env.GetWorkflowError())
			}
		})
	}
}

func TestParallelFlow(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}

	tests := []struct {
		name     string
		fields   Parallel
		bindings map[string]string
		wantErr  bool
	}{
		{
			name: "Test Parallel Execution with Single Activity",
			fields: Parallel{
				Branches: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
			},
			wantErr: false,
		},
		{
			name: "Test Parallel Execution with Multiple Activities",
			fields: Parallel{
				Branches: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var2"},
							Result:    "resultVar2",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: false,
		},
		{
			name: "Test Parallel Execution with Error",
			fields: Parallel{
				Branches: []*Statement{
					{
						Activity: &ActivityInvocation{
							Name:      "sampleActivity",
							Arguments: []string{"var1"},
							Result:    "resultVar1",
						},
					},
					{
						Activity: &ActivityInvocation{
							Name:      "nonExistentActivity",
							Arguments: []string{"var2"},
							Result:    "resultVar2",
						},
					},
				},
			},
			bindings: map[string]string{
				"var1": "value1",
				"var2": "value2",
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			env := testSuite.NewTestWorkflowEnvironment()
			env.RegisterActivityWithOptions(sampleActivity, activity.RegisterOptions{
				Name: "sampleActivity",
			})

			env.ExecuteWorkflow(func(ctx workflow.Context) error {
				ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
					ScheduleToStartTimeout: time.Minute,
					StartToCloseTimeout:    time.Minute,
				})
				return tt.fields.execute(ctx, tt.bindings)
			})

			require.True(t, env.IsWorkflowCompleted())
			if tt.wantErr {
				require.Error(t, env.GetWorkflowError())
			} else {
				require.NoError(t, env.GetWorkflowError())
			}
		})
	}
}

func TestActivityInvocationFlow(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}

	tests := []struct {
		name     string
		fields   ActivityInvocation
		bindings map[string]string
		wantErr  bool
	}{
		{
			name: "Test Activity Invocation Success",
			fields: ActivityInvocation{
				Name:      "sampleActivity",
				Arguments: []string{"var1"},
				Result:    "resultVar",
			},
			bindings: map[string]string{
				"var1": "value1",
			},
			wantErr: false,
		},
		{
			name: "Test Activity Invocation with Error",
			fields: ActivityInvocation{
				Name:      "nonExistentActivity",
				Arguments: []string{"var1"},
				Result:    "resultVar",
			},
			bindings: map[string]string{
				"var1": "value1",
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			env := testSuite.NewTestWorkflowEnvironment()
			env.RegisterActivityWithOptions(sampleActivity, activity.RegisterOptions{
				Name: "sampleActivity",
			})

			env.ExecuteWorkflow(func(ctx workflow.Context) error {
				ctx = workflow.WithActivityOptions(ctx, workflow.ActivityOptions{
					ScheduleToStartTimeout: time.Minute,
					StartToCloseTimeout:    time.Minute,
				})
				return tt.fields.execute(ctx, tt.bindings)
			})

			require.True(t, env.IsWorkflowCompleted())
			if tt.wantErr {
				require.Error(t, env.GetWorkflowError())
			} else {
				require.NoError(t, env.GetWorkflowError())
			}
		})
	}
}

func Test_SimpleDSLWorkflow(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}
	env := testSuite.NewTestWorkflowEnvironment()

	// Define a sample DSL workflow
	dslWorkflow := Workflow{
		Variables: map[string]string{
			"var1": "value1",
			"var2": "value2",
		},
		Root: Statement{
			Activity: &ActivityInvocation{
				Name:      "sampleActivity",
				Arguments: []string{"var1", "var2"},
				Result:    "resultVar",
			},
		},
	}

	// Register a sample activity
	env.RegisterActivityWithOptions(sampleActivity, activity.RegisterOptions{
		Name: "sampleActivity",
	})

	env.ExecuteWorkflow(simpleDSLWorkflow, dslWorkflow)

	require.True(t, env.IsWorkflowCompleted())
	require.NoError(t, env.GetWorkflowError())
}

func sampleActivity(input []string) (string, error) {
	name := "sampleActivity"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}


================================================
FILE: cmd/samples/expense/README.md
================================================
# Expense
This sample workflow process an expense request. The key part of this sample is to show how to complete an activity asynchronously.

# Sample Description
* Create a new expense report.
* Wait for the expense report to be approved. This could take an arbitrary amount of time. So the activity's Execute method has to return before it is actually approved. This is done by returning a special error so the framework knows the activity is not completed yet.
  * When the expense is approved (or rejected), somewhere in the world needs to be notified, and it will need to call WorkflowClient.CompleteActivity() to tell cadence service that that activity is now completed. In this sample case, the dummy server do this job. In real world, you will need to register some listener to the expense system or you will need to have your own pulling agent to check for the expense status periodic.
* After the wait activity is completed, it did the payment for the expense. (dummy step in this sample case)

This sample rely on an a dummy expense server to work.

# Steps To Run Sample
* You need a cadence service running. See https://github.com/cadence-workflow/cadence/blob/master/README.md for more details.
* Start the dummy server
```
./bin/expense_dummy
```
If dummy is not found, run make to build it.
* Start workflow and activity workers
```
./bin/expense -m worker
```
* Start expanse workflow execution
```
./bin/expense -m trigger
```
* When you see the console print out the expense is created, go to [localhost:8099/list](http://localhost:8099/list) to approve the expense.
* You should see the workflow complete after you approve the expense. You can also reject the expense.
* If you see the workflow failed, try to change to a different port number in dummy.go and workflow.go. Then rebuild everything.


================================================
FILE: cmd/samples/expense/activities.go
================================================
package main

import (
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"

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

func createExpenseActivity(ctx context.Context, expenseID string) error {
	if len(expenseID) == 0 {
		return errors.New("expense id is empty")
	}

	resp, err := http.Get(expenseServerHostPort + "/create?is_api_call=true&id=" + expenseID)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return err
	}

	if string(body) == "SUCCEED" {
		activity.GetLogger(ctx).Info("Expense created.", zap.String("ExpenseID", expenseID))
		return nil
	}

	return errors.New(string(body))
}

// waitForDecisionActivity waits for the expense decision. This activity will complete asynchronously. When this method
// returns error activity.ErrResultPending, the cadence client recognize this error, and won't mark this activity
// as failed or completed. The cadence server will wait until Client.CompleteActivity() is called or timeout happened
// whichever happen first. In this sample case, the CompleteActivity() method is called by our dummy expense server when
// the expense is approved.
func waitForDecisionActivity(ctx context.Context, expenseID string) (string, error) {
	if len(expenseID) == 0 {
		return "", errors.New("expense id is empty")
	}

	logger := activity.GetLogger(ctx)

	// save current activity info so it can be completed asynchronously when expense is approved/rejected
	activityInfo := activity.GetInfo(ctx)
	formData := url.Values{}
	formData.Add("task_token", string(activityInfo.TaskToken))

	registerCallbackURL := expenseServerHostPort + "/registerCallback?id=" + expenseID
	resp, err := http.PostForm(registerCallbackURL, formData)
	if err != nil {
		logger.Info("waitForDecisionActivity failed to register callback.", zap.Error(err))
		return "", err
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return "", err
	}

	status := string(body)
	if status == "SUCCEED" {
		// register callback succeed
		logger.Info("Successfully registered callback.", zap.String("ExpenseID", expenseID))

		// ErrActivityResultPending is returned from activity's execution to indicate the activity is not completed when it returns.
		// activity will be completed asynchronously when Client.CompleteActivity() is called.
		return "", activity.ErrResultPending
	}

	logger.Warn("Register callback failed.", zap.String("ExpenseStatus", status))
	return "", fmt.Errorf("register callback failed status:%s", status)
}

func paymentActivity(ctx context.Context, expenseID string) error {
	if len(expenseID) == 0 {
		return errors.New("expense id is empty")
	}

	resp, err := http.Get(expenseServerHostPort + "/action?is_api_call=true&type=payment&id=" + expenseID)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		return err
	}

	if string(body) == "SUCCEED" {
		activity.GetLogger(ctx).Info("paymentActivity succeed", zap.String("ExpenseID", expenseID))
		return nil
	}

	return errors.New(string(body))
}


================================================
FILE: cmd/samples/expense/main.go
================================================
package main

import (
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflow(h *common.SampleHelper, expenseID string) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "expense_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute * 12,
		DecisionTaskStartToCloseTimeout: time.Minute * 12,
	}
	h.StartWorkflow(workflowOptions, sampleExpenseWorkflow, expenseID)
}

func main() {
	var mode string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger.")
	flag.Parse()

	var h common.SampleHelper
	h.SetupServiceConfig()

	switch mode {
	case "worker":
		h.RegisterWorkflow(sampleExpenseWorkflow)
		h.RegisterActivity(createExpenseActivity)
		h.RegisterActivity(waitForDecisionActivity)
		h.RegisterActivity(paymentActivity)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":
		startWorkflow(&h, uuid.New())
	}
}


================================================
FILE: cmd/samples/expense/server/dummy.go
================================================
package main

import (
	"context"
	"fmt"
	"net/http"
	"sort"

	"go.uber.org/cadence/client"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

/**
 * Dummy server that support to list expenses, create new expense, update expense state and checking expense state.
 */

type expenseState string

const (
	created   expenseState = "CREATED"
	approved               = "APPROVED"
	rejected               = "REJECTED"
	completed              = "COMPLETED"
)

// use memory store for this dummy server
var allExpense = make(map[string]expenseState)

var tokenMap = make(map[string][]byte)

var workflowClient client.Client

func main() {
	var h common.SampleHelper
	h.SetupServiceConfig()
	var err error
	workflowClient, err = h.Builder.BuildCadenceClient()
	if err != nil {
		panic(err)
	}

	fmt.Println("Starting dummy server...")
	http.HandleFunc("/", listHandler)
	http.HandleFunc("/list", listHandler)
	http.HandleFunc("/create", createHandler)
	http.HandleFunc("/action", actionHandler)
	http.HandleFunc("/status", statusHandler)
	http.HandleFunc("/registerCallback", callbackHandler)
	http.ListenAndServe(":8099", nil)
}

func listHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "<h1>DUMMY EXPENSE SYSTEM</h1>"+"<a href=\"/list\">HOME</a>"+
		"<h3>All expense requests:</h3><table border=1><tr><th>Expense ID</th><th>Status</th><th>Action</th>")
	keys := []string{}
	for k := range allExpense {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, id := range keys {
		state := allExpense[id]
		actionLink := ""
		if state == created {
			actionLink = fmt.Sprintf("<a href=\"/action?type=approve&id=%s\">"+
				"<button style=\"background-color:#4CAF50;\">APPROVE</button></a>"+
				"&nbsp;&nbsp;<a href=\"/action?type=reject&id=%s\">"+
				"<button style=\"background-color:#f44336;\">REJECT</button></a>", id, id)
		}
		fmt.Fprintf(w, "<tr><td>%s</td><td>%s</td><td>%s</td></tr>", id, state, actionLink)
	}
	fmt.Fprint(w, "</table>")
}

func actionHandler(w http.ResponseWriter, r *http.Request) {
	isAPICall := r.URL.Query().Get("is_api_call") == "true"
	id := r.URL.Query().Get("id")
	oldState, ok := allExpense[id]
	if !ok {
		fmt.Fprint(w, "ERROR:INVALID_ID")
		return
	}
	actionType := r.URL.Query().Get("type")
	switch actionType {
	case "approve":
		allExpense[id] = approved
	case "reject":
		allExpense[id] = rejected
	case "payment":
		allExpense[id] = completed
	}
	if isAPICall {
		fmt.Fprint(w, "SUCCEED")
	} else {
		listHandler(w, r)
	}

	if oldState == created && (allExpense[id] == approved || allExpense[id] == rejected) {
		// report state change
		notifyExpenseStateChange(id, string(allExpense[id]))
	}

	fmt.Printf("Set state for %s from %s to %s.\n", id, oldState, allExpense[id])
	return
}

func createHandler(w http.ResponseWriter, r *http.Request) {
	isAPICall := r.URL.Query().Get("is_api_call") == "true"
	id := r.URL.Query().Get("id")
	_, ok := allExpense[id]
	if ok {
		fmt.Fprint(w, "ERROR:ID_ALREADY_EXISTS")
		return
	}

	allExpense[id] = created
	if isAPICall {
		fmt.Fprint(w, "SUCCEED")
	} else {
		listHandler(w, r)
	}
	fmt.Printf("Created new expense id:%s.\n", id)
	return
}

func statusHandler(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	state, ok := allExpense[id]
	if !ok {
		fmt.Fprint(w, "ERROR:INVALID_ID")
		return
	}

	fmt.Fprint(w, state)
	fmt.Printf("Checking status for %s: %s\n", id, state)
	return
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	currState, ok := allExpense[id]
	if !ok {
		fmt.Fprint(w, "ERROR:INVALID_ID")
		return
	}
	if currState != created {
		fmt.Fprint(w, "ERROR:INVALID_STATE")
		return
	}

	err := r.ParseForm()
	if err != nil {
		// Handle error here via logging and then return
		fmt.Fprint(w, "ERROR:INVALID_FORM_DATA")
		return
	}

	taskToken := r.PostFormValue("task_token")
	fmt.Printf("Registered callback for ID=%s, token=%s\n", id, taskToken)
	tokenMap[id] = []byte(taskToken)
	fmt.Fprint(w, "SUCCEED")
}

func notifyExpenseStateChange(id, state string) {
	token, ok := tokenMap[id]
	if !ok {
		fmt.Printf("Invalid id:%s\n", id)
		return
	}
	err := workflowClient.CompleteActivity(context.Background(), token, state, nil)
	if err != nil {
		fmt.Printf("Failed to complete activity with error: %+v\n", err)
	} else {
		fmt.Printf("Successfully complete activity: %s\n", token)
	}
}


================================================
FILE: cmd/samples/expense/workflow.go
================================================
package main

import (
	"time"

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

const (
	// ApplicationName is the task list for this sample
	ApplicationName = "expenseGroup"
)

var expenseServerHostPort = "http://localhost:8099"

// sampleExpenseWorkflow workflow decider
func sampleExpenseWorkflow(ctx workflow.Context, expenseID string) (result string, err error) {
	// step 1, create new expense report
	ao := workflow.ActivityOptions{
		ScheduleToStartTimeout: time.Minute,
		StartToCloseTimeout:    time.Minute,
		HeartbeatTimeout:       time.Second * 20,
	}
	ctx1 := workflow.WithActivityOptions(ctx, ao)
	logger := workflow.GetLogger(ctx)

	err = workflow.ExecuteActivity(ctx1, createExpenseActivity, expenseID).Get(ctx1, nil)
	if err != nil {
		logger.Error("Failed to create expense report", zap.Error(err))
		return "", err
	}

	// step 2, wait for the expense report to be approved (or rejected)
	ao = workflow.ActivityOptions{
		ScheduleToStartTimeout: time.Minute,
		StartToCloseTimeout:    4 * time.Minute,
	}
	ctx2 := workflow.WithActivityOptions(ctx, ao)
	// Notice that we set the timeout to be 4 minutes for this sample demo. If the expected time for the activity to
	// complete (waiting for human to approve the request) is longer, you should set the timeout accordingly so the
	// cadence system will wait accordingly. Otherwise, cadence system could mark the activity as failure by timeout.
	var status string
	err = workflow.ExecuteActivity(ctx2, waitForDecisionActivity, expenseID).Get(ctx2, &status)
	if err != nil {
		return "", err
	}

	if status != "APPROVED" {
		logger.Info("Workflow completed.", zap.String("ExpenseStatus", status))
		return "", nil
	}

	// step 3, request payment to the expense
	err = workflow.ExecuteActivity(ctx2, paymentActivity, expenseID).Get(ctx2, nil)
	if err != nil {
		logger.Info("Workflow completed with payment failed.", zap.Error(err))
		return "", err
	}

	logger.Info("Workflow completed with expense payment completed.")
	return "COMPLETED", nil
}


================================================
FILE: cmd/samples/expense/workflow_test.go
================================================
package main

import (
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/suite"
	"go.uber.org/cadence/testsuite"
)

type UnitTestSuite struct {
	suite.Suite
	testsuite.WorkflowTestSuite

	env *testsuite.TestWorkflowEnvironment
}

func TestUnitTestSuite(t *testing.T) {
	suite.Run(t, new(UnitTestSuite))
}

func (s *UnitTestSuite) SetupTest() {
	s.env = s.NewTestWorkflowEnvironment()
	s.env.RegisterWorkflow(sampleExpenseWorkflow)
	s.env.RegisterActivity(createExpenseActivity)
	s.env.RegisterActivity(waitForDecisionActivity)
	s.env.RegisterActivity(paymentActivity)
}

func (s *UnitTestSuite) TearDownTest() {
	s.env.AssertExpectations(s.T())
}

func (s *UnitTestSuite) Test_WorkflowWithMockActivities() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("APPROVED", nil).Once()
	s.env.OnActivity(paymentActivity, mock.Anything, mock.Anything).Return(nil).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.NoError(err)
	s.Equal("COMPLETED", workflowResult)
}

func (s *UnitTestSuite) Test_TimeoutWithMockActivities() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.SetWorkflowTimeout(time.Microsecond * 500)
	s.env.SetTestTimeout(time.Minute * 10)

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.Equal("TimeoutType: SCHEDULE_TO_CLOSE", err.Error())
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_WorkflowStatusRejected() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("REJECTED", nil).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.NoError(err)
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_WorkflowStatusCancelled() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("CANCELLED", nil).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.NoError(err)
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_WorkflowStatusApprovedWithPaymentError() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("APPROVED", nil).Once()
	s.env.OnActivity(paymentActivity, mock.Anything, mock.Anything).Return(errors.New("payment error")).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.Error(s.env.GetWorkflowError())
	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.Equal("payment error", err.Error())
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_CreateActivityFailed() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(errors.New("expense id is empty")).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "")

	s.True(s.env.IsWorkflowCompleted())
	s.Error(s.env.GetWorkflowError())
	var workflowResult string

	err := s.env.GetWorkflowResult(&workflowResult)
	s.Equal("expense id is empty", err.Error())
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_WaitForDecisionActivityFailed() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("", errors.New("failed to get decision")).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.Error(s.env.GetWorkflowError())
	var workflowResult string

	err := s.env.GetWorkflowResult(&workflowResult)
	s.Equal("failed to get decision", err.Error())
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_PaymentActivityFailed() {
	s.env.OnActivity(createExpenseActivity, mock.Anything, mock.Anything).Return(nil).Once()
	s.env.OnActivity(waitForDecisionActivity, mock.Anything, mock.Anything).Return("APPROVED", nil).Once()
	s.env.OnActivity(paymentActivity, mock.Anything, mock.Anything).Return(errors.New("payment failed")).Once()

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.Error(s.env.GetWorkflowError())
	var workflowResult string

	err := s.env.GetWorkflowResult(&workflowResult)
	s.Equal("payment failed", err.Error())
	s.Empty(workflowResult)
}

func (s *UnitTestSuite) Test_WorkflowWithMockServer() {
	// setup mock expense server
	handler := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/text")
		switch r.URL.Path {
		case "/create":
		case "/registerCallback":
			taskToken := []byte(r.PostFormValue("task_token"))
			// simulate the expense is approved one hour later.
			s.env.RegisterDelayedCallback(func() {
				s.env.CompleteActivity(taskToken, "APPROVED", nil)
			}, time.Hour)
		case "/action":
		}
		io.WriteString(w, "SUCCEED")
	}
	server := httptest.NewServer(http.HandlerFunc(handler))
	defer server.Close()

	// pointing server to test mock
	expenseServerHostPort = server.URL

	s.env.ExecuteWorkflow(sampleExpenseWorkflow, "test-expense-id")

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
	var workflowResult string
	err := s.env.GetWorkflowResult(&workflowResult)
	s.NoError(err)
	s.Equal("COMPLETED", workflowResult)
}


================================================
FILE: cmd/samples/fileprocessing/README.md
================================================
This sample workflow demos a file processing process. The key part is to show how to use the session API.

The workflow first starts an activity to download a requested resource file from web and store it locally on the host where it runs the download activity. Then, the workflow will start more activities to process the downloaded resource file. The key part is the following activities have to be run on the same host as the initial downloading activity. This is achieved by using the session API.

Steps for using Session API:
1) When starting worker, set `EnableSessionWorker` to true in workerOptions.
2) In the workflow code, create a new session using the `CreateSession()` API
```
  so := &workflow.SessionOptions{
    CreationTimeout:  time.Minute,
    ExecutionTimeout: time.Minute,
  }
  sessionCtx, err := workflow.CreateSession(ctx, so)
```
3) Use the returned `sessionCtx` or its child context to execute activities. These activities will be to scheduled on the same host.
4) After all activites are executed, call `CompleteSession()`.
```
  workflow.CompleteSession(sessionCtx)
```
5) Check the inline document in workflow/session.go of the go-client repo for more advanced usage.

Steps to run this sample:
1) You need a cadence service running. See details in cmd/samples/README.md
2) Run the following command multiple times on different console window. This is to simulate running workers on multiple different machines.
```
./bin/fileprocessing -m worker
```
3) Run the following command to submit a start request for this fileprocessing workflow.
```
./bin/fileprocessing -m trigger
```

You should see that all activities for one particular workflow execution are scheduled to run on one console window.


================================================
FILE: cmd/samples/fileprocessing/activities.go
================================================
package main

import (
	"context"
	"errors"
	"io/ioutil"
	"os"
	"strings"
	"time"

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

/**
 * Sample activities used by file processing sample workflow.
 */
const (
	downloadFileActivityName = "downloadFileActivity"
	processFileActivityName  = "processFileActivity"
	uploadFileActivityName   = "uploadFileActivity"
)

func downloadFileActivity(ctx context.Context, fileID string) (*fileInfo, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("Downloading file...", zap.String("FileID", fileID))
	data := downloadFile(fileID)

	tmpFile, err := saveToTmpFile(data)
	if err != nil {
		logger.Error("downloadFileActivity failed to save tmp file.", zap.Error(err))
		return nil, err
	}

	fileInfo := &fileInfo{FileName: tmpFile.Name(), HostID: HostID}
	logger.Info("downloadFileActivity succeed.", zap.String("SavedFilePath", fileInfo.FileName))
	return fileInfo, nil
}

func processFileActivity(ctx context.Context, fInfo fileInfo) (*fileInfo, error) {
	logger := activity.GetLogger(ctx).With(zap.String("HostID", HostID))
	logger.Info("processFileActivity started.", zap.String("FileName", fInfo.FileName))
	// assert that we are running on the same host as the file was downloaded
	// this check is not necessary, just to demo the host specific tasklist is working
	if fInfo.HostID != HostID {
		logger.Error("processFileActivity on wrong host",
			zap.String("TargetFile", fInfo.FileName),
			zap.String("TargetHostID", fInfo.HostID))
		return nil, errors.New("processFileActivity running on wrong host")
	}

	defer os.Remove(fInfo.FileName) // cleanup temp file

	// read downloaded file
	data, err := ioutil.ReadFile(fInfo.FileName)
	if err != nil {
		logger.Error("processFileActivity failed to read file.", zap.String("FileName", fInfo.FileName), zap.Error(err))
		return nil, err
	}

	// process the file
	transData := transcodeData(ctx, data)
	tmpFile, err := saveToTmpFile(transData)
	if err != nil {
		logger.Error("processFileActivity failed to save tmp file.", zap.Error(err))
		return nil, err
	}

	processedInfo := &fileInfo{FileName: tmpFile.Name(), HostID: HostID}
	logger.Info("processFileActivity succeed.", zap.String("SavedFilePath", processedInfo.FileName))
	return processedInfo, nil
}

func uploadFileActivity(ctx context.Context, fInfo fileInfo) error {
	logger := activity.GetLogger(ctx).With(zap.String("HostID", HostID))
	logger.Info("uploadFileActivity begin.", zap.String("UploadedFileName", fInfo.FileName))

	// assert that we are running on the same host as the file was downloaded
	// this check is not necessary, just to demo the host specific tasklist is working
	if fInfo.HostID != HostID {
		logger.Error("uploadFileActivity on wrong host",
			zap.String("TargetFile", fInfo.FileName),
			zap.String("TargetHostID", fInfo.HostID))
		return errors.New("uploadFileActivity running on wrong host")
	}

	defer os.Remove(fInfo.FileName) // clean up tmp file

	err := uploadFile(ctx, fInfo.FileName)
	if err != nil {
		logger.Error("uploadFileActivity uploading failed.", zap.Error(err))
		return err
	}
	logger.Info("uploadFileActivity succeed.", zap.String("UploadedFileName", fInfo.FileName))
	return nil
}

func downloadFile(fileID string) []byte {
	// dummy downloader
	dummyContent := "dummy content for fileID:" + fileID
	return []byte(dummyContent)
}

func uploadFile(ctx context.Context, filename string) error {
	// dummy uploader
	_, err := ioutil.ReadFile(filename)
	for i := 0; i < 5; i++ {
		time.Sleep(1 * time.Second)
		// Demonstrates that heartbeat accepts progress data.
		// In case of a heartbeat timeout it is included into the error.
		activity.RecordHeartbeat(ctx, i)
	}
	if err != nil {
		return err
	}
	return nil
}

func transcodeData(ctx context.Context, data []byte) []byte {
	// dummy file processor, just do upper case for the data.
	// in real world case, you would want to avoid load entire file content into memory at once.
	for i := 0; i < 5; i++ {
		time.Sleep(1 * time.Second)
		// Demonstrates that heartbeat accepts progress data.
		// In case of a heartbeat timeout it is included into the error.
		activity.RecordHeartbeat(ctx, i)
	}
	return []byte(strings.ToUpper(string(data)))
}

func saveToTmpFile(data []byte) (f *os.File, err error) {
	tmpFile, err := ioutil.TempFile("", "cadence_sample")
	if err != nil {
		return nil, err
	}
	_, err = tmpFile.Write(data)
	if err != nil {
		os.Remove(tmpFile.Name())
		return nil, err
	}

	return tmpFile, nil
}


================================================
FILE: cmd/samples/fileprocessing/main.go
================================================
package main

import (
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope:          h.WorkerMetricScope,
		Logger:                h.Logger,
		EnableLoggingInReplay: true,
		EnableSessionWorker:   true,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)

	// Host Specific activities processing case
	workerOptions.DisableWorkflowWorker = true
	h.StartWorkers(h.Config.DomainName, HostID, workerOptions)
}

func startWorkflow(h *common.SampleHelper, fileID string) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "fileprocessing_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}
	h.StartWorkflow(workflowOptions, sampleFileProcessingWorkflow, fileID)
}

func main() {
	var mode string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger.")
	flag.Parse()

	var h common.SampleHelper
	h.SetupServiceConfig()

	switch mode {
	case "worker":
		h.RegisterWorkflow(sampleFileProcessingWorkflow)
		h.RegisterActivityWithAlias(downloadFileActivity, downloadFileActivityName)
		h.RegisterActivityWithAlias(processFileActivity, processFileActivityName)
		h.RegisterActivityWithAlias(uploadFileActivity, uploadFileActivityName)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":
		startWorkflow(&h, uuid.New())
	}
}


================================================
FILE: cmd/samples/fileprocessing/workflow.go
================================================
package main

import (
	"time"

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

type (
	fileInfo struct {
		FileName string
		HostID   string
	}
)

// ApplicationName is the task list for this sample
const ApplicationName = "FileProcessorGroup"

// HostID - Use a new uuid just for demo so we can run 2 host specific activity workers on same machine.
// In real world case, you would use a hostname or ip address as HostID.
var HostID = ApplicationName + "_" + uuid.New()

//sampleFileProcessingWorkflow workflow decider
func sampleFileProcessingWorkflow(ctx workflow.Context, fileID string) (err error) {
	// step 1: download resource file
	ao := workflow.ActivityOptions{
		ScheduleToStartTimeout: time.Second * 5,
		StartToCloseTimeout:    time.Minute,
		HeartbeatTimeout:       time.Second * 2, // such a short timeout to make sample fail over very fast
		RetryPolicy: &cadence.RetryPolicy{
			InitialInterval:          time.Second,
			BackoffCoefficient:       2.0,
			MaximumInterval:          time.Minute,
			ExpirationInterval:       time.Minute * 10,
			NonRetriableErrorReasons: []string{"bad-error"},
		},
	}
	ctx = workflow.WithActivityOptions(ctx, ao)

	// Retry the whole sequence from the first activity on any error
	// to retry it on a different host. In a real application it might be reasonable to
	// retry individual activities and the whole sequence discriminating between different types of errors.
	// See the retryactivity sample for a more sophisticated retry implementation.
	for i := 1; i < 5; i++ {
		err = processFile(ctx, fileID)
		if err == nil {
			break
		}
	}
	if err != nil {
		workflow.GetLogger(ctx).Error("Workflow failed.", zap.String("Error", err.Error()))
	} else {
		workflow.GetLogger(ctx).Info("Workflow completed.")
	}
	return err
}

func processFile(ctx workflow.Context, fileID string) (err error) {
	var fInfo *fileInfo
	so := &workflow.SessionOptions{
		CreationTimeout:  time.Minute,
		ExecutionTimeout: time.Minute,
	}

	sessionCtx, err := workflow.CreateSession(ctx, so)
	if err != nil {
		return err
	}
	defer workflow.CompleteSession(sessionCtx)

	err = workflow.ExecuteActivity(sessionCtx, downloadFileActivityName, fileID).Get(sessionCtx, &fInfo)
	if err != nil {
		return err
	}

	var fInfoProcessed *fileInfo
	err = workflow.ExecuteActivity(sessionCtx, processFileActivityName, *fInfo).Get(sessionCtx, &fInfoProcessed)
	if err != nil {
		return err
	}

	err = workflow.ExecuteActivity(sessionCtx, uploadFileActivityName, *fInfoProcessed).Get(sessionCtx, nil)
	return err
}


================================================
FILE: cmd/samples/fileprocessing/workflow_test.go
================================================
package main

import (
	"context"
	"strings"
	"testing"

	"github.com/stretchr/testify/suite"
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/testsuite"
)

type UnitTestSuite struct {
	suite.Suite
	testsuite.WorkflowTestSuite

	env *testsuite.TestWorkflowEnvironment
}

func TestUnitTestSuite(t *testing.T) {
	suite.Run(t, new(UnitTestSuite))
}

func (s *UnitTestSuite) SetupTest() {
	s.env = s.NewTestWorkflowEnvironment()
	s.env.RegisterWorkflow(sampleFileProcessingWorkflow)
	s.env.RegisterActivityWithOptions(downloadFileActivity, activity.RegisterOptions{
		Name: downloadFileActivityName,
	})
	s.env.RegisterActivityWithOptions(processFileActivity, activity.RegisterOptions{
		Name: processFileActivityName,
	})
	s.env.RegisterActivityWithOptions(uploadFileActivity, activity.RegisterOptions{
		Name: uploadFileActivityName,
	})
}

func (s *UnitTestSuite) TearDownTest() {
	s.env.AssertExpectations(s.T())
}

func (s *UnitTestSuite) Test_SampleFileProcessingWorkflow() {
	fileID := "test-file-id"
	expectedCall := []string{
		"downloadFileActivity",
		"processFileActivity",
		"uploadFileActivity",
	}

	var activityCalled []string
	s.env.SetOnActivityStartedListener(func(activityInfo *activity.Info, ctx context.Context, args encoded.Values) {
		activityType := activityInfo.ActivityType.Name
		if strings.HasPrefix(activityType, "internalSession") {
			return
		}
		activityCalled = append(activityCalled, activityType)
		switch activityType {
		case expectedCall[0]:
			var input string
			s.NoError(args.Get(&input))
			s.Equal(fileID, input)
		case expectedCall[1]:
			var input fileInfo
			s.NoError(args.Get(&input))
			s.Equal(input.HostID, HostID)
		case expectedCall[2]:
			var input fileInfo
			s.NoError(args.Get(&input))
			s.Equal(input.HostID, HostID)
		default:
			panic("unexpected activity call")
		}
	})
	s.env.ExecuteWorkflow(sampleFileProcessingWorkflow, fileID)

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
	s.Equal(expectedCall, activityCalled)
}


================================================
FILE: cmd/samples/pso/README.md
================================================
This sample workflow demos a long iterative math optimization process using particle swarm optimization (PSO). 

The workflow first does some data structure initialization and then runs many iterations using a child workflow. The child workflow runs 10 iterations and then uses ContinueAsNew to avoid to store too long history in the Cadence database. In case of recovery the whole history has to be replayed to reconstruct the workflow state. So if history is too large the recover can take very long time.
Each particle is processed in parallel using worflow.Go and the math grunt work is done in the activites.
Since the data structure that maintains the optimization state has to be passed to the child workflow and the activities, a custom DataConverter has been implemented to take care of serialization/deserialization.
Also the query API is supported to get the current state of running workflow.

Steps to run this sample: 
1) You need a cadence service running. See details in cmd/samples/README.md
2) Run the following command multiple times on different console window. This is to simulate running workers on multiple different machines.
```
./bin/pso -m worker
```
3) Run the following command to submit a start request for this PSO workflow.
```
./bin/pso -m trigger
```
4) Query the state with
```
./bin/pso -m query -w <workflow_id from step 3> -r <run_id from step 3> -t state
```
Replace -t state with -t \_\_stack_trace to dump the call stack for the workflow.

You should see that all activities for one particular workflow execution are scheduled to run on one console window.


================================================
FILE: cmd/samples/pso/activities.go
================================================
package main

import (
	"context"
	"math/rand"
	"time"

	"go.uber.org/cadence/activity"
)

/**
 * Sample activities used by file processing sample workflow.
 */
const (
	initParticleActivityName   = "initParticleActivityName"
	updateParticleActivityName = "updateParticleActivityName"
)

var rng *rand.Rand

// This is registration process where you register all your activity handlers.
func init() {
	// initialize the RNG
	// WARNING: the randomness of activity scheduling with multiple workers makes random number generation truly random and not repeatable in debugging
	// worker.ReplayWorkflowHistoryFromJSONFile should be used to troubleshoot a specific workflow failure.
	rng = rand.New(rand.NewSource(time.Now().UnixNano()))
}

func initParticleActivity(ctx context.Context, swarm Swarm) (Particle, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("initParticleActivity started.")

	particle := NewParticle(&swarm, rng)
	particle.UpdateFitness(&swarm)

	return *particle, nil
}

func updateParticleActivity(ctx context.Context, swarm Swarm, particleIdx int) (Particle, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("updateParticleActivity started.")

	particle := swarm.Particles[particleIdx]
	particle.UpdateLocation(&swarm, rng)
	particle.UpdateFitness(&swarm)

	return *particle, nil
}


================================================
FILE: cmd/samples/pso/dataconverter.go
================================================
package main

import (
	"bytes"
	"encoding/gob"
	"encoding/json"
	"fmt"
	"reflect"

	"go.uber.org/cadence/encoded"
)

// gobDataConverter implements encoded.DataConverter using gob for Swarm and Particle
// WARGNING: Make sure all struct members are public (Capital letter) otherwise serialization does not work!
// TODO: consider storing blobs in external DB or S3
type gobDataConverter struct {
}

// NewGobDataConverter creates a gob data converter
func NewGobDataConverter() encoded.DataConverter {
	return &gobDataConverter{}
}

// jsonDataConverter implements encoded.DataConverter using JSON for Swarm and Particle
// WARGNING: Make sure all struct members are public (Capital letter) otherwise serialization does not work!
// TODO: consider storing blobs in external DB or S3
type jsonDataConverter struct {
}

// NewJSONDataConverter creates a json data converter
func NewJSONDataConverter() encoded.DataConverter {
	return &jsonDataConverter{}
}

// Gob data converter implementation

func (dc *gobDataConverter) ToData(value ...interface{}) ([]byte, error) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	var err error
	for i, obj := range value {
		switch t := obj.(type) {
		case Swarm:
			err = enc.Encode(*t.Settings)
			if err == nil {
				err = enc.Encode(*t.Gbest)
				if err == nil {
					if t.Settings.Size > 0 {
						for _, particle := range t.Particles {
							if particle == nil {
								particle = new(Particle)
							}
							err = enc.Encode(*particle)
						}
					}
				}
			}
		default:
			err = enc.Encode(obj)
		}
		if err != nil {
			return nil, fmt.Errorf(
				"unable to encode argument: %d, %v, with gob error: %v", i, reflect.TypeOf(obj), err)
		}
	}
	return buf.Bytes(), nil
	// TODO: store buf.Bytes() in DB/S3 and get key
	// return key, nil
}

func (dc *gobDataConverter) FromData(input []byte, valuePtr ...interface{}) error {
	// TODO: convert input into key in DB/S3 and retrieve bytes
	//dec := gob.NewDecoder(bytes)
	dec := gob.NewDecoder(bytes.NewBuffer(input))
	var err error
	for i, obj := range valuePtr {
		switch t := obj.(type) {
		case *Swarm:
			t.Settings = new(SwarmSettings)
			err = dec.Decode(t.Settings)
			t.Settings.function = FunctionFactory(t.Settings.FunctionName)
			t.Gbest = NewPosition(t.Settings.function.dim)
			err = dec.Decode(t.Gbest)
			t.Particles = make([]*Particle, t.Settings.Size)
			for index := 0; index < t.Settings.Size; index++ {
				t.Particles[index] = new(Particle)
				err = dec.Decode(t.Particles[index])
			}
		default:
			err = dec.Decode(obj)
		}
		if err != nil {
			return fmt.Errorf(
				"unable to decode argument: %d, %v, with gob error: %v", i, reflect.TypeOf(obj), err)
		}
	}
	return nil
}

// Json data converter implementation

func (dc *jsonDataConverter) ToData(value ...interface{}) ([]byte, error) {
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	var err error
	for i, obj := range value {
		switch t := obj.(type) {
		case Swarm:
			err = enc.Encode(*t.Settings)
			if err == nil {
				err = enc.Encode(*t.Gbest)
				if err == nil {
					if t.Settings.Size > 0 {
						for _, particle := range t.Particles {
							if particle == nil {
								particle = new(Particle)
							}
							err = enc.Encode(*particle)
						}
					}
				}
			}
		case WorkflowResult:
			err = enc.Encode(t.Msg)
			err = enc.Encode(t.Success)
		default:
			err = enc.Encode(obj)
		}
		if err != nil {
			return nil, fmt.Errorf(
				"unable to encode argument: %d, %v, with error: %v", i, reflect.TypeOf(obj), err)
		}
	}
	return buf.Bytes(), nil
	// TODO: store buf.Bytes() in DB/S3 and get key
	// return key, nil
}

func (dc *jsonDataConverter) FromData(input []byte, valuePtr ...interface{}) error {
	// TODO: convert input into key in DB/S3 and retrieve bytes
	//dec := json.NewDecoder(bytes)
	dec := json.NewDecoder(bytes.NewBuffer(input))
	var err error
	for i, obj := range valuePtr {
		switch t := obj.(type) {
		case *Swarm:
			t.Settings = new(SwarmSettings)
			err = dec.Decode(t.Settings)
			t.Settings.function = FunctionFactory(t.Settings.FunctionName)
			t.Gbest = NewPosition(t.Settings.function.dim)
			err = dec.Decode(t.Gbest)
			t.Particles = make([]*Particle, t.Settings.Size)
			for index := 0; index < t.Settings.Size; index++ {
				t.Particles[index] = new(Particle)
				err = dec.Decode(t.Particles[index])
			}
		case *WorkflowResult:
			err = dec.Decode(&t.Msg)
			err = dec.Decode(&t.Success)
		default:
			err = dec.Decode(obj)
		}
		if err != nil {
			return fmt.Errorf(
				"unable to decode argument: %d, %v, with error: %v", i, reflect.TypeOf(obj), err)
		}
	}
	return nil
}


================================================
FILE: cmd/samples/pso/functions.go
================================================
package main

import "math"

type ObjectiveFunction struct {
	name     string                      // name of the function
	dim      int                         // problem dimensionality
	xLo      float64                     // lower range limit
	xHi      float64                     // higher range limit
	Goal     float64                     // optimization goal (error threshold)
	Evaluate func(vec []float64) float64 // the objective function
}

var Sphere = ObjectiveFunction{
	name:     "sphere",
	dim:      3,
	xLo:      -100,
	xHi:      100,
	Goal:     1e-5,
	Evaluate: EvalSphere,
}

var Rosenbrock = ObjectiveFunction{
	name:     "rosenbrock",
	dim:      3,
	xLo:      -2.048,
	xHi:      2.048,
	Goal:     1e-5,
	Evaluate: EvalRosenbrock,
}
var Griewank = ObjectiveFunction{
	name:     "griewank",
	dim:      3,
	xLo:      -600,
	xHi:      600,
	Goal:     1e-5,
	Evaluate: EvalGriewank,
}

func EvalSphere(vec []float64) float64 {
	var sum float64 = 0
	for i := 0; i < len(vec); i++ {
		sum += math.Pow(vec[i], 2.0)
	}
	return sum
}

func EvalRosenbrock(vec []float64) float64 {
	var sum float64 = 0
	for i := 0; i < len(vec)-1; i++ {
		sum += 100.0*
			math.Pow((vec[i+1]-math.Pow(vec[i], 2.0)), 2.0) +
			math.Pow((1-vec[i]), 2.0)
	}
	return sum
}

func EvalGriewank(vec []float64) float64 {
	var sum float64 = 0
	var prod float64 = 1

	for i := 0; i < len(vec); i++ {
		sum += math.Pow(vec[i], 2.0)
		prod *= math.Cos(vec[i] / math.Sqrt(float64(i+1)))
	}
	return sum/4000.0 - prod + 1.0
}


================================================
FILE: cmd/samples/pso/main.go
================================================
package main

import (
	"encoding/gob"
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope:                       h.WorkerMetricScope,
		Logger:                             h.Logger,
		MaxConcurrentActivityExecutionSize: 1, // Activities are supposed to be CPU intensive, so better limit the concurrency
		DataConverter:                      h.DataConverter,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflow(h *common.SampleHelper, functionName string) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "PSO_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute * 60,
		DecisionTaskStartToCloseTimeout: time.Second * 10, // Measure of responsiveness of the worker to various server signals apart from start workflow. Small means faster recovery in the case of worker failure
	}
	h.StartWorkflow(workflowOptions, samplePSOWorkflow, functionName)
}

func main() {
	var mode, functionName, workflowID, runID, queryType string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger")
	flag.StringVar(&functionName, "f", "sphere", "One of [sphere, rosenbrock, griewank]")
	flag.StringVar(&workflowID, "w", "", "WorkflowID")
	flag.StringVar(&runID, "r", "", "RunID")
	flag.StringVar(&queryType, "t", "__stack_trace", "Query type is one of [__stack_trace, child, iteration]")
	flag.Parse()

	// If Gob is used to serialize data, then need to register types into gob as well???
	// TOVERIFY: the test works even without type registation!
	const useGob = false
	var dataConverter encoded.DataConverter
	if useGob {
		dataConverter = NewGobDataConverter()
		gob.Register(Vector{})
		gob.Register(Position{})
		gob.Register(Particle{})
		gob.Register(ObjectiveFunction{})
		gob.Register(SwarmSettings{})
		gob.Register(Swarm{})
	} else {
		dataConverter = NewJSONDataConverter()
	}

	var h common.SampleHelper
	h.DataConverter = dataConverter
	h.SetupServiceConfig() // This configures DataConverter

	switch mode {
	case "worker":
		h.RegisterWorkflow(samplePSOWorkflow)
		h.RegisterWorkflow(samplePSOChildWorkflow)
		h.RegisterActivityWithAlias(initParticleActivity, initParticleActivityName)
		h.RegisterActivityWithAlias(updateParticleActivity, updateParticleActivityName)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":
		startWorkflow(&h, functionName)
	case "query":
		h.QueryWorkflow(workflowID, runID, queryType)
	}
}


================================================
FILE: cmd/samples/pso/particle.go
================================================
package main

import "math/rand"

type Particle struct {
	Position *Position
	Pbest    *Position
	Velocity Vector
}

func NewParticle(swarm *Swarm, rng *rand.Rand) *Particle {
	particle := new(Particle)
	particle.Position = RandomPosition(swarm.Settings.function, rng)

	particle.Pbest = particle.Position.Copy()
	particle.Pbest.Fitness = 1e20

	particle.Velocity = make([]float64, swarm.Settings.function.dim)
	xLo := swarm.Settings.function.xLo
	xHi := swarm.Settings.function.xHi
	for i := 0; i < swarm.Settings.function.dim; i++ {
		a := xLo + (xHi-xLo)*rng.Float64()
		b := xLo + (xHi-xLo)*rng.Float64()
		particle.Velocity[i] = (a - b) / 2.0
	}
	return particle
}

func (particle *Particle) UpdateLocation(swarm *Swarm, rng *rand.Rand) {
	for i := 0; i < swarm.Settings.function.dim; i++ {
		// calculate stochastic coefficients
		rho1 := swarm.Settings.C1 * rng.Float64()
		rho2 := swarm.Settings.C2 * rng.Float64()
		// update velocity
		particle.Velocity[i] =
			swarm.Settings.Inertia*particle.Velocity[i] +
				rho1*(particle.Pbest.Location[i]-particle.Position.Location[i]) +
				rho2*(swarm.Gbest.Location[i]-particle.Position.Location[i])

		particle.Position.Location[i] += particle.Velocity[i]
	}
}

func (particle *Particle) UpdateFitness(swarm *Swarm) {
	particle.Position.Fitness = swarm.Settings.function.Evaluate(particle.Position.Location)

	if particle.Position.IsBetterThan(particle.Pbest) {
		particle.Pbest = particle.Position.Copy()
	}
}


================================================
FILE: cmd/samples/pso/position.go
================================================
package main

import (
	"math/rand"
)

type Vector []float64

type Position struct {
	Location Vector
	Fitness  float64
}

func NewPosition(dim int) *Position {
	loc := make([]float64, dim)
	return &Position{
		Location: loc,
		// Fitness:  EvaluateFunction(settings.Function.Evaluate, loc),
	}
}

func RandomPosition(function ObjectiveFunction, rng *rand.Rand) *Position {
	pos := NewPosition(function.dim)
	xLo := function.xLo
	xHi := function.xHi
	for i := 0; i < len(pos.Location); i++ {
		pos.Location[i] = xLo + (xHi-xLo)*rng.Float64()
	}
	// pos.Fitness = EvaluateFunction(settings.Function.Evaluate, pos.Location)
	return pos
}

func (position *Position) Copy() *Position {
	newPosition := NewPosition(len(position.Location))
	copy(newPosition.Location, position.Location)
	newPosition.Fitness = position.Fitness
	return newPosition
}

func (position *Position) IsBetterThan(other *Position) bool {
	return position.Fitness < other.Fitness
}


================================================
FILE: cmd/samples/pso/settings.go
================================================
package main

const pso_max_size int = 100
const pso_inertia float64 = 0.7298 // default value of w (see clerc02)

type SwarmSettings struct {
	FunctionName string
	function     ObjectiveFunction // lower case to avoid data converter export
	// swarm size (number of particles)
	Size int
	// ... N steps (set to 0 for no output)
	PrintEvery int
	// Steps after issuing a ContinueAsNew, to reduce history size
	ContinueAsNewEvery int
	// maximum number of iterations
	Steps int
	// cognitive coefficient
	C1 float64
	// social coefficient
	C2 float64
	// max inertia weight value
	InertiaMax float64
	// min inertia weight value
	InertiaMin float64
	// whether to keep particle position within defined bounds (TRUE)
	// or apply periodic boundary conditions (FALSE)
	ClampPosition bool

	Inertia float64 // current inertia weight value
}

func FunctionFactory(functionName string) ObjectiveFunction {
	var function ObjectiveFunction
	switch functionName {
	case "sphere":
		function = Sphere
	case "rosenbrock":
		function = Rosenbrock
	case "griewank":
		function = Griewank
	}
	return function
}

func PSODefaultSettings(functionName string) *SwarmSettings {
	settings := new(SwarmSettings)

	settings.FunctionName = functionName
	settings.function = FunctionFactory(functionName)

	settings.Size = CalculateSwarmSize(settings.function.dim, pso_max_size)
	settings.PrintEvery = 10
	settings.ContinueAsNewEvery = 10
	settings.Steps = 100000
	settings.C1 = 1.496
	settings.C2 = 1.496
	settings.InertiaMax = pso_inertia
	settings.InertiaMin = 0.3
	settings.Inertia = settings.InertiaMax

	settings.ClampPosition = true

	return settings
}


================================================
FILE: cmd/samples/pso/swarm.go
================================================
package main

import (
	"errors"
	"fmt"
	"strconv"

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

type ParticleResult struct {
	Position
	Step int
}

type Swarm struct {
	Settings  *SwarmSettings
	Gbest     *Position
	Particles []*Particle
}

func NewSwarm(ctx workflow.Context, settings *SwarmSettings) (*Swarm, error) {
	var swarm Swarm
	// store settings
	swarm.Settings = settings
	// initialize gbest
	swarm.Gbest = NewPosition(swarm.Settings.function.dim)
	swarm.Gbest.Fitness = 1e20

	// initialize particles in parallel
	chunkResultChannel := workflow.NewChannel(ctx)
	swarm.Particles = make([]*Particle, settings.Size)
	for i := 0; i < swarm.Settings.Size; i++ {
		particleIdx := i
		workflow.Go(ctx, func(ctx workflow.Context) {
			var particle Particle
			err := workflow.ExecuteActivity(ctx, initParticleActivityName, swarm).Get(ctx, &particle)
			if err == nil {
				swarm.Particles[particleIdx] = &particle
			}
			chunkResultChannel.Send(ctx, err)
		})
	}

	// wait for all particles to be initialized
	for i := 0; i < swarm.Settings.Size; i++ {
		var v interface{}
		chunkResultChannel.Receive(ctx, &v)
		switch r := v.(type) {
		case error:
			if r != nil {
				return &swarm, r
			}
		}
	}

	swarm.updateBest()

	return &swarm, nil
}

func (swarm *Swarm) updateBest() {
	for i := 0; i < swarm.Settings.Size; i++ {
		if swarm.Particles[i].Pbest.IsBetterThan(swarm.Gbest) {
			swarm.Gbest = swarm.Particles[i].Pbest.Copy()
		}
	}
}

func (swarm *Swarm) Run(ctx workflow.Context, step int) (ParticleResult, error) {
	logger := workflow.GetLogger(ctx)

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

	// the algorithm goes here
	chunkResultChannel := workflow.NewChannel(ctx)
	for step <= swarm.Settings.Steps {
		logger.Info("Iteration ", zap.String("step", strconv.Itoa(step)))
		// Update particles in parallel
		for i := 0; i < swarm.Settings.Size; i++ {
			particleIdx := i
			workflow.Go(ctx, func(ctx workflow.Context) {
				var particle Particle
				err := workflow.ExecuteActivity(ctx, updateParticleActivityName, *swarm, particleIdx).Get(ctx, &particle)
				if err == nil {
					swarm.Particles[particleIdx] = &particle
				}
				chunkResultChannel.Send(ctx, err)
			})
		}

		// Wait for all particles to be updated
		for i := 0; i < swarm.Settings.Size; i++ {
			var v interface{}
			chunkResultChannel.Receive(ctx, &v)
			switch r := v.(type) {
			case error:
				if r != nil {
					return ParticleResult{
						Position: *swarm.Gbest,
						Step:     step,
					}, r
				}
			}
		}

		logger.Debug("Iteration Update Swarm Best", zap.String("step", strconv.Itoa(step)))

		swarm.updateBest()

		// Check if the goal has reached then stop early
		if swarm.Gbest.Fitness < swarm.Settings.function.Goal {
			logger.Debug("Iteration New Swarm Best", zap.String("step", strconv.Itoa(step)))
			return ParticleResult{
				Position: *swarm.Gbest,
				Step:     step,
			}, nil
		}

		iterationMessage = fmt.Sprintf("Step %d :: min err=%.5e\n", step, swarm.Gbest.Fitness)
		if step%swarm.Settings.PrintEvery == 0 {
			logger.Info(iterationMessage)
		}

		// Finished all iterations
		if step == swarm.Settings.Steps {
			break
		}

		// Not finished yet, just continue as new to reduce history size
		if step%swarm.Settings.ContinueAsNewEvery == 0 {
			return ParticleResult{
				Position: *swarm.Gbest,
				Step:     step,
			}, errors.New(ContinueAsNewStr)
		}

		step++
	}

	return ParticleResult{
		Position: *swarm.Gbest,
		Step:     step,
	}, nil
}


================================================
FILE: cmd/samples/pso/utils.go
================================================
package main

import (
	"math"
)

func CalculateSwarmSize(dim, max_size int) int {
	s := 10. + 2.*math.Sqrt(float64(dim))
	size := int(math.Floor(s + 0.5))
	if size > max_size {
		return max_size
	} else {
		return size
	}
}


================================================
FILE: cmd/samples/pso/workflow.go
================================================
package main

import (
	"errors"
	"fmt"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence"
	"go.uber.org/cadence/workflow"
)

type WorkflowResult struct {
	Msg     string // Uppercase the members otherwise serialization won't work!
	Success bool
}

// ApplicationName is the task list for this sample
const ApplicationName = "PSO"

// ActivityOptions can be reused
var ActivityOptions = workflow.ActivityOptions{
	ScheduleToStartTimeout: time.Second * 5,
	StartToCloseTimeout:    time.Minute * 10,
	HeartbeatTimeout:       time.Second * 2, // such a short timeout to make sample fail over very fast
	RetryPolicy: &cadence.RetryPolicy{
		InitialInterval:          time.Second,
		BackoffCoefficient:       2.0,
		MaximumInterval:          time.Minute,
		ExpirationInterval:       time.Minute * 10,
		MaximumAttempts:          5,
		NonRetriableErrorReasons: []string{"bad-error"},
	},
}

const ContinueAsNewStr = "CONTINUEASNEW"

//samplePSOWorkflow workflow decider
func samplePSOWorkflow(ctx workflow.Context, functionName string) (string, error) {
	logger := workflow.GetLogger(ctx)
	logger.Info(fmt.Sprintf("Optimizing function %s", functionName))

	// Set activity options
	ctx = workflow.WithActivityOptions(ctx, ActivityOptions)

	// Setup query handler for query type "child"
	var childWorkflowID string
	err := workflow.SetQueryHandler(ctx, "child", func(input []byte) (string, error) {
		return childWorkflowID, nil
	})
	if err != nil {
		msg := fmt.Sprintf("SetQueryHandler failed: " + err.Error())
		logger.Error(msg)
		return msg, err
	}

	// Retry with different random seed
	settings := PSODefaultSettings(functionName)
	const NumberOfAttempts = 5
	for i := 1; i < NumberOfAttempts; i++ {
		logger.Info(fmt.Sprintf("Attempt #%d", i))

		swarm, err := NewSwarm(ctx, settings)
		if err != nil {
			msg := fmt.Sprintf("Optimization failed. " + err.Error())
			logger.Error(msg)
			return msg, err
		}

		// Set child workflow options
		// Parent workflow can choose to specify it's own ID for child execution.  Make sure they are unique for each execution.
		cwo := workflow.ChildWorkflowOptions{
			WorkflowID:                   "PSO_Child_" + uuid.New(),
			ExecutionStartToCloseTimeout: time.Minute,
		}
		ctx = workflow.WithChildOptions(ctx, cwo)

		childWorkflowFuture := workflow.ExecuteChildWorkflow(ctx, samplePSOChildWorkflow, *swarm, 1)
		var childWE workflow.Execution
		childWorkflowFuture.GetChildWorkflowExecution().Get(ctx, &childWE)
		childWorkflowID = childWE.ID
		var result WorkflowResult
		err = childWorkflowFuture.Get(ctx, &result) // This blocking until the child workflow has finished
		if err != nil {
			msg := fmt.Sprintf("Parent execution received child execution failure. " + err.Error())
			logger.Error(msg)
			return msg, err
		}
		if result.Success {
			msg := fmt.Sprintf("Optimization was successful at attempt #%d. %s", i, result.Msg)
			logger.Info(msg)
			return msg, nil
		}
	}

	msg := fmt.Sprintf("Unable to reach goal after %d attempts", NumberOfAttempts)
	logger.Info(msg)
	return msg, nil
}

// samplePSOChildWorkflow workflow decider
// Returns true if the optimization has converged
func samplePSOChildWorkflow(ctx workflow.Context, swarm Swarm, startingStep int) (WorkflowResult, error) {
	logger := workflow.GetLogger(ctx)
	logger.Info("Child workflow execution started.")

	// Set activity options
	ctx = workflow.WithActivityOptions(ctx, ActivityOptions)

	// Run real optimization loop
	result, err := swarm.Run(ctx, startingStep)
	if err != nil {
		if err.Error() == ContinueAsNewStr {
			return WorkflowResult{"NewContinueAsNewError", false}, workflow.NewContinueAsNewError(ctx, samplePSOChildWorkflow, swarm, result.Step+1)
		}

		msg := fmt.Sprintf("Error in swarm loop: " + err.Error())
		logger.Error(msg)
		return WorkflowResult{msg, false}, errors.New("Error in swarm loop")
	}
	if result.Position.Fitness < swarm.Settings.function.Goal {
		msg := fmt.Sprintf("Yay! Goal was reached @ step %d (fitness=%.2e) :-)", result.Step, result.Position.Fitness)
		logger.Info(msg)
		return WorkflowResult{msg, true}, nil
	}

	msg := fmt.Sprintf("Goal was not reached after %d steps (fitness=%.2e) :-)", result.Step, result.Position.Fitness)
	logger.Info(msg)
	return WorkflowResult{msg, false}, nil
}


================================================
FILE: cmd/samples/pso/workflow_test.go
================================================
package main

import (
	"context"
	"testing"

	"github.com/stretchr/testify/require"
	"go.uber.org/cadence/activity"
	"go.uber.org/cadence/encoded"
	"go.uber.org/cadence/testsuite"
	"go.uber.org/cadence/worker"
	"go.uber.org/cadence/workflow"
)

func Test_Workflow(t *testing.T) {
	testSuite := &testsuite.WorkflowTestSuite{}
	env := testSuite.NewTestWorkflowEnvironment()
	env.RegisterWorkflow(samplePSOWorkflow)
	env.RegisterWorkflow(samplePSOChildWorkflow)
	env.RegisterActivityWithOptions(initParticleActivity, activity.RegisterOptions{
		Name: initParticleActivityName,
	})
	env.RegisterActivityWithOptions(updateParticleActivity, activity.RegisterOptions{
		Name: updateParticleActivityName,
	})

	var activityCalled []string

	//var dataConverter = NewGobDataConverter()
	var dataConverter = NewJSONDataConverter()
	workerOptions := worker.Options{
		DataConverter: dataConverter,
	}
	env.SetWorkerOptions(workerOptions)

	// env.SetWorkflowTimeout(time.Minute * 5)
	// env.SetTestTimeout(time.Minute * 5)

	env.SetOnActivityStartedListener(func(activityInfo *activity.Info, ctx context.Context, args encoded.Values) {
		activityType := activityInfo.ActivityType.Name
		activityCalled = append(activityCalled, activityType)
		switch activityType {
		case "initParticleActivityName":
		case "updateParticleActivityName":
		default:
			panic("unexpected activity call")
		}
	})

	var childWorkflowID string
	env.SetOnChildWorkflowStartedListener(func(workflowInfo *workflow.Info, ctx workflow.Context, args encoded.Values) {
		childWorkflowID = workflowInfo.WorkflowExecution.ID
	})

	env.ExecuteWorkflow(samplePSOWorkflow, "sphere")

	require.True(t, env.IsWorkflowCompleted())
	queryAndVerify(t, env, "child", childWorkflowID)
	//queryAndVerify(t, env, "iteration", "???")
	require.Equal(t, env.GetWorkflowError().Error(), "ContinueAsNew") // consider recreating a new test env on every iteration and calling execute workflow with the arguments from the previous iteration (contained in ContinueAsNewError)
}

func queryAndVerify(t *testing.T, env *testsuite.TestWorkflowEnvironment, query string, expectedState string) {
	result, err := env.QueryWorkflow(query)
	require.NoError(t, err)
	var state string
	err = result.Get(&state)
	require.NoError(t, err)
	require.Equal(t, expectedState, state)
}


================================================
FILE: cmd/samples/recipes/branch/branch_workflow.go
================================================
package main

import (
	"fmt"
	"time"

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

/**
 * This sample workflow executes multiple branches in parallel. The number of branches is controlled by passed in parameter.
 */

const (
	// ApplicationName is the task list for this sample
	ApplicationName = "branchGroup"

	totalBranches = 3
)

// sampleBranchWorkflow workflow decider
func sampleBranchWorkflow(ctx workflow.Context) error {
	var futures []workflow.Future
	// starts activities in parallel
	ao := workflow.ActivityOptions{
		ScheduleToStartTimeout: time.Minute,
		StartToCloseTimeout:    time.Minute,
		HeartbeatTimeout:       time.Second * 20,
	}
	ctx = workflow.WithActivityOptions(ctx, ao)

	for i := 1; i <= totalBranches; i++ {
		activityInput := fmt.Sprintf("branch %d of %d.", i, totalBranches)
		future := workflow.ExecuteActivity(ctx, sampleActivity, activityInput)
		futures = append(futures, future)
	}

	// wait until all futures are done
	for _, future := range futures {
		if err := future.Get(ctx, nil); err != nil {
			return err
		}
	}

	workflow.GetLogger(ctx).Info("Workflow completed.")

	return nil
}

func sampleActivity(input string) (string, error) {
	name := "sampleActivity"
	fmt.Printf("Run %s with input %v \n", name, input)
	return "Result_" + name, nil
}


================================================
FILE: cmd/samples/recipes/branch/main.go
================================================
package main

import (
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflowParallel(h *common.SampleHelper) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "parallel_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}
	h.StartWorkflow(workflowOptions, sampleParallelWorkflow)
}

func startWorkflowBranch(h *common.SampleHelper) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "branch_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}
	h.StartWorkflow(workflowOptions, sampleBranchWorkflow)
}

func main() {
	var mode, sampleCase string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker or trigger.")
	flag.StringVar(&sampleCase, "c", "", "Sample case to run.")
	flag.Parse()

	var h common.SampleHelper
	h.SetupServiceConfig()

	switch mode {
	case "worker":
		h.RegisterWorkflow(sampleBranchWorkflow)
		h.RegisterWorkflow(sampleParallelWorkflow)
		h.RegisterActivity(sampleActivity)
		startWorkers(&h)

		// The workers are supposed to be long running process that should not exit.
		// Use select{} to block indefinitely for samples, you can quit by CMD+C.
		select {}
	case "trigger":
		switch sampleCase {
		case "branch":
			startWorkflowBranch(&h)
		default:
			startWorkflowParallel(&h)
		}
	}
}


================================================
FILE: cmd/samples/recipes/branch/parallel_workflow.go
================================================
package main

import (
	"errors"
	"time"

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

/**
 * This sample workflow executes multiple branches in parallel using workflow.Go() method.
 */

// sampleParallelWorkflow workflow decider
func sampleParallelWorkflow(ctx workflow.Context) error {
	waitChannel := workflow.NewChannel(ctx)

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

	logger := workflow.GetLogger(ctx)
	workflow.Go(ctx, func(ctx workflow.Context) {
		err := workflow.ExecuteActivity(ctx, sampleActivity, "branch1.1").Get(ctx, nil)
		if err != nil {
			logger.Error("Activity failed", zap.Error(err))
			waitChannel.Send(ctx, err.Error())
			return
		}
		err = workflow.ExecuteActivity(ctx, sampleActivity, "branch1.2").Get(ctx, nil)
		if err != nil {
			logger.Error("Activity failed", zap.Error(err))
			waitChannel.Send(ctx, err.Error())
			return
		}
		waitChannel.Send(ctx, "")
	})

	workflow.Go(ctx, func(ctx workflow.Context) {
		err := workflow.ExecuteActivity(ctx, sampleActivity, "branch2").Get(ctx, nil)
		if err != nil {
			logger.Error("Activity failed", zap.Error(err))
			waitChannel.Send(ctx, err.Error())
			return
		}
		waitChannel.Send(ctx, "")
	})

	// wait for both of the coroutinue to complete.
	var errMsg string
	for i := 0; i != 2; i++ {
		waitChannel.Receive(ctx, &errMsg)
		if errMsg != "" {
			err := errors.New(errMsg)
			logger.Error("Coroutine failed", zap.Error(err))
			return err
		}
	}

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


================================================
FILE: cmd/samples/recipes/branch/workflow_test.go
================================================
package main

import (
	"testing"

	"github.com/stretchr/testify/suite"
	"go.uber.org/cadence/testsuite"
)

type UnitTestSuite struct {
	suite.Suite
	testsuite.WorkflowTestSuite

	env *testsuite.TestWorkflowEnvironment
}

func TestUnitTestSuite(t *testing.T) {
	suite.Run(t, new(UnitTestSuite))
}

func (s *UnitTestSuite) SetupTest() {
	s.env = s.NewTestWorkflowEnvironment()
	s.env.RegisterWorkflow(sampleBranchWorkflow)
	s.env.RegisterWorkflow(sampleParallelWorkflow)
	s.env.RegisterActivity(sampleActivity)
}

func (s *UnitTestSuite) TearDownTest() {
	s.env.AssertExpectations(s.T())
}

func (s *UnitTestSuite) Test_BranchWorkflow() {
	s.env.ExecuteWorkflow(sampleBranchWorkflow)

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
}

func (s *UnitTestSuite) Test_ParallelWorkflow() {
	s.env.ExecuteWorkflow(sampleParallelWorkflow)

	s.True(s.env.IsWorkflowCompleted())
	s.NoError(s.env.GetWorkflowError())
}


================================================
FILE: cmd/samples/recipes/cancelactivity/main.go
================================================
package main

import (
	"flag"
	"time"

	"github.com/pborman/uuid"
	"go.uber.org/cadence/client"
	"go.uber.org/cadence/worker"

	"github.com/uber-common/cadence-samples/cmd/samples/common"
)

// This needs to be done as part of a bootstrap step when the process starts.
// The workers are supposed to be long running.
func startWorkers(h *common.SampleHelper) {
	// Configure worker options.
	workerOptions := worker.Options{
		MetricsScope: h.WorkerMetricScope,
		Logger:       h.Logger,
	}
	h.StartWorkers(h.Config.DomainName, ApplicationName, workerOptions)
}

func startWorkflow(h *common.SampleHelper) {
	workflowOptions := client.StartWorkflowOptions{
		ID:                              "cancel_" + uuid.New(),
		TaskList:                        ApplicationName,
		ExecutionStartToCloseTimeout:    time.Minute * 30,
		DecisionTaskStartToCloseTimeout: time.Minute,
	}
	h.StartWorkflow(workflowOptions, sampleCancelWorkflow)
}

func cancelWorkflow(h *common.SampleHelper, wid string) {
	h.CancelWorkflow(wid)
}

func main() {
	var mode, wid string
	flag.StringVar(&mode, "m", "trigger", "Mode is worker, trigger or cancel.")
	flag.StringVar(&wid
Download .txt
gitextract__zd9l1h0/

├── .gitar/
│   └── rules/
│       └── pr-description-quality.md
├── .github/
│   ├── dco.yml
│   ├── pull_request_guidance.md
│   ├── pull_request_template.md
│   └── workflows/
│       ├── build.yml
│       └── semantic-pr.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── NOTICE
├── README.md
├── cmd/
│   └── samples/
│       ├── advanced/
│       │   └── autoscaling-monitoring/
│       │       ├── Makefile
│       │       ├── README.md
│       │       ├── activities.go
│       │       ├── config/
│       │       │   └── autoscaling.yaml
│       │       ├── config.go
│       │       ├── config_test.go
│       │       ├── main.go
│       │       ├── worker_config.go
│       │       └── workflow.go
│       ├── common/
│       │   ├── factory.go
│       │   ├── sample_helper.go
│       │   └── util.go
│       ├── cron/
│       │   ├── cron_workflow.go
│       │   ├── cron_workflow_test.go
│       │   └── main.go
│       ├── dsl/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── workflow.go
│       │   ├── workflow1.yaml
│       │   ├── workflow2.yaml
│       │   └── workflow_test.go
│       ├── expense/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── server/
│       │   │   └── dummy.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── fileprocessing/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── main.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── pso/
│       │   ├── README.md
│       │   ├── activities.go
│       │   ├── dataconverter.go
│       │   ├── functions.go
│       │   ├── main.go
│       │   ├── particle.go
│       │   ├── position.go
│       │   ├── settings.go
│       │   ├── swarm.go
│       │   ├── utils.go
│       │   ├── workflow.go
│       │   └── workflow_test.go
│       ├── recipes/
│       │   ├── branch/
│       │   │   ├── branch_workflow.go
│       │   │   ├── main.go
│       │   │   ├── parallel_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── cancelactivity/
│       │   │   ├── main.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── childworkflow/
│       │   │   ├── child_workflow.go
│       │   │   ├── main.go
│       │   │   └── parent_workflow.go
│       │   ├── choice/
│       │   │   ├── exclusive_choice_workflow.go
│       │   │   ├── main.go
│       │   │   ├── multi_choice_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── consistentquery/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   └── query_workflow.go
│       │   ├── crossdomain/
│       │   │   ├── main.go
│       │   │   └── wf.go
│       │   ├── ctxpropagation/
│       │   │   ├── README.md
│       │   │   ├── activities.go
│       │   │   ├── main.go
│       │   │   ├── propagator.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── delaystart/
│       │   │   ├── delaystart_workflow.go
│       │   │   ├── delaystart_workflow_test.go
│       │   │   └── main.go
│       │   ├── dynamic/
│       │   │   ├── dynamic_workflow.go
│       │   │   ├── main.go
│       │   │   └── workflow_test.go
│       │   ├── greetings/
│       │   │   ├── greetings.json
│       │   │   ├── greetings_workflow.go
│       │   │   ├── main.go
│       │   │   ├── replay_test.go
│       │   │   ├── shadow_test.go
│       │   │   └── workflow_test.go
│       │   ├── helloworld/
│       │   │   ├── activity_logger_test.go
│       │   │   ├── helloworld.json
│       │   │   ├── helloworld_workflow.go
│       │   │   ├── helloworld_workflow_test.go
│       │   │   ├── main.go
│       │   │   ├── replay_test.go
│       │   │   └── shadow_test.go
│       │   ├── localactivity/
│       │   │   ├── README.md
│       │   │   ├── local_activity_workflow.go
│       │   │   ├── local_activity_workflow_test.go
│       │   │   └── main.go
│       │   ├── mutex/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── mutex_workflow.go
│       │   │   └── mutex_workflow_test.go
│       │   ├── pickfirst/
│       │   │   ├── main.go
│       │   │   ├── pickfirst_workflow.go
│       │   │   └── pickfirst_workflow_test.go
│       │   ├── query/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── query_workflow.go
│       │   │   └── query_workflow_test.go
│       │   ├── retryactivity/
│       │   │   ├── main.go
│       │   │   ├── retry_activity_workflow.go
│       │   │   └── retry_activity_workflow_test.go
│       │   ├── searchattributes/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── searchattributes_workflow.go
│       │   │   └── searchattributes_workflow_test.go
│       │   ├── sideeffect/
│       │   │   └── sideeffect_workflow.go
│       │   ├── signalcounter/
│       │   │   ├── main.go
│       │   │   ├── signal_counter_workflow.go
│       │   │   └── workflow_test.go
│       │   ├── sleep/
│       │   │   ├── README.md
│       │   │   ├── main.go
│       │   │   ├── sleep_workflow.go
│       │   │   └── sleep_workflow_test.go
│       │   ├── splitmerge/
│       │   │   ├── main.go
│       │   │   ├── splitmerge_workflow.go
│       │   │   └── splitmerge_workflow_test.go
│       │   ├── timer/
│       │   │   ├── main.go
│       │   │   ├── workflow.go
│       │   │   └── workflow_test.go
│       │   ├── tracing/
│       │   │   ├── helloworld_workflow.go
│       │   │   └── main.go
│       │   └── versioning/
│       │       ├── README.md
│       │       ├── main.go
│       │       └── versioned_workflow.go
│       └── recovery/
│           ├── README.md
│           ├── cache/
│           │   ├── cache.go
│           │   └── lru.go
│           ├── main.go
│           ├── recovery_workflow.go
│           └── trip_workflow.go
├── config/
│   └── development.yaml
├── go.mod
├── go.sum
├── k8s/
│   ├── README.md
│   ├── cadence-samples-pod.yaml
│   └── docker/
│       └── Dockerfile
├── new_samples/
│   ├── README.md
│   ├── activities/
│   │   ├── README.md
│   │   ├── dynamic_workflow.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── parallel_pick_first_workflow.go
│   │   └── worker.go
│   ├── client_tls/
│   │   ├── README.md
│   │   ├── cadence_client.go
│   │   ├── main.go
│   │   └── tls_config.go
│   ├── concurrency/
│   │   ├── README.md
│   │   ├── batch_workflow.go
│   │   ├── batch_workflow_test.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   └── worker.go
│   ├── data/
│   │   ├── README.md
│   │   ├── compressed_dataconverter_workflow.go
│   │   ├── compressed_dataconverter_workflow_test.go
│   │   ├── encrypted_dataconverter_workflow.go
│   │   ├── encrypted_dataconverter_workflow_test.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── s3_dataconverter_workflow.go
│   │   ├── s3_dataconverter_workflow_test.go
│   │   └── worker.go
│   ├── hello_world/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── worker.go
│   │   └── workflow.go
│   ├── operations/
│   │   ├── README.md
│   │   ├── cancel_workflow.go
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   └── worker.go
│   ├── query/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── lunch_vote_workflow.go
│   │   ├── main.go
│   │   ├── markdown_query.go
│   │   ├── order_fulfillment_workflow.go
│   │   └── worker.go
│   ├── signal/
│   │   ├── README.md
│   │   ├── generator/
│   │   │   ├── README.md
│   │   │   ├── README_specific.md
│   │   │   └── generate.go
│   │   ├── main.go
│   │   ├── simple_signal_workflow.go
│   │   └── worker.go
│   └── template/
│       ├── README.tmpl
│       ├── README_generator.tmpl
│       ├── README_references.tmpl
│       ├── generator.go
│       ├── main.tmpl
│       └── worker.tmpl
└── python_sdk_samples/
    ├── .python-version
    ├── README.md
    ├── __init__.py
    ├── openai_samples/
    │   ├── __init__.py
    │   └── agent_handoffs/
    │       ├── README.md
    │       ├── __init__.py
    │       ├── book_trip_agent.py
    │       ├── main.py
    │       └── tools.py
    └── pyproject.toml
Download .txt
SYMBOL INDEX (812 symbols across 160 files)

FILE: cmd/samples/advanced/autoscaling-monitoring/activities.go
  constant loadGenerationActivityName (line 13) | loadGenerationActivityName = "loadGenerationActivity"
  function LoadGenerationActivity (line 18) | func LoadGenerationActivity(ctx context.Context, taskID int, minProcessi...

FILE: cmd/samples/advanced/autoscaling-monitoring/config.go
  type AutoscalingConfiguration (line 13) | type AutoscalingConfiguration struct
    method applyDefaults (line 117) | func (c *AutoscalingConfiguration) applyDefaults() {
    method ToCommonConfiguration (line 167) | func (c *AutoscalingConfiguration) ToCommonConfiguration() common.Conf...
  type AutoscalingSettings (line 25) | type AutoscalingSettings struct
  type LoadGenerationSettings (line 36) | type LoadGenerationSettings struct
  constant DefaultDomainName (line 50) | DefaultDomainName      = "default"
  constant DefaultServiceName (line 51) | DefaultServiceName     = "cadence-frontend"
  constant DefaultHostNameAndPort (line 52) | DefaultHostNameAndPort = "localhost:7833"
  constant DefaultPrometheusAddr (line 53) | DefaultPrometheusAddr  = "127.0.0.1:8004"
  constant DefaultPollerMinCount (line 55) | DefaultPollerMinCount  = 2
  constant DefaultPollerMaxCount (line 56) | DefaultPollerMaxCount  = 8
  constant DefaultPollerInitCount (line 57) | DefaultPollerInitCount = 4
  constant DefaultWorkflows (line 59) | DefaultWorkflows             = 10
  constant DefaultWorkflowDelay (line 60) | DefaultWorkflowDelay         = 1000
  constant DefaultActivitiesPerWorkflow (line 61) | DefaultActivitiesPerWorkflow = 30
  constant DefaultBatchDelay (line 62) | DefaultBatchDelay            = 2000
  constant DefaultMinProcessingTime (line 63) | DefaultMinProcessingTime     = 1000
  constant DefaultMaxProcessingTime (line 64) | DefaultMaxProcessingTime     = 6000
  function DefaultAutoscalingConfiguration (line 68) | func DefaultAutoscalingConfiguration() AutoscalingConfiguration {
  function loadConfiguration (line 93) | func loadConfiguration(configFile string) AutoscalingConfiguration {

FILE: cmd/samples/advanced/autoscaling-monitoring/config_test.go
  function TestLoadConfiguration_SuccessfulLoading (line 12) | func TestLoadConfiguration_SuccessfulLoading(t *testing.T) {
  function TestLoadConfiguration_MissingFileFallback (line 62) | func TestLoadConfiguration_MissingFileFallback(t *testing.T) {
  function TestDefaultAutoscalingConfiguration (line 81) | func TestDefaultAutoscalingConfiguration(t *testing.T) {
  function TestApplyDefaults (line 101) | func TestApplyDefaults(t *testing.T) {

FILE: cmd/samples/advanced/autoscaling-monitoring/main.go
  constant ApplicationName (line 21) | ApplicationName = "autoscaling-monitoring"
  function findConfigFile (line 25) | func findConfigFile() string {
  function main (line 47) | func main() {
  function startWorkers (line 140) | func startWorkers(h *common.SampleHelper, config *AutoscalingConfigurati...
  function startWorkflow (line 144) | func startWorkflow(h *common.SampleHelper, config *AutoscalingConfigurat...

FILE: cmd/samples/advanced/autoscaling-monitoring/worker_config.go
  function startWorkersWithAutoscaling (line 14) | func startWorkersWithAutoscaling(h *common.SampleHelper, config *Autosca...
  function registerWorkflowAndActivityForAutoscaling (line 53) | func registerWorkflowAndActivityForAutoscaling(w worker.Worker) {

FILE: cmd/samples/advanced/autoscaling-monitoring/workflow.go
  constant autoscalingWorkflowName (line 11) | autoscalingWorkflowName = "autoscalingWorkflow"
  function AutoscalingWorkflow (line 16) | func AutoscalingWorkflow(ctx workflow.Context, activitiesPerWorkflow int...

FILE: cmd/samples/common/factory.go
  constant _cadenceClientName (line 20) | _cadenceClientName      = "cadence-client"
  constant _cadenceFrontendService (line 21) | _cadenceFrontendService = "cadence-frontend"
  type WorkflowClientBuilder (line 25) | type WorkflowClientBuilder struct
    method SetHostPort (line 45) | func (b *WorkflowClientBuilder) SetHostPort(hostport string) *Workflow...
    method SetDomain (line 51) | func (b *WorkflowClientBuilder) SetDomain(domain string) *WorkflowClie...
    method SetClientIdentity (line 57) | func (b *WorkflowClientBuilder) SetClientIdentity(identity string) *Wo...
    method SetMetricsScope (line 63) | func (b *WorkflowClientBuilder) SetMetricsScope(metricsScope tally.Sco...
    method SetDispatcher (line 69) | func (b *WorkflowClientBuilder) SetDispatcher(dispatcher *yarpc.Dispat...
    method SetContextPropagators (line 75) | func (b *WorkflowClientBuilder) SetContextPropagators(ctxProps []workf...
    method SetDataConverter (line 81) | func (b *WorkflowClientBuilder) SetDataConverter(dataConverter encoded...
    method SetTracer (line 87) | func (b *WorkflowClientBuilder) SetTracer(tracer opentracing.Tracer) *...
    method BuildCadenceClient (line 93) | func (b *WorkflowClientBuilder) BuildCadenceClient() (client.Client, e...
    method BuildCadenceDomainClient (line 115) | func (b *WorkflowClientBuilder) BuildCadenceDomainClient() (client.Dom...
    method BuildServiceClient (line 135) | func (b *WorkflowClientBuilder) BuildServiceClient() (workflowservicec...
    method build (line 153) | func (b *WorkflowClientBuilder) build() error {
  function NewBuilder (line 38) | func NewBuilder(logger *zap.Logger) *WorkflowClientBuilder {

FILE: cmd/samples/common/sample_helper.go
  constant defaultConfigFile (line 26) | defaultConfigFile = "config/development.yaml"
  type SampleHelper (line 31) | type SampleHelper struct
    method SetConfigFile (line 82) | func (h *SampleHelper) SetConfigFile(configFile string) {
    method SetupServiceConfig (line 87) | func (h *SampleHelper) SetupServiceConfig() {
    method StartWorkflow (line 172) | func (h *SampleHelper) StartWorkflow(
    method StartWorkflowWithCtx (line 181) | func (h *SampleHelper) StartWorkflowWithCtx(
    method SignalWithStartWorkflowWithCtx (line 204) | func (h *SampleHelper) SignalWithStartWorkflowWithCtx(ctx context.Cont...
    method RegisterWorkflow (line 223) | func (h *SampleHelper) RegisterWorkflow(workflow interface{}) {
    method RegisterWorkflowWithAlias (line 227) | func (h *SampleHelper) RegisterWorkflowWithAlias(workflow interface{},...
    method RegisterActivity (line 235) | func (h *SampleHelper) RegisterActivity(activity interface{}) {
    method RegisterActivityWithAlias (line 239) | func (h *SampleHelper) RegisterActivityWithAlias(activity interface{},...
    method StartWorkers (line 248) | func (h *SampleHelper) StartWorkers(domainName string, groupName strin...
    method QueryWorkflow (line 261) | func (h *SampleHelper) QueryWorkflow(workflowID, runID, queryType stri...
    method ConsistentQueryWorkflow (line 280) | func (h *SampleHelper) ConsistentQueryWorkflow(
    method SignalWorkflow (line 310) | func (h *SampleHelper) SignalWorkflow(workflowID, signal string, data ...
    method CancelWorkflow (line 324) | func (h *SampleHelper) CancelWorkflow(workflowID string) {
    method registerWorkflowAndActivity (line 338) | func (h *SampleHelper) registerWorkflowAndActivity(worker worker.Worke...
  type Configuration (line 48) | type Configuration struct
  type registryOption (line 55) | type registryOption struct

FILE: cmd/samples/common/util.go
  function StringPtr (line 4) | func StringPtr(v string) *string {
  function Int32Ptr (line 9) | func Int32Ptr(v int32) *int32 {
  function Int64Ptr (line 14) | func Int64Ptr(v int64) *int64 {

FILE: cmd/samples/cron/cron_workflow.go
  constant activityScheduleToStartTimeout (line 19) | activityScheduleToStartTimeout = time.Second * 10
  constant activityStartToCloseTimeout (line 21) | activityStartToCloseTimeout = time.Minute
  constant WorkflowStartToCloseTimeout (line 24) | WorkflowStartToCloseTimeout = time.Minute * 20
  constant DecisionTaskStartToCloseTimeout (line 26) | DecisionTaskStartToCloseTimeout = time.Second * 10
  function sampleCronActivity (line 32) | func sampleCronActivity(ctx context.Context, beginTime, endTime time.Tim...
  type SampleCronResult (line 39) | type SampleCronResult struct
  function sampleCronWorkflow (line 44) | func sampleCronWorkflow(ctx workflow.Context) (*SampleCronResult, error) {

FILE: cmd/samples/cron/cron_workflow_test.go
  type UnitTestSuite (line 16) | type UnitTestSuite struct
    method SetupTest (line 27) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 33) | func (s *UnitTestSuite) TearDownTest() {
    method Test_CronWorkflow (line 37) | func (s *UnitTestSuite) Test_CronWorkflow() {
  function TestUnitTestSuite (line 23) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/cron/main.go
  constant ApplicationName (line 16) | ApplicationName = "cronGroup"
  function startWorkers (line 21) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 36) | func startWorkflow(h *common.SampleHelper, cron string) {
  function main (line 49) | func main() {

FILE: cmd/samples/dsl/activities.go
  function sampleActivity1 (line 7) | func sampleActivity1(input []string) (string, error) {
  function sampleActivity2 (line 13) | func sampleActivity2(input []string) (string, error) {
  function sampleActivity3 (line 19) | func sampleActivity3(input []string) (string, error) {
  function sampleActivity4 (line 25) | func sampleActivity4(input []string) (string, error) {
  function sampleActivity5 (line 31) | func sampleActivity5(input []string) (string, error) {

FILE: cmd/samples/dsl/main.go
  function startWorkers (line 19) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 28) | func startWorkflow(h *common.SampleHelper, w Workflow) {
  function main (line 38) | func main() {

FILE: cmd/samples/dsl/workflow.go
  constant ApplicationName (line 11) | ApplicationName = "dslGroup"
  type Workflow (line 16) | type Workflow struct
  type Statement (line 23) | type Statement struct
    method execute (line 78) | func (b *Statement) execute(ctx workflow.Context, bindings map[string]...
  type Sequence (line 30) | type Sequence struct
    method execute (line 113) | func (s Sequence) execute(ctx workflow.Context, bindings map[string]st...
  type Parallel (line 35) | type Parallel struct
    method execute (line 123) | func (p Parallel) execute(ctx workflow.Context, bindings map[string]st...
  type ActivityInvocation (line 42) | type ActivityInvocation struct
    method execute (line 100) | func (a ActivityInvocation) execute(ctx workflow.Context, bindings map...
  type executable (line 48) | type executable interface
  function simpleDSLWorkflow (line 54) | func simpleDSLWorkflow(ctx workflow.Context, dslWorkflow Workflow) ([]by...
  function executeAsync (line 156) | func executeAsync(exe executable, ctx workflow.Context, bindings map[str...
  function makeInput (line 165) | func makeInput(argNames []string, argsMap map[string]string) []string {

FILE: cmd/samples/dsl/workflow_test.go
  function TestActivitySequenceParallelStatements (line 14) | func TestActivitySequenceParallelStatements(t *testing.T) {
  function TestSequenceFlow (line 120) | func TestSequenceFlow(t *testing.T) {
  function TestParallelFlow (line 226) | func TestParallelFlow(t *testing.T) {
  function TestActivityInvocationFlow (line 332) | func TestActivityInvocationFlow(t *testing.T) {
  function Test_SimpleDSLWorkflow (line 392) | func Test_SimpleDSLWorkflow(t *testing.T) {
  function sampleActivity (line 422) | func sampleActivity(input []string) (string, error) {

FILE: cmd/samples/expense/activities.go
  function createExpenseActivity (line 15) | func createExpenseActivity(ctx context.Context, expenseID string) error {
  function waitForDecisionActivity (line 43) | func waitForDecisionActivity(ctx context.Context, expenseID string) (str...
  function paymentActivity (line 81) | func paymentActivity(ctx context.Context, expenseID string) error {

FILE: cmd/samples/expense/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper, expenseID string) {
  function main (line 35) | func main() {

FILE: cmd/samples/expense/server/dummy.go
  type expenseState (line 18) | type expenseState
  constant created (line 21) | created   expenseState = "CREATED"
  constant approved (line 22) | approved               = "APPROVED"
  constant rejected (line 23) | rejected               = "REJECTED"
  constant completed (line 24) | completed              = "COMPLETED"
  function main (line 34) | func main() {
  function listHandler (line 53) | func listHandler(w http.ResponseWriter, r *http.Request) {
  function actionHandler (line 75) | func actionHandler(w http.ResponseWriter, r *http.Request) {
  function createHandler (line 107) | func createHandler(w http.ResponseWriter, r *http.Request) {
  function statusHandler (line 126) | func statusHandler(w http.ResponseWriter, r *http.Request) {
  function callbackHandler (line 139) | func callbackHandler(w http.ResponseWriter, r *http.Request) {
  function notifyExpenseStateChange (line 164) | func notifyExpenseStateChange(id, state string) {

FILE: cmd/samples/expense/workflow.go
  constant ApplicationName (line 12) | ApplicationName = "expenseGroup"
  function sampleExpenseWorkflow (line 18) | func sampleExpenseWorkflow(ctx workflow.Context, expenseID string) (resu...

FILE: cmd/samples/expense/workflow_test.go
  type UnitTestSuite (line 16) | type UnitTestSuite struct
    method SetupTest (line 27) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 35) | func (s *UnitTestSuite) TearDownTest() {
    method Test_WorkflowWithMockActivities (line 39) | func (s *UnitTestSuite) Test_WorkflowWithMockActivities() {
    method Test_TimeoutWithMockActivities (line 54) | func (s *UnitTestSuite) Test_TimeoutWithMockActivities() {
    method Test_WorkflowStatusRejected (line 67) | func (s *UnitTestSuite) Test_WorkflowStatusRejected() {
    method Test_WorkflowStatusCancelled (line 81) | func (s *UnitTestSuite) Test_WorkflowStatusCancelled() {
    method Test_WorkflowStatusApprovedWithPaymentError (line 95) | func (s *UnitTestSuite) Test_WorkflowStatusApprovedWithPaymentError() {
    method Test_CreateActivityFailed (line 110) | func (s *UnitTestSuite) Test_CreateActivityFailed() {
    method Test_WaitForDecisionActivityFailed (line 124) | func (s *UnitTestSuite) Test_WaitForDecisionActivityFailed() {
    method Test_PaymentActivityFailed (line 139) | func (s *UnitTestSuite) Test_PaymentActivityFailed() {
    method Test_WorkflowWithMockServer (line 155) | func (s *UnitTestSuite) Test_WorkflowWithMockServer() {
  function TestUnitTestSuite (line 23) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/fileprocessing/activities.go
  constant downloadFileActivityName (line 19) | downloadFileActivityName = "downloadFileActivity"
  constant processFileActivityName (line 20) | processFileActivityName  = "processFileActivity"
  constant uploadFileActivityName (line 21) | uploadFileActivityName   = "uploadFileActivity"
  function downloadFileActivity (line 24) | func downloadFileActivity(ctx context.Context, fileID string) (*fileInfo...
  function processFileActivity (line 40) | func processFileActivity(ctx context.Context, fInfo fileInfo) (*fileInfo...
  function uploadFileActivity (line 74) | func uploadFileActivity(ctx context.Context, fInfo fileInfo) error {
  function downloadFile (line 98) | func downloadFile(fileID string) []byte {
  function uploadFile (line 104) | func uploadFile(ctx context.Context, filename string) error {
  function transcodeData (line 119) | func transcodeData(ctx context.Context, data []byte) []byte {
  function saveToTmpFile (line 131) | func saveToTmpFile(data []byte) (f *os.File, err error) {

FILE: cmd/samples/fileprocessing/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 31) | func startWorkflow(h *common.SampleHelper, fileID string) {
  function main (line 41) | func main() {

FILE: cmd/samples/fileprocessing/workflow.go
  type fileInfo (line 13) | type fileInfo struct
  constant ApplicationName (line 20) | ApplicationName = "FileProcessorGroup"
  function sampleFileProcessingWorkflow (line 27) | func sampleFileProcessingWorkflow(ctx workflow.Context, fileID string) (...
  function processFile (line 61) | func processFile(ctx workflow.Context, fileID string) (err error) {

FILE: cmd/samples/fileprocessing/workflow_test.go
  type UnitTestSuite (line 14) | type UnitTestSuite struct
    method SetupTest (line 25) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 39) | func (s *UnitTestSuite) TearDownTest() {
    method Test_SampleFileProcessingWorkflow (line 43) | func (s *UnitTestSuite) Test_SampleFileProcessingWorkflow() {
  function TestUnitTestSuite (line 21) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/pso/activities.go
  constant initParticleActivityName (line 15) | initParticleActivityName   = "initParticleActivityName"
  constant updateParticleActivityName (line 16) | updateParticleActivityName = "updateParticleActivityName"
  function init (line 22) | func init() {
  function initParticleActivity (line 29) | func initParticleActivity(ctx context.Context, swarm Swarm) (Particle, e...
  function updateParticleActivity (line 39) | func updateParticleActivity(ctx context.Context, swarm Swarm, particleId...

FILE: cmd/samples/pso/dataconverter.go
  type gobDataConverter (line 16) | type gobDataConverter struct
    method ToData (line 37) | func (dc *gobDataConverter) ToData(value ...interface{}) ([]byte, erro...
    method FromData (line 71) | func (dc *gobDataConverter) FromData(input []byte, valuePtr ...interfa...
  function NewGobDataConverter (line 20) | func NewGobDataConverter() encoded.DataConverter {
  type jsonDataConverter (line 27) | type jsonDataConverter struct
    method ToData (line 102) | func (dc *jsonDataConverter) ToData(value ...interface{}) ([]byte, err...
    method FromData (line 139) | func (dc *jsonDataConverter) FromData(input []byte, valuePtr ...interf...
  function NewJSONDataConverter (line 31) | func NewJSONDataConverter() encoded.DataConverter {

FILE: cmd/samples/pso/functions.go
  type ObjectiveFunction (line 5) | type ObjectiveFunction struct
  function EvalSphere (line 40) | func EvalSphere(vec []float64) float64 {
  function EvalRosenbrock (line 48) | func EvalRosenbrock(vec []float64) float64 {
  function EvalGriewank (line 58) | func EvalGriewank(vec []float64) float64 {

FILE: cmd/samples/pso/main.go
  function startWorkers (line 18) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 29) | func startWorkflow(h *common.SampleHelper, functionName string) {
  function main (line 39) | func main() {

FILE: cmd/samples/pso/particle.go
  type Particle (line 5) | type Particle struct
    method UpdateLocation (line 29) | func (particle *Particle) UpdateLocation(swarm *Swarm, rng *rand.Rand) {
    method UpdateFitness (line 44) | func (particle *Particle) UpdateFitness(swarm *Swarm) {
  function NewParticle (line 11) | func NewParticle(swarm *Swarm, rng *rand.Rand) *Particle {

FILE: cmd/samples/pso/position.go
  type Vector (line 7) | type Vector
  type Position (line 9) | type Position struct
    method Copy (line 33) | func (position *Position) Copy() *Position {
    method IsBetterThan (line 40) | func (position *Position) IsBetterThan(other *Position) bool {
  function NewPosition (line 14) | func NewPosition(dim int) *Position {
  function RandomPosition (line 22) | func RandomPosition(function ObjectiveFunction, rng *rand.Rand) *Position {

FILE: cmd/samples/pso/settings.go
  constant pso_max_size (line 3) | pso_max_size int = 100
  constant pso_inertia (line 4) | pso_inertia float64 = 0.7298
  type SwarmSettings (line 6) | type SwarmSettings struct
  function FunctionFactory (line 32) | func FunctionFactory(functionName string) ObjectiveFunction {
  function PSODefaultSettings (line 45) | func PSODefaultSettings(functionName string) *SwarmSettings {

FILE: cmd/samples/pso/swarm.go
  type ParticleResult (line 12) | type ParticleResult struct
  type Swarm (line 17) | type Swarm struct
    method updateBest (line 63) | func (swarm *Swarm) updateBest() {
    method Run (line 71) | func (swarm *Swarm) Run(ctx workflow.Context, step int) (ParticleResul...
  function NewSwarm (line 23) | func NewSwarm(ctx workflow.Context, settings *SwarmSettings) (*Swarm, er...

FILE: cmd/samples/pso/utils.go
  function CalculateSwarmSize (line 7) | func CalculateSwarmSize(dim, max_size int) int {

FILE: cmd/samples/pso/workflow.go
  type WorkflowResult (line 13) | type WorkflowResult struct
  constant ApplicationName (line 19) | ApplicationName = "PSO"
  constant ContinueAsNewStr (line 36) | ContinueAsNewStr = "CONTINUEASNEW"
  function samplePSOWorkflow (line 39) | func samplePSOWorkflow(ctx workflow.Context, functionName string) (strin...
  function samplePSOChildWorkflow (line 103) | func samplePSOChildWorkflow(ctx workflow.Context, swarm Swarm, startingS...

FILE: cmd/samples/pso/workflow_test.go
  function Test_Workflow (line 15) | func Test_Workflow(t *testing.T) {
  function queryAndVerify (line 63) | func queryAndVerify(t *testing.T, env *testsuite.TestWorkflowEnvironment...

FILE: cmd/samples/recipes/branch/branch_workflow.go
  constant ApplicationName (line 16) | ApplicationName = "branchGroup"
  constant totalBranches (line 18) | totalBranches = 3
  function sampleBranchWorkflow (line 22) | func sampleBranchWorkflow(ctx workflow.Context) error {
  function sampleActivity (line 50) | func sampleActivity(input string) (string, error) {

FILE: cmd/samples/recipes/branch/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflowParallel (line 25) | func startWorkflowParallel(h *common.SampleHelper) {
  function startWorkflowBranch (line 35) | func startWorkflowBranch(h *common.SampleHelper) {
  function main (line 45) | func main() {

FILE: cmd/samples/recipes/branch/parallel_workflow.go
  function sampleParallelWorkflow (line 16) | func sampleParallelWorkflow(ctx workflow.Context) error {

FILE: cmd/samples/recipes/branch/workflow_test.go
  type UnitTestSuite (line 10) | type UnitTestSuite struct
    method SetupTest (line 21) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 28) | func (s *UnitTestSuite) TearDownTest() {
    method Test_BranchWorkflow (line 32) | func (s *UnitTestSuite) Test_BranchWorkflow() {
    method Test_ParallelWorkflow (line 39) | func (s *UnitTestSuite) Test_ParallelWorkflow() {
  function TestUnitTestSuite (line 17) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/cancelactivity/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function cancelWorkflow (line 35) | func cancelWorkflow(h *common.SampleHelper, wid string) {
  function main (line 39) | func main() {

FILE: cmd/samples/recipes/cancelactivity/workflow.go
  constant ApplicationName (line 19) | ApplicationName = "cancelGroup"
  function sampleCancelWorkflow (line 22) | func sampleCancelWorkflow(ctx workflow.Context) (retError error) {
  function activityToBeCanceled (line 66) | func activityToBeCanceled(ctx context.Context) (string, error) {
  function cleanupActivity (line 83) | func cleanupActivity(ctx context.Context) error {
  function activityToBeSkipped (line 89) | func activityToBeSkipped(ctx context.Context) error {

FILE: cmd/samples/recipes/cancelactivity/workflow_test.go
  function TestCancelWorkflow (line 13) | func TestCancelWorkflow(t *testing.T) {

FILE: cmd/samples/recipes/childworkflow/child_workflow.go
  function sampleChildWorkflow (line 17) | func sampleChildWorkflow(ctx workflow.Context, totalCount, runCount int)...

FILE: cmd/samples/recipes/childworkflow/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/childworkflow/parent_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "childWorkflowGroup"
  function sampleParentWorkflow (line 20) | func sampleParentWorkflow(ctx workflow.Context) error {

FILE: cmd/samples/recipes/choice/exclusive_choice_workflow.go
  constant ApplicationName (line 18) | ApplicationName = "choiceGroup"
  constant orderChoiceApple (line 20) | orderChoiceApple  = "apple"
  constant orderChoiceBanana (line 21) | orderChoiceBanana = "banana"
  constant orderChoiceCherry (line 22) | orderChoiceCherry = "cherry"
  constant orderChoiceOrange (line 23) | orderChoiceOrange = "orange"
  function exclusiveChoiceWorkflow (line 29) | func exclusiveChoiceWorkflow(ctx workflow.Context) error {
  function getOrderActivity (line 64) | func getOrderActivity() (string, error) {
  function orderAppleActivity (line 71) | func orderAppleActivity(choice string) error {
  function orderBananaActivity (line 76) | func orderBananaActivity(choice string) error {
  function orderCherryActivity (line 81) | func orderCherryActivity(choice string) error {
  function orderOrangeActivity (line 86) | func orderOrangeActivity(choice string) error {

FILE: cmd/samples/recipes/choice/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflowMultiChoice (line 27) | func startWorkflowMultiChoice(h *common.SampleHelper) {
  function startWorkflowExclusiveChoice (line 37) | func startWorkflowExclusiveChoice(h *common.SampleHelper) {
  function main (line 47) | func main() {

FILE: cmd/samples/recipes/choice/multi_choice_workflow.go
  function multiChoiceWorkflow (line 19) | func multiChoiceWorkflow(ctx workflow.Context) error {
  function getBasketOrderActivity (line 64) | func getBasketOrderActivity(ctx context.Context) ([]string, error) {

FILE: cmd/samples/recipes/choice/workflow_test.go
  type UnitTestSuite (line 10) | type UnitTestSuite struct
    method SetupTest (line 21) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 33) | func (s *UnitTestSuite) TearDownTest() {
    method Test_ExclusiveChoiceWorkflow (line 37) | func (s *UnitTestSuite) Test_ExclusiveChoiceWorkflow() {
    method Test_MultiChoiceWorkflow (line 44) | func (s *UnitTestSuite) Test_MultiChoiceWorkflow() {
  function TestUnitTestSuite (line 17) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/consistentquery/main.go
  function startWorkers (line 17) | func startWorkers(h *common.SampleHelper) {
  function main (line 26) | func main() {

FILE: cmd/samples/recipes/consistentquery/query_workflow.go
  constant ApplicationName (line 11) | ApplicationName = "queryGroup"
  function queryWorkflow (line 14) | func queryWorkflow(ctx workflow.Context) error {

FILE: cmd/samples/recipes/crossdomain/main.go
  constant tasklist0 (line 19) | tasklist0    = "cross-domain-tl0"
  constant tasklist1 (line 20) | tasklist1    = "cross-domain-tl1"
  constant tasklist2 (line 21) | tasklist2    = "cross-domain-tl2"
  constant domain0 (line 22) | domain0      = "domain0"
  constant domain1 (line 23) | domain1      = "domain1"
  constant domain2 (line 24) | domain2      = "domain2"
  constant portCluster0 (line 25) | portCluster0 = "127.0.0.1:7833"
  constant portCluster1 (line 26) | portCluster1 = "127.0.0.1:8833"
  constant portCluster2 (line 27) | portCluster2 = "127.0.0.1:9833"
  function main (line 30) | func main() {
  function setupClient (line 70) | func setupClient(domain string, hostport string) client.Client {
  function setupWorker (line 101) | func setupWorker(domain string, tl string, hostport string, wfs []interf...

FILE: cmd/samples/recipes/crossdomain/wf.go
  type Data (line 13) | type Data struct
  function wf0 (line 17) | func wf0(ctx workflow.Context) error {
  function wf1 (line 48) | func wf1(ctx workflow.Context, args Data) error {
  function wf2 (line 68) | func wf2(ctx workflow.Context, args Data) error {
  function activity1 (line 86) | func activity1(ctx context.Context) (string, error) {
  function activity2 (line 92) | func activity2(ctx context.Context) (string, error) {

FILE: cmd/samples/recipes/ctxpropagation/activities.go
  constant sampleActivityName (line 8) | sampleActivityName = "sampleActivity"
  function sampleActivity (line 11) | func sampleActivity(ctx context.Context) (*Values, error) {

FILE: cmd/samples/recipes/ctxpropagation/main.go
  function startWorkers (line 18) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 31) | func startWorkflow(h *common.SampleHelper) {
  function main (line 43) | func main() {

FILE: cmd/samples/recipes/ctxpropagation/propagator.go
  type contextKey (line 14) | type contextKey struct
  type propagator (line 17) | type propagator struct
    method Inject (line 40) | func (s *propagator) Inject(ctx context.Context, writer workflow.Heade...
    method InjectFromWorkflow (line 51) | func (s *propagator) InjectFromWorkflow(ctx workflow.Context, writer w...
    method Extract (line 62) | func (s *propagator) Extract(ctx context.Context, reader workflow.Head...
    method ExtractToWorkflow (line 79) | func (s *propagator) ExtractToWorkflow(ctx workflow.Context, reader wo...
  type Values (line 20) | type Values struct
  constant propagationKey (line 31) | propagationKey = "_prop"
  function NewContextPropagator (line 35) | func NewContextPropagator() workflow.ContextPropagator {
  function SetValuesInHeader (line 96) | func SetValuesInHeader(values Values, header *shared.Header) error {

FILE: cmd/samples/recipes/ctxpropagation/workflow.go
  constant ApplicationName (line 11) | ApplicationName = "CtxPropagatorGroup"
  function sampleCtxPropWorkflow (line 14) | func sampleCtxPropWorkflow(ctx workflow.Context) (err error) {

FILE: cmd/samples/recipes/ctxpropagation/workflow_test.go
  type UnitTestSuite (line 16) | type UnitTestSuite struct
    method SetupTest (line 28) | func (s *UnitTestSuite) SetupTest() {
    method Test_CtxPropWorkflow (line 47) | func (s *UnitTestSuite) Test_CtxPropWorkflow() {
  function TestUnitTestSuite (line 24) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/delaystart/delaystart_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "delaystartGroup"
  constant delayStartWorkflowName (line 19) | delayStartWorkflowName = "delayStartWorkflow"
  function delayStartWorkflow (line 22) | func delayStartWorkflow(ctx workflow.Context, delayStart time.Duration) ...
  function delayStartActivity (line 60) | func delayStartActivity(ctx context.Context, delayStart time.Duration) (...

FILE: cmd/samples/recipes/delaystart/delaystart_workflow_test.go
  function Test_Workflow (line 13) | func Test_Workflow(t *testing.T) {

FILE: cmd/samples/recipes/delaystart/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startShadower (line 28) | func startShadower(h *common.SampleHelper) {
  function startWorkflow (line 44) | func startWorkflow(h *common.SampleHelper) {
  function registerWorkflowAndActivity (line 56) | func registerWorkflowAndActivity(
  function main (line 63) | func main() {

FILE: cmd/samples/recipes/dynamic/dynamic_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "dynamicGroup"
  constant GreetingsWorkflowName (line 20) | GreetingsWorkflowName = "main.sampleGreetingsWorkflow"
  constant getNameActivityName (line 23) | getNameActivityName = "main.getNameActivity"
  constant getGreetingActivityName (line 24) | getGreetingActivityName = "main.getGreetingActivity"
  constant sayGreetingActivityName (line 25) | sayGreetingActivityName = "main.sayGreetingActivity"
  function sampleGreetingsWorkflow (line 28) | func sampleGreetingsWorkflow(ctx workflow.Context) error {
  function getNameActivity (line 66) | func getNameActivity() (string, error) {
  function getGreetingActivity (line 71) | func getGreetingActivity() (string, error) {
  function sayGreetingActivity (line 76) | func sayGreetingActivity(greeting string, name string) (string, error) {

FILE: cmd/samples/recipes/dynamic/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/dynamic/workflow_test.go
  function TestDynamicWorkflow (line 11) | func TestDynamicWorkflow(t *testing.T) {

FILE: cmd/samples/recipes/greetings/greetings_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "greetingsGroup"
  function sampleGreetingsWorkflow (line 20) | func sampleGreetingsWorkflow(ctx workflow.Context) error {
  function getNameActivity (line 58) | func getNameActivity() (string, error) {
  function getGreetingActivity (line 63) | func getGreetingActivity() (string, error) {
  function sayGreetingActivity (line 68) | func sayGreetingActivity(greeting string, name string) (string, error) {

FILE: cmd/samples/recipes/greetings/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/greetings/replay_test.go
  function TestReplayWorkflowHistoryFromFile (line 18) | func TestReplayWorkflowHistoryFromFile(t *testing.T) {

FILE: cmd/samples/recipes/greetings/shadow_test.go
  constant configFile (line 16) | configFile = "../../../../config/development.yaml"
  function TestWorkflowShadowing (line 21) | func TestWorkflowShadowing(t *testing.T) {

FILE: cmd/samples/recipes/greetings/workflow_test.go
  type UnitTestSuite (line 13) | type UnitTestSuite struct
    method SetupTest (line 24) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 32) | func (s *UnitTestSuite) TearDownTest() {
    method Test_SampleGreetingsWorkflow (line 36) | func (s *UnitTestSuite) Test_SampleGreetingsWorkflow() {
  function TestUnitTestSuite (line 20) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/helloworld/activity_logger_test.go
  function sampleActivity (line 14) | func sampleActivity(ctx context.Context) error {
  function Test_Activity_Noop_Logger (line 20) | func Test_Activity_Noop_Logger(t *testing.T) {
  function Test_Activity_Print_Logger (line 29) | func Test_Activity_Print_Logger(t *testing.T) {

FILE: cmd/samples/recipes/helloworld/helloworld_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "helloWorldGroup"
  constant helloWorldWorkflowName (line 19) | helloWorldWorkflowName = "helloWorldWorkflow"
  function helloWorldWorkflow (line 22) | func helloWorldWorkflow(ctx workflow.Context, name string) error {
  function helloWorldActivity (line 60) | func helloWorldActivity(ctx context.Context, name string) (string, error) {

FILE: cmd/samples/recipes/helloworld/helloworld_workflow_test.go
  function Test_Workflow (line 12) | func Test_Workflow(t *testing.T) {

FILE: cmd/samples/recipes/helloworld/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startShadower (line 28) | func startShadower(h *common.SampleHelper) {
  function startWorkflow (line 44) | func startWorkflow(h *common.SampleHelper) {
  function registerWorkflowAndActivity (line 54) | func registerWorkflowAndActivity(
  function main (line 61) | func main() {

FILE: cmd/samples/recipes/helloworld/replay_test.go
  function TestReplayWorkflowHistoryFromFile (line 18) | func TestReplayWorkflowHistoryFromFile(t *testing.T) {

FILE: cmd/samples/recipes/helloworld/shadow_test.go
  constant configFile (line 16) | configFile = "../../../../config/development.yaml"
  function TestWorkflowShadowing (line 21) | func TestWorkflowShadowing(t *testing.T) {

FILE: cmd/samples/recipes/localactivity/local_activity_workflow.go
  constant ApplicationName (line 19) | ApplicationName = "localActivityGroup"
  constant SignalName (line 22) | SignalName = "trigger-signal"
  type conditionAndAction (line 24) | type conditionAndAction struct
  function processingWorkflow (line 45) | func processingWorkflow(ctx workflow.Context, data string) (string, erro...
  function signalHandlingWorkflow (line 89) | func signalHandlingWorkflow(ctx workflow.Context) error {
  function checkCondition0 (line 124) | func checkCondition0(ctx context.Context, signal string) (bool, error) {
  function checkCondition1 (line 129) | func checkCondition1(ctx context.Context, signal string) (bool, error) {
  function checkCondition2 (line 134) | func checkCondition2(ctx context.Context, signal string) (bool, error) {
  function checkCondition3 (line 139) | func checkCondition3(ctx context.Context, signal string) (bool, error) {
  function checkCondition4 (line 144) | func checkCondition4(ctx context.Context, signal string) (bool, error) {
  function activityForCondition0 (line 149) | func activityForCondition0(ctx context.Context, signal string) (string, ...
  function activityForCondition1 (line 156) | func activityForCondition1(ctx context.Context, signal string) (string, ...
  function activityForCondition2 (line 163) | func activityForCondition2(ctx context.Context, signal string) (string, ...
  function activityForCondition3 (line 170) | func activityForCondition3(ctx context.Context, signal string) (string, ...
  function activityForCondition4 (line 177) | func activityForCondition4(ctx context.Context, signal string) (string, ...

FILE: cmd/samples/recipes/localactivity/local_activity_workflow_test.go
  type UnitTestSuite (line 12) | type UnitTestSuite struct
    method SetupTest (line 23) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 34) | func (s *UnitTestSuite) TearDownTest() {
    method Test_ProcessingWorkflow_SingleAction (line 38) | func (s *UnitTestSuite) Test_ProcessingWorkflow_SingleAction() {
    method Test_ProcessingWorkflow_MultiAction (line 53) | func (s *UnitTestSuite) Test_ProcessingWorkflow_MultiAction() {
    method Test_SignalHandlingWorkflow (line 69) | func (s *UnitTestSuite) Test_SignalHandlingWorkflow() {
  function TestUnitTestSuite (line 19) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/localactivity/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 36) | func main() {

FILE: cmd/samples/recipes/mutex/main.go
  constant ApplicationName (line 17) | ApplicationName = "mutexExample"
  constant _sampleHelperContextKey (line 19) | _sampleHelperContextKey = "sampleHelper"
  function startWorkers (line 24) | func startWorkers(h *common.SampleHelper) {
  function startTwoWorkflows (line 37) | func startTwoWorkflows(h *common.SampleHelper) {
  function main (line 57) | func main() {

FILE: cmd/samples/recipes/mutex/mutex_workflow.go
  constant AcquireLockSignalName (line 20) | AcquireLockSignalName = "acquire-lock-event"
  constant RequestLockSignalName (line 22) | RequestLockSignalName = "request-lock-event"
  type UnlockFunc (line 26) | type UnlockFunc
  type Mutex (line 29) | type Mutex struct
    method Lock (line 43) | func (s *Mutex) Lock(ctx workflow.Context,
  function NewMutex (line 35) | func NewMutex(currentWorkflowID string, lockNamespace string) *Mutex {
  function mutexWorkflow (line 76) | func mutexWorkflow(
  function signalWithStartMutexWorkflowActivity (line 130) | func signalWithStartMutexWorkflowActivity(
  function _generateUnlockChannelName (line 166) | func _generateUnlockChannelName(senderWorkflowID string) string {
  function MockMutexLock (line 171) | func MockMutexLock(env *testsuite.TestWorkflowEnvironment, resourceID st...
  function sampleWorkflowWithMutex (line 185) | func sampleWorkflowWithMutex(

FILE: cmd/samples/recipes/mutex/mutex_workflow_test.go
  type UnitTestSuite (line 17) | type UnitTestSuite struct
    method SetupTest (line 28) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 40) | func (s *UnitTestSuite) TearDownTest() {
    method Test_Workflow_Success (line 44) | func (s *UnitTestSuite) Test_Workflow_Success() {
    method Test_Workflow_Error (line 53) | func (s *UnitTestSuite) Test_Workflow_Error() {
    method Test_MutexWorkflow_Success (line 62) | func (s *UnitTestSuite) Test_MutexWorkflow_Success() {
    method Test_MutexWorkflow_TimeoutSuccess (line 87) | func (s *UnitTestSuite) Test_MutexWorkflow_TimeoutSuccess() {
  function TestUnitTestSuite (line 24) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/pickfirst/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 27) | func startWorkflow(h *common.SampleHelper) {
  function main (line 37) | func main() {

FILE: cmd/samples/recipes/pickfirst/pickfirst_workflow.go
  constant ApplicationName (line 18) | ApplicationName = "pickfirstGroup"
  function samplePickFirstWorkflow (line 21) | func samplePickFirstWorkflow(ctx workflow.Context) error {
  function sampleActivity (line 66) | func sampleActivity(ctx context.Context, currentBranchID int, totalDurat...

FILE: cmd/samples/recipes/pickfirst/pickfirst_workflow_test.go
  type UnitTestSuite (line 13) | type UnitTestSuite struct
    method SetupTest (line 24) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 30) | func (s *UnitTestSuite) TearDownTest() {
    method Test_Workflow (line 34) | func (s *UnitTestSuite) Test_Workflow() {
  function TestUnitTestSuite (line 20) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/query/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/query/query_workflow.go
  constant ApplicationName (line 10) | ApplicationName = "queryGroup"
  function queryWorkflow (line 13) | func queryWorkflow(ctx workflow.Context) error {

FILE: cmd/samples/recipes/query/query_workflow_test.go
  function Test_QueryWorkflow (line 11) | func Test_QueryWorkflow(t *testing.T) {
  function queryAndVerify (line 29) | func queryAndVerify(t *testing.T, env *testsuite.TestWorkflowEnvironment...

FILE: cmd/samples/recipes/retryactivity/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/retryactivity/retry_activity_workflow.go
  constant ApplicationName (line 20) | ApplicationName = "retryactivityGroup"
  function retryWorkflow (line 23) | func retryWorkflow(ctx workflow.Context) error {
  function batchProcessingActivity (line 50) | func batchProcessingActivity(ctx context.Context, firstTaskID, batchSize...

FILE: cmd/samples/recipes/retryactivity/retry_activity_workflow_test.go
  type UnitTestSuite (line 14) | type UnitTestSuite struct
    method SetupTest (line 25) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 31) | func (s *UnitTestSuite) TearDownTest() {
    method Test_Workflow (line 35) | func (s *UnitTestSuite) Test_Workflow() {
  function TestUnitTestSuite (line 21) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/searchattributes/main.go
  function startWorkers (line 18) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 36) | func startWorkflow(h *common.SampleHelper) {
  function getSearchAttributesForStart (line 47) | func getSearchAttributesForStart() map[string]interface{} {
  function main (line 53) | func main() {

FILE: cmd/samples/recipes/searchattributes/searchattributes_workflow.go
  constant ApplicationName (line 25) | ApplicationName = "searchAttributesGroup"
  type ClientKey (line 28) | type ClientKey
  constant DomainName (line 32) | DomainName = "default"
  constant CadenceClientKey (line 34) | CadenceClientKey ClientKey = iota
  function searchAttributesWorkflow (line 43) | func searchAttributesWorkflow(ctx workflow.Context) error {
  function printSearchAttributes (line 111) | func printSearchAttributes(searchAttributes *shared.SearchAttributes, lo...
  function listExecutions (line 126) | func listExecutions(ctx context.Context, query string) ([]*shared.Workfl...
  function getCadenceClientFromContext (line 160) | func getCadenceClientFromContext(ctx context.Context) (client.Client, er...

FILE: cmd/samples/recipes/searchattributes/searchattributes_workflow_test.go
  function Test_Workflow (line 13) | func Test_Workflow(t *testing.T) {

FILE: cmd/samples/recipes/sideeffect/sideeffect_workflow.go
  constant ApplicationName (line 16) | ApplicationName = "HelloSideEffect"
  function SideEffectWorkflow (line 18) | func SideEffectWorkflow(ctx workflow.Context) error {
  function startWorkflow (line 42) | func startWorkflow(h *common.SampleHelper) {
  function startWorkers (line 53) | func startWorkers(h *common.SampleHelper) {
  function main (line 62) | func main() {

FILE: cmd/samples/recipes/signalcounter/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/signalcounter/signal_counter_workflow.go
  constant ApplicationName (line 13) | ApplicationName = "signal_counter"
  constant maxSignalsPerExecution (line 18) | maxSignalsPerExecution = 3
  function sampleSignalCounterWorkflow (line 21) | func sampleSignalCounterWorkflow(ctx workflow.Context, counter int) error {

FILE: cmd/samples/recipes/signalcounter/workflow_test.go
  type UnitTestSuite (line 12) | type UnitTestSuite struct
    method SetupTest (line 23) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 28) | func (s *UnitTestSuite) TearDownTest() {
    method Test_SampleSignalCounterWorkflow (line 32) | func (s *UnitTestSuite) Test_SampleSignalCounterWorkflow() {
  function TestUnitTestSuite (line 19) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/sleep/main.go
  constant ApplicationName (line 15) | ApplicationName   = "sleepTaskList"
  constant SleepWorkflowName (line 16) | SleepWorkflowName = "sleepWorkflow"
  function startWorkers (line 19) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 30) | func startWorkflow(h *common.SampleHelper) {
  function registerWorkflowAndActivity (line 41) | func registerWorkflowAndActivity(h *common.SampleHelper) {
  function main (line 46) | func main() {

FILE: cmd/samples/recipes/sleep/sleep_workflow.go
  constant sleepWorkflowName (line 12) | sleepWorkflowName = "sleepWorkflow"
  function sleepWorkflow (line 15) | func sleepWorkflow(ctx workflow.Context, sleepDuration time.Duration) er...
  function mainSleepActivity (line 48) | func mainSleepActivity(ctx context.Context) (string, error) {

FILE: cmd/samples/recipes/sleep/sleep_workflow_test.go
  function Test_Sleep (line 13) | func Test_Sleep(t *testing.T) {

FILE: cmd/samples/recipes/splitmerge/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 25) | func startWorkflow(h *common.SampleHelper) {
  function main (line 35) | func main() {

FILE: cmd/samples/recipes/splitmerge/splitmerge_workflow.go
  constant ApplicationName (line 19) | ApplicationName = "splitmergeGroup"
  type ChunkResult (line 23) | type ChunkResult struct
  function sampleSplitMergeWorkflow (line 30) | func sampleSplitMergeWorkflow(ctx workflow.Context, workerCount int) (Ch...
  function chunkProcessingActivity (line 71) | func chunkProcessingActivity(ctx context.Context, chunkID int) (result C...

FILE: cmd/samples/recipes/splitmerge/splitmerge_workflow_test.go
  type UnitTestSuite (line 10) | type UnitTestSuite struct
    method SetupTest (line 21) | func (s *UnitTestSuite) SetupTest() {
    method TearDownTest (line 27) | func (s *UnitTestSuite) TearDownTest() {
    method Test_Workflow (line 31) | func (s *UnitTestSuite) Test_Workflow() {
  function TestUnitTestSuite (line 17) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/timer/main.go
  function startWorkers (line 16) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 27) | func startWorkflow(h *common.SampleHelper) {
  function main (line 37) | func main() {

FILE: cmd/samples/recipes/timer/workflow.go
  constant ApplicationName (line 14) | ApplicationName = "timerGroup"
  function sampleTimerWorkflow (line 17) | func sampleTimerWorkflow(ctx workflow.Context, processingTimeThreshold t...
  function orderProcessingActivity (line 63) | func orderProcessingActivity(ctx context.Context) error {
  function sendEmailActivity (line 72) | func sendEmailActivity(ctx context.Context) error {

FILE: cmd/samples/recipes/timer/workflow_test.go
  type UnitTestSuite (line 14) | type UnitTestSuite struct
    method SetupTest (line 25) | func (s *UnitTestSuite) SetupTest() {
    method Test_Workflow_FastProcessing (line 32) | func (s *UnitTestSuite) Test_Workflow_FastProcessing() {
    method Test_Workflow_SlowProcessing (line 46) | func (s *UnitTestSuite) Test_Workflow_SlowProcessing() {
  function TestUnitTestSuite (line 21) | func TestUnitTestSuite(t *testing.T) {

FILE: cmd/samples/recipes/tracing/helloworld_workflow.go
  constant ApplicationName (line 17) | ApplicationName = "helloWorldGroup"
  constant helloWorldWorkflowName (line 19) | helloWorldWorkflowName = "helloWorldWorkflow"
  function helloWorldWorkflow (line 22) | func helloWorldWorkflow(ctx workflow.Context, name string) error {
  function helloWorldActivity (line 44) | func helloWorldActivity(ctx context.Context, name string) (string, error) {

FILE: cmd/samples/recipes/tracing/main.go
  function startWorkers (line 21) | func startWorkers(h *common.SampleHelper) {
  function startWorkflow (line 34) | func startWorkflow(h *common.SampleHelper) {
  function registerWorkflowAndActivity (line 44) | func registerWorkflowAndActivity(
  function main (line 51) | func main() {
  function initJaeger (line 77) | func initJaeger(service string) (opentracing.Tracer, io.Closer) {

FILE: cmd/samples/recipes/versioning/main.go
  function startWorkers (line 17) | func startWorkers(h *common.SampleHelper) worker.Worker {
  function startWorkflow (line 27) | func startWorkflow(h *common.SampleHelper) {
  function stopWorkflow (line 40) | func stopWorkflow(h *common.SampleHelper) {
  function main (line 45) | func main() {

FILE: cmd/samples/recipes/versioning/versioned_workflow.go
  constant ApplicationName (line 18) | ApplicationName = "versioning"
  constant TestChangeID (line 21) | TestChangeID = "test-change"
  constant FooActivityName (line 24) | FooActivityName = "FooActivity"
  constant BarActivityName (line 25) | BarActivityName = "BarActivity"
  constant VersionedWorkflowName (line 28) | VersionedWorkflowName = "VersionedWorkflow"
  constant VersionedWorkflowID (line 31) | VersionedWorkflowID = "versioned_workflow"
  constant StopSignalName (line 34) | StopSignalName = "StopSignal"
  constant V1 (line 38) | V1 int32 = iota + 1
  constant V2 (line 39) | V2
  constant V3 (line 40) | V3
  constant V4 (line 41) | V4
  function VersionedWorkflowV1 (line 52) | func VersionedWorkflowV1(ctx workflow.Context) error {
  function VersionedWorkflowV2 (line 65) | func VersionedWorkflowV2(ctx workflow.Context) error {
  function VersionedWorkflowV3 (line 86) | func VersionedWorkflowV3(ctx workflow.Context) error {
  function VersionedWorkflowV4 (line 107) | func VersionedWorkflowV4(ctx workflow.Context) error {
  function waitForSignal (line 119) | func waitForSignal(ctx workflow.Context, version int32) error {
  function SetupHelperForVersionedWorkflowV1 (line 139) | func SetupHelperForVersionedWorkflowV1(h *common.SampleHelper) {
  function SetupHelperForVersionedWorkflowV2 (line 145) | func SetupHelperForVersionedWorkflowV2(h *common.SampleHelper) {
  function SetupHelperForVersionedWorkflowV3 (line 152) | func SetupHelperForVersionedWorkflowV3(h *common.SampleHelper) {
  function SetupHelperForVersionedWorkflowV4 (line 159) | func SetupHelperForVersionedWorkflowV4(h *common.SampleHelper) {
  function FooActivity (line 165) | func FooActivity(ctx context.Context) (string, error) {
  function BarActivity (line 171) | func BarActivity(ctx context.Context) (string, error) {

FILE: cmd/samples/recovery/cache/cache.go
  type Cache (line 7) | type Cache interface
  type Options (line 30) | type Options struct
  type RemovedFunc (line 50) | type RemovedFunc

FILE: cmd/samples/recovery/cache/lru.go
  type lru (line 16) | type lru struct
    method Get (line 57) | func (c *lru) Get(key string) interface{} {
    method Put (line 87) | func (c *lru) Put(key string, value interface{}) interface{} {
    method PutIfNotExist (line 96) | func (c *lru) PutIfNotExist(key string, value interface{}) (interface{...
    method Delete (line 111) | func (c *lru) Delete(key string) {
    method Release (line 126) | func (c *lru) Release(key string) {
    method Size (line 136) | func (c *lru) Size() int {
    method putInternal (line 145) | func (c *lru) putInternal(key string, value interface{}, allowUpdate b...
  function New (line 27) | func New(maxSize int, opts *Options) Cache {
  function NewLRU (line 44) | func NewLRU(maxSize int) Cache {
  function NewLRUWithInitialCapacity (line 50) | func NewLRUWithInitialCapacity(initialCapacity, maxSize int) Cache {
  type cacheEntry (line 201) | type cacheEntry struct

FILE: cmd/samples/recovery/main.go
  function startWorkers (line 19) | func startWorkers(h *common.SampleHelper) {
  function startTripWorkflow (line 48) | func startTripWorkflow(h *common.SampleHelper, workflowID string, user U...
  function startRecoveryWorkflow (line 58) | func startRecoveryWorkflow(h *common.SampleHelper, workflowID string, pa...
  function main (line 68) | func main() {

FILE: cmd/samples/recovery/recovery_workflow.go
  type Params (line 22) | type Params struct
  type ListOpenExecutionsResult (line 29) | type ListOpenExecutionsResult struct
  type RestartParams (line 36) | type RestartParams struct
  type SignalParams (line 42) | type SignalParams struct
  type ClientKey (line 49) | type ClientKey
  constant DomainName (line 53) | DomainName = "default"
  constant CadenceClientKey (line 56) | CadenceClientKey ClientKey = iota
  constant WorkflowExecutionCacheKey (line 58) | WorkflowExecutionCacheKey
  function init (line 74) | func init() {
  function recoverWorkflow (line 81) | func recoverWorkflow(ctx workflow.Context, params Params) error {
  function listOpenExecutions (line 156) | func listOpenExecutions(ctx context.Context, workflowType string) (*List...
  function recoverExecutions (line 187) | func recoverExecutions(ctx context.Context, key string, startIndex, batc...
  function recoverSingleExecution (line 229) | func recoverSingleExecution(ctx context.Context, workflowID string) error {
  function extractStateFromEvent (line 290) | func extractStateFromEvent(workflowID string, event *shared.HistoryEvent...
  function extractSignals (line 315) | func extractSignals(events []*shared.HistoryEvent) ([]*SignalParams, err...
  function isExecutionCompleted (line 339) | func isExecutionCompleted(event *shared.HistoryEvent) bool {
  function getAllExecutionsOfType (line 350) | func getAllExecutionsOfType(ctx context.Context, cadenceClient client.Cl...
  function getHistory (line 382) | func getHistory(ctx context.Context, execution *shared.WorkflowExecution...
  function getCadenceClientFromContext (line 403) | func getCadenceClientFromContext(ctx context.Context) (client.Client, er...

FILE: cmd/samples/recovery/trip_workflow.go
  type UserState (line 12) | type UserState struct
  type TripEvent (line 17) | type TripEvent struct
  constant TripSignalName (line 25) | TripSignalName = "trip_event"
  constant ApplicationName (line 28) | ApplicationName = "recoveryGroup"
  constant QueryName (line 31) | QueryName = "counter"
  function tripWorkflow (line 37) | func tripWorkflow(ctx workflow.Context, state UserState) error {
  function deserializeUserState (line 67) | func deserializeUserState(data []byte) (UserState, error) {
  function deserializeTripEvent (line 76) | func deserializeTripEvent(data []byte) (TripEvent, error) {

FILE: new_samples/activities/dynamic_workflow.go
  constant DynamicGreetingActivityName (line 11) | DynamicGreetingActivityName = "cadence_samples.DynamicGreetingActivity"
  type dynamicWorkflowInput (line 13) | type dynamicWorkflowInput struct
  function DynamicWorkflow (line 17) | func DynamicWorkflow(ctx workflow.Context, input dynamicWorkflowInput) (...
  function DynamicGreetingActivity (line 38) | func DynamicGreetingActivity(ctx context.Context, message string) (strin...

FILE: new_samples/activities/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/activities/main.go
  function main (line 13) | func main() {

FILE: new_samples/activities/parallel_pick_first_workflow.go
  type parallelBranchInput (line 10) | type parallelBranchInput struct
  function ParallelBranchPickFirstWorkflow (line 16) | func ParallelBranchPickFirstWorkflow(ctx workflow.Context) (string, erro...
  function ParallelActivity (line 67) | func ParallelActivity(ctx context.Context, input parallelBranchInput) (s...

FILE: new_samples/activities/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 60) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 92) | func BuildLogger() *zap.Logger {

FILE: new_samples/client_tls/cadence_client.go
  constant HostPort (line 16) | HostPort       = "127.0.0.1:7833"
  constant ClientName (line 17) | ClientName     = "cadence-samples-client"
  constant CadenceService (line 18) | CadenceService = "cadence-frontend"
  function BuildCadenceClient (line 22) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 51) | func BuildLogger() *zap.Logger {

FILE: new_samples/client_tls/main.go
  function main (line 14) | func main() {
  function printUsage (line 33) | func printUsage() {
  function startWorkflow (line 41) | func startWorkflow() {
  function registerDomain (line 90) | func registerDomain() {

FILE: new_samples/client_tls/tls_config.go
  function BuildTLSDialOption (line 15) | func BuildTLSDialOption() (grpc.DialOption, error) {

FILE: new_samples/concurrency/batch_workflow.go
  type BatchWorkflowInput (line 13) | type BatchWorkflowInput struct
  function BatchWorkflow (line 23) | func BatchWorkflow(ctx workflow.Context, input BatchWorkflowInput) error {
  function BatchActivity (line 50) | func BatchActivity(ctx context.Context, taskID int) error {

FILE: new_samples/concurrency/batch_workflow_test.go
  function Test_BatchWorkflow (line 10) | func Test_BatchWorkflow(t *testing.T) {

FILE: new_samples/concurrency/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/concurrency/main.go
  function main (line 13) | func main() {

FILE: new_samples/concurrency/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 58) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 90) | func BuildLogger() *zap.Logger {

FILE: new_samples/data/compressed_dataconverter_workflow.go
  type compressedJSONDataConverter (line 22) | type compressedJSONDataConverter struct
    method ToData (line 29) | func (dc *compressedJSONDataConverter) ToData(value ...interface{}) ([...
    method FromData (line 55) | func (dc *compressedJSONDataConverter) FromData(input []byte, valuePtr...
  function NewCompressedJSONDataConverter (line 25) | func NewCompressedJSONDataConverter() encoded.DataConverter {
  type LargePayload (line 84) | type LargePayload struct
  type Item (line 96) | type Item struct
  type Review (line 107) | type Review struct
  type Inventory (line 119) | type Inventory struct
  type Config (line 126) | type Config struct
  type Limits (line 134) | type Limits struct
  type HistoryEntry (line 142) | type HistoryEntry struct
  type Statistics (line 151) | type Statistics struct
  function CreateLargePayload (line 162) | func CreateLargePayload() LargePayload {
  function GetPayloadSizeInfo (line 265) | func GetPayloadSizeInfo(payload LargePayload, converter encoded.DataConv...
  function CompressionDataConverterWorkflow (line 289) | func CompressionDataConverterWorkflow(ctx workflow.Context) (LargePayloa...
  function CompressionDataConverterActivity (line 320) | func CompressionDataConverterActivity(ctx context.Context, input LargePa...

FILE: new_samples/data/compressed_dataconverter_workflow_test.go
  function Test_CompressionDataConverterWorkflow (line 13) | func Test_CompressionDataConverterWorkflow(t *testing.T) {

FILE: new_samples/data/encrypted_dataconverter_workflow.go
  type encryptedJSONDataConverter (line 27) | type encryptedJSONDataConverter struct
    method ToData (line 73) | func (dc *encryptedJSONDataConverter) ToData(value ...interface{}) ([]...
    method FromData (line 93) | func (dc *encryptedJSONDataConverter) FromData(input []byte, valuePtr ...
  function NewEncryptedJSONDataConverter (line 35) | func NewEncryptedJSONDataConverter(key []byte) (encoded.DataConverter, e...
  function LoadEncryptionKey (line 56) | func LoadEncryptionKey() []byte {
  type SensitiveCustomerRecord (line 119) | type SensitiveCustomerRecord struct
  function CreateSensitiveCustomerRecord (line 134) | func CreateSensitiveCustomerRecord() SensitiveCustomerRecord {
  function GetEncryptionSizeInfo (line 151) | func GetEncryptionSizeInfo(record SensitiveCustomerRecord, converter enc...
  function EncryptionDataConverterWorkflow (line 179) | func EncryptionDataConverterWorkflow(ctx workflow.Context) (SensitiveCus...
  function EncryptionDataConverterActivity (line 206) | func EncryptionDataConverterActivity(ctx context.Context, record Sensiti...

FILE: new_samples/data/encrypted_dataconverter_workflow_test.go
  function Test_EncryptionDataConverterWorkflow (line 13) | func Test_EncryptionDataConverterWorkflow(t *testing.T) {
  function Test_EncryptionRoundTrip (line 40) | func Test_EncryptionRoundTrip(t *testing.T) {
  function Test_EncryptionDifferentEachTime (line 57) | func Test_EncryptionDifferentEachTime(t *testing.T) {
  function Test_NewEncryptedJSONDataConverter_InvalidKey (line 71) | func Test_NewEncryptedJSONDataConverter_InvalidKey(t *testing.T) {

FILE: new_samples/data/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/data/main.go
  function main (line 13) | func main() {

FILE: new_samples/data/s3_dataconverter_workflow.go
  type BlobStore (line 23) | type BlobStore interface
  type localFSBlobStore (line 31) | type localFSBlobStore struct
    method Put (line 51) | func (s *localFSBlobStore) Put(_ context.Context, key string, data []b...
    method Get (line 56) | func (s *localFSBlobStore) Get(_ context.Context, key string) ([]byte,...
  function NewLocalFSBlobStore (line 36) | func NewLocalFSBlobStore() BlobStore {
  function sanitizeKey (line 47) | func sanitizeKey(key string) string {
  type s3Envelope (line 116) | type s3Envelope struct
  constant inlinePrefix (line 122) | inlinePrefix = byte(0x00)
  constant offloadPrefix (line 124) | offloadPrefix = byte(0x01)
  constant defaultThresholdBytes (line 128) | defaultThresholdBytes = 4096
  type s3OffloadDataConverter (line 133) | type s3OffloadDataConverter struct
    method ToData (line 151) | func (dc *s3OffloadDataConverter) ToData(value ...interface{}) ([]byte...
    method FromData (line 192) | func (dc *s3OffloadDataConverter) FromData(input []byte, valuePtr ...i...
  function NewS3OffloadDataConverter (line 143) | func NewS3OffloadDataConverter(store BlobStore, bucket string, threshold...
  type S3LargePayload (line 234) | type S3LargePayload struct
  type S3DataPoint (line 243) | type S3DataPoint struct
  function CreateS3LargePayload (line 251) | func CreateS3LargePayload() S3LargePayload {
  function GetS3OffloadSizeInfo (line 277) | func GetS3OffloadSizeInfo(payload S3LargePayload, thresholdBytes int) (i...
  function S3OffloadDataConverterWorkflow (line 298) | func S3OffloadDataConverterWorkflow(ctx workflow.Context) (S3LargePayloa...
  function S3OffloadDataConverterActivity (line 328) | func S3OffloadDataConverterActivity(ctx context.Context, payload S3Large...

FILE: new_samples/data/s3_dataconverter_workflow_test.go
  type memoryBlobStore (line 16) | type memoryBlobStore struct
    method Put (line 25) | func (m *memoryBlobStore) Put(_ context.Context, key string, data []by...
    method Get (line 32) | func (m *memoryBlobStore) Get(_ context.Context, key string) ([]byte, ...
  function newMemoryBlobStore (line 21) | func newMemoryBlobStore() BlobStore {
  function Test_S3OffloadDataConverterWorkflow (line 42) | func Test_S3OffloadDataConverterWorkflow(t *testing.T) {
  function Test_S3OffloadRoundTrip (line 70) | func Test_S3OffloadRoundTrip(t *testing.T) {
  function Test_S3ReplayIdempotent (line 90) | func Test_S3ReplayIdempotent(t *testing.T) {
  function Test_S3InlineSmallPayload (line 117) | func Test_S3InlineSmallPayload(t *testing.T) {

FILE: new_samples/data/worker.go
  constant HostPort (line 26) | HostPort       = "127.0.0.1:7833"
  constant Domain (line 27) | Domain         = "cadence-samples"
  constant ClientName (line 28) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 29) | CadenceService = "cadence-frontend"
  constant TaskListCompression (line 32) | TaskListCompression = "cadence-samples-data-compression"
  constant TaskListEncryption (line 33) | TaskListEncryption  = "cadence-samples-data-encryption"
  constant TaskListS3 (line 34) | TaskListS3          = "cadence-samples-data-s3"
  function StartWorker (line 38) | func StartWorker() {
  function startCompressionWorker (line 51) | func startCompressionWorker(logger *zap.Logger, cadenceClient workflowse...
  function startEncryptionWorker (line 69) | func startEncryptionWorker(logger *zap.Logger, cadenceClient workflowser...
  function startS3OffloadWorker (line 91) | func startS3OffloadWorker(logger *zap.Logger, cadenceClient workflowserv...
  function printCompressionStats (line 111) | func printCompressionStats() {
  function printEncryptionStats (line 129) | func printEncryptionStats() {
  function printS3OffloadStats (line 151) | func printS3OffloadStats() {
  function BuildCadenceClient (line 169) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 197) | func BuildLogger() *zap.Logger {

FILE: new_samples/hello_world/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/hello_world/main.go
  function main (line 13) | func main() {

FILE: new_samples/hello_world/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 58) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 90) | func BuildLogger() *zap.Logger {

FILE: new_samples/hello_world/workflow.go
  type sampleInput (line 12) | type sampleInput struct
  function HelloWorldWorkflow (line 18) | func HelloWorldWorkflow(ctx workflow.Context, input sampleInput) (string...
  function HelloWorldActivity (line 41) | func HelloWorldActivity(ctx context.Context, input sampleInput) (string,...

FILE: new_samples/operations/cancel_workflow.go
  function CancelWorkflow (line 13) | func CancelWorkflow(ctx workflow.Context) (retError error) {
  function ActivityToBeCanceled (line 57) | func ActivityToBeCanceled(ctx context.Context) (string, error) {
  function CleanupActivity (line 74) | func CleanupActivity(ctx context.Context) error {
  function ActivityToBeSkipped (line 80) | func ActivityToBeSkipped(ctx context.Context) error {

FILE: new_samples/operations/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/operations/main.go
  function main (line 13) | func main() {

FILE: new_samples/operations/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 60) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 92) | func BuildLogger() *zap.Logger {

FILE: new_samples/query/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/query/lunch_vote_workflow.go
  type lunchVoteFormattedResponse (line 13) | type lunchVoteFormattedResponse struct
  function LunchVoteWorkflow (line 21) | func LunchVoteWorkflow(ctx workflow.Context) error {
  function makeLunchVoteResponse (line 56) | func makeLunchVoteResponse(ctx workflow.Context, votes []map[string]stri...
  function makeLunchVoteTable (line 133) | func makeLunchVoteTable(votes []map[string]string) string {
  function makeLunchMenu (line 148) | func makeLunchMenu() string {

FILE: new_samples/query/main.go
  function main (line 13) | func main() {

FILE: new_samples/query/markdown_query.go
  constant CompleteSignalChan (line 16) | CompleteSignalChan = "complete"
  type markdownFormattedResponse (line 20) | type markdownFormattedResponse struct
  function MarkdownQueryWorkflow (line 26) | func MarkdownQueryWorkflow(ctx workflow.Context) error {
  function makeMarkdownQueryResponse (line 66) | func makeMarkdownQueryResponse(ctx workflow.Context) markdownFormattedRe...
  function MarkdownQueryActivity (line 130) | func MarkdownQueryActivity(ctx context.Context, complete bool) (string, ...

FILE: new_samples/query/order_fulfillment_workflow.go
  type orderDashboardFormattedResponse (line 14) | type orderDashboardFormattedResponse struct
  type Order (line 21) | type Order struct
  type OrderItem (line 36) | type OrderItem struct
  type ActionLogEntry (line 43) | type ActionLogEntry struct
  constant StatusPendingPayment (line 52) | StatusPendingPayment  = "pending_payment"
  constant StatusPaymentApproved (line 53) | StatusPaymentApproved = "payment_approved"
  constant StatusReadyToShip (line 54) | StatusReadyToShip     = "ready_to_ship"
  constant StatusShipped (line 55) | StatusShipped         = "shipped"
  constant StatusDelivered (line 56) | StatusDelivered       = "delivered"
  constant StatusCancelled (line 57) | StatusCancelled       = "cancelled"
  constant StatusRefunded (line 58) | StatusRefunded        = "refunded"
  type RejectPaymentSignal (line 62) | type RejectPaymentSignal struct
  type ApprovePaymentSignal (line 67) | type ApprovePaymentSignal struct
  type ShipOrderSignal (line 71) | type ShipOrderSignal struct
  type RefundSignal (line 77) | type RefundSignal struct
  type CancelOrderSignal (line 83) | type CancelOrderSignal struct
  type SimpleSignal (line 88) | type SimpleSignal struct
  function OrderFulfillmentWorkflow (line 94) | func OrderFulfillmentWorkflow(ctx workflow.Context) error {
  function isTerminalState (line 257) | func isTerminalState(status string) bool {
  function getOperator (line 261) | func getOperator(operator string) string {
  function makeOrderDashboard (line 268) | func makeOrderDashboard(ctx workflow.Context, order Order, actionLog []A...
  function getStatusBadge (line 346) | func getStatusBadge(status string) string {
  function makeItemsTable (line 362) | func makeItemsTable(items []OrderItem) string {
  function makeActionButtons (line 371) | func makeActionButtons(ctx workflow.Context, order Order) string {
  function makeActionHistory (line 525) | func makeActionHistory(actionLog []ActionLogEntry) string {

FILE: new_samples/query/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 60) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 92) | func BuildLogger() *zap.Logger {

FILE: new_samples/signal/generator/generate.go
  function main (line 5) | func main() {

FILE: new_samples/signal/main.go
  function main (line 13) | func main() {

FILE: new_samples/signal/simple_signal_workflow.go
  constant CompleteSignalChan (line 13) | CompleteSignalChan = "complete"
  function SimpleSignalWorkflow (line 16) | func SimpleSignalWorkflow(ctx workflow.Context) error {
  function SimpleSignalActivity (line 49) | func SimpleSignalActivity(ctx context.Context, complete bool) (string, e...

FILE: new_samples/signal/worker.go
  constant HostPort (line 24) | HostPort = "127.0.0.1:7833"
  constant Domain (line 25) | Domain   = "cadence-samples"
  constant TaskListName (line 28) | TaskListName   = "cadence-samples-worker"
  constant ClientName (line 29) | ClientName     = "cadence-samples-worker"
  constant CadenceService (line 30) | CadenceService = "cadence-frontend"
  function StartWorker (line 34) | func StartWorker() {
  function BuildCadenceClient (line 58) | func BuildCadenceClient(dialOptions ...grpc.DialOption) workflowservicec...
  function BuildLogger (line 90) | func BuildLogger() *zap.Logger {

FILE: new_samples/template/generator.go
  type TemplateData (line 8) | type TemplateData struct
  function GenerateAll (line 14) | func GenerateAll(data TemplateData) {
  function GenerateWorker (line 21) | func GenerateWorker(data TemplateData) {
  function GenerateMain (line 26) | func GenerateMain(data TemplateData) {
  function GenerateSampleReadMe (line 31) | func GenerateSampleReadMe(data TemplateData) {
  function GenerateGeneratorReadMe (line 36) | func GenerateGeneratorReadMe(data TemplateData) {
  function GenerateFile (line 41) | func GenerateFile(templatePath, outputPath string, data TemplateData) {
  function GenerateREADME (line 59) | func GenerateREADME(inputs []string, outputPath string, data TemplateDat...

FILE: python_sdk_samples/openai_samples/agent_handoffs/book_trip_agent.py
  class BookTripAgentWorkflow (line 9) | class BookTripAgentWorkflow:
    method run (line 12) | async def run(self, input: str) -> str:

FILE: python_sdk_samples/openai_samples/agent_handoffs/main.py
  function main (line 15) | async def main():

FILE: python_sdk_samples/openai_samples/agent_handoffs/tools.py
  class Flight (line 8) | class Flight:
  function book_flight (line 18) | async def book_flight(from_city: str, to_city: str, departure_date: date...
  class UberTrip (line 25) | class UberTrip:
  function book_uber (line 37) | async def book_uber(from_address: str, to_address: str, passengers: int)...
Condensed preview — 233 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (691K chars).
[
  {
    "path": ".gitar/rules/pr-description-quality.md",
    "chars": 4165,
    "preview": "---\ntitle: PR Description Quality Standards\ndescription: Ensures PR descriptions meet quality criteria for the cadence-s"
  },
  {
    "path": ".github/dco.yml",
    "chars": 26,
    "preview": "require:\n  members: false\n"
  },
  {
    "path": ".github/pull_request_guidance.md",
    "chars": 2580,
    "preview": "<!-- List the area(s) touched so reviewers know where to look.\nThis repo has two sample trees: legacy samples under cmd/"
  },
  {
    "path": ".github/pull_request_template.md",
    "chars": 324,
    "preview": "<!-- For guidance on each section, see the PR guidance doc:\n     https://github.com/cadence-workflow/cadence-samples/blo"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 301,
    "preview": "name: Build and test cadence-samples\non: [push, pull_request]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n   "
  },
  {
    "path": ".github/workflows/semantic-pr.yml",
    "chars": 2102,
    "preview": "name: Semantic Pull Request\n\non:\n  pull_request:\n    types:\n      - opened\n      - edited\n      - synchronize\n\njobs:\n  s"
  },
  {
    "path": ".gitignore",
    "chars": 342,
    "preview": "*.out\n*.test\n*.xml\n*.swp\n.idea/\n.vscode/\n*.iml\n*.cov\n*.html\n.tmp/\n.DS_Store\ntest\ntest.log\nvendor/\n# Executables produced"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1856,
    "preview": "# Contributing to Cadence Samples\n\nThis doc is intended for contributors to Cadence samples. Thanks for considering to c"
  },
  {
    "path": "LICENSE",
    "chars": 10254,
    "preview": "Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AN"
  },
  {
    "path": "Makefile",
    "chars": 5651,
    "preview": ".PHONY: test bins clean run-generators\nPROJECT_ROOT = github.com/uber-common/cadence-samples\n\nexport PATH := $(GOPATH)/b"
  },
  {
    "path": "NOTICE",
    "chars": 1081,
    "preview": "Copyright (c) 2025 Uber Technologies, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy"
  },
  {
    "path": "README.md",
    "chars": 20716,
    "preview": "# Cadence Samples ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/uber-common/ca"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/Makefile",
    "chars": 508,
    "preview": "# Makefile for autoscaling monitoring sample\n\n.PHONY: build clean test\n\n# Build the autoscaling monitoring sample\nbuild:"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/README.md",
    "chars": 10751,
    "preview": "# Autoscaling Monitoring Sample\n\nThis sample demonstrates three advanced Cadence worker features:\n\n1. **Worker Poller Au"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/activities.go",
    "chars": 992,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tl"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/config/autoscaling.yaml",
    "chars": 975,
    "preview": "# Configuration for autoscaling monitoring sample\ndomain: \"default\"\nservice: \"cadence-frontend\"\nhost: \"localhost:7833\"\n\n"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/config.go",
    "chars": 5558,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/uber-common/cadence-samples/cmd/samples/common\"\n\t\"github.com/uber-go/t"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/config_test.go",
    "chars": 5511,
    "preview": "package main\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/main.go",
    "chars": 5432,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.o"
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/worker_config.go",
    "chars": 2101,
    "preview": "package main\n\nimport (\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/worker\"\n\t\"go."
  },
  {
    "path": "cmd/samples/advanced/autoscaling-monitoring/workflow.go",
    "chars": 1631,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tautoscalingWorkflowName ="
  },
  {
    "path": "cmd/samples/common/factory.go",
    "chars": 5066,
    "preview": "package common\n\nimport (\n\t\"errors\"\n\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/uber-go/tally\"\n\tapiv1 \"github."
  },
  {
    "path": "cmd/samples/common/sample_helper.go",
    "chars": 10794,
    "preview": "package common\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"time\"\n\n\t\"github.com/opentracing/opentracing-go\"\n\t\"go.uber.org/"
  },
  {
    "path": "cmd/samples/common/util.go",
    "chars": 275,
    "preview": "package common\n\n// StringPtr returns pointer to a string\nfunc StringPtr(v string) *string {\n\treturn &v\n}\n\n// Int32Ptr re"
  },
  {
    "path": "cmd/samples/cron/cron_workflow.go",
    "chars": 2286,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/cron/cron_workflow_test.go",
    "chars": 2319,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/testify/"
  },
  {
    "path": "cmd/samples/cron/main.go",
    "chars": 1927,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/dsl/README.md",
    "chars": 759,
    "preview": "This sample demonstrates how to implement a DSL workflow. In this sample, we provide 2 sample yaml files each defines a "
  },
  {
    "path": "cmd/samples/dsl/activities.go",
    "chars": 867,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc sampleActivity1(input []string) (string, error) {\n\tname := \"sampleActivity1\"\n\tfmt."
  },
  {
    "path": "cmd/samples/dsl/main.go",
    "chars": 2065,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"g"
  },
  {
    "path": "cmd/samples/dsl/workflow.go",
    "chars": 4431,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n// ApplicationName is the task lis"
  },
  {
    "path": "cmd/samples/dsl/workflow1.yaml",
    "chars": 712,
    "preview": "# This sample workflow execute 3 steps in sequence.\n# 1) sampleActivity1, takes arg1 as input, and put result as result1"
  },
  {
    "path": "cmd/samples/dsl/workflow2.yaml",
    "chars": 1864,
    "preview": "# This sample workflow execute 3 steps in sequence.\n# 1) activity1, takes arg1 as input, and put result as result1.\n# 2)"
  },
  {
    "path": "cmd/samples/dsl/workflow_test.go",
    "chars": 9653,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\""
  },
  {
    "path": "cmd/samples/expense/README.md",
    "chars": 1819,
    "preview": "# Expense\nThis sample workflow process an expense request. The key part of this sample is to show how to complete an act"
  },
  {
    "path": "cmd/samples/expense/activities.go",
    "chars": 3098,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"net/url\"\n\n\t\"go.uber.org/cadence/activity\"\n"
  },
  {
    "path": "cmd/samples/expense/main.go",
    "chars": 1579,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/expense/server/dummy.go",
    "chars": 4383,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sort\"\n\n\t\"go.uber.org/cadence/client\"\n\n\t\"github.com/uber-common/ca"
  },
  {
    "path": "cmd/samples/expense/workflow.go",
    "chars": 2021,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\t// ApplicationName is the"
  },
  {
    "path": "cmd/samples/expense/workflow_test.go",
    "chars": 6122,
    "preview": "package main\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testif"
  },
  {
    "path": "cmd/samples/fileprocessing/README.md",
    "chars": 1728,
    "preview": "This sample workflow demos a file processing process. The key part is to show how to use the session API.\n\nThe workflow "
  },
  {
    "path": "cmd/samples/fileprocessing/activities.go",
    "chars": 4480,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go."
  },
  {
    "path": "cmd/samples/fileprocessing/main.go",
    "chars": 1914,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/fileprocessing/workflow.go",
    "chars": 2588,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.u"
  },
  {
    "path": "cmd/samples/fileprocessing/workflow_test.go",
    "chars": 2044,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/acti"
  },
  {
    "path": "cmd/samples/pso/README.md",
    "chars": 1598,
    "preview": "This sample workflow demos a long iterative math optimization process using particle swarm optimization (PSO). \n\nThe wor"
  },
  {
    "path": "cmd/samples/pso/activities.go",
    "chars": 1316,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n)\n\n/**\n * Sample activities used"
  },
  {
    "path": "cmd/samples/pso/dataconverter.go",
    "chars": 4609,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"go.uber.org/cadence/encoded\"\n)\n\n//"
  },
  {
    "path": "cmd/samples/pso/functions.go",
    "chars": 1502,
    "preview": "package main\n\nimport \"math\"\n\ntype ObjectiveFunction struct {\n\tname     string                      // name of the functi"
  },
  {
    "path": "cmd/samples/pso/main.go",
    "chars": 3022,
    "preview": "package main\n\nimport (\n\t\"encoding/gob\"\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.ub"
  },
  {
    "path": "cmd/samples/pso/particle.go",
    "chars": 1465,
    "preview": "package main\n\nimport \"math/rand\"\n\ntype Particle struct {\n\tPosition *Position\n\tPbest    *Position\n\tVelocity Vector\n}\n\nfun"
  },
  {
    "path": "cmd/samples/pso/position.go",
    "chars": 950,
    "preview": "package main\n\nimport (\n\t\"math/rand\"\n)\n\ntype Vector []float64\n\ntype Position struct {\n\tLocation Vector\n\tFitness  float64\n"
  },
  {
    "path": "cmd/samples/pso/settings.go",
    "chars": 1637,
    "preview": "package main\n\nconst pso_max_size int = 100\nconst pso_inertia float64 = 0.7298 // default value of w (see clerc02)\n\ntype "
  },
  {
    "path": "cmd/samples/pso/swarm.go",
    "chars": 3746,
    "preview": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\ntype ParticleR"
  },
  {
    "path": "cmd/samples/pso/utils.go",
    "chars": 225,
    "preview": "package main\n\nimport (\n\t\"math\"\n)\n\nfunc CalculateSwarmSize(dim, max_size int) int {\n\ts := 10. + 2.*math.Sqrt(float64(dim)"
  },
  {
    "path": "cmd/samples/pso/workflow.go",
    "chars": 4267,
    "preview": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence"
  },
  {
    "path": "cmd/samples/pso/workflow_test.go",
    "chars": 2306,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"g"
  },
  {
    "path": "cmd/samples/recipes/branch/branch_workflow.go",
    "chars": 1282,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n)\n\n/**\n * This sample workflow executes multiple "
  },
  {
    "path": "cmd/samples/recipes/branch/main.go",
    "chars": 2023,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/branch/parallel_workflow.go",
    "chars": 1648,
    "preview": "package main\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This sample workf"
  },
  {
    "path": "cmd/samples/recipes/branch/workflow_test.go",
    "chars": 935,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/testsuite\"\n)\n\ntype UnitTes"
  },
  {
    "path": "cmd/samples/recipes/cancelactivity/main.go",
    "chars": 1762,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/cancelactivity/workflow.go",
    "chars": 2791,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/c"
  },
  {
    "path": "cmd/samples/recipes/cancelactivity/workflow_test.go",
    "chars": 1729,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.u"
  },
  {
    "path": "cmd/samples/recipes/childworkflow/child_workflow.go",
    "chars": 1139,
    "preview": "package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This sample workfl"
  },
  {
    "path": "cmd/samples/recipes/childworkflow/main.go",
    "chars": 1447,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/childworkflow/parent_workflow.go",
    "chars": 1380,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This sample workflow"
  },
  {
    "path": "cmd/samples/recipes/choice/exclusive_choice_workflow.go",
    "chars": 2179,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This sa"
  },
  {
    "path": "cmd/samples/recipes/choice/main.go",
    "chars": 2296,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/choice/multi_choice_workflow.go",
    "chars": 2040,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"github.com/pkg/errors\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.ub"
  },
  {
    "path": "cmd/samples/recipes/choice/workflow_test.go",
    "chars": 1176,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/testsuite\"\n)\n\ntype UnitTes"
  },
  {
    "path": "cmd/samples/recipes/consistentquery/README.md",
    "chars": 660,
    "preview": "This sample workflow demos how to use consistent query API to get the current state of running workflow.\n\nquery_workflow"
  },
  {
    "path": "cmd/samples/recipes/consistentquery/main.go",
    "chars": 2097,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/ca"
  },
  {
    "path": "cmd/samples/recipes/consistentquery/query_workflow.go",
    "chars": 1232,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n// ApplicationName is the task lis"
  },
  {
    "path": "cmd/samples/recipes/crossdomain/main.go",
    "chars": 3803,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"github.com/google/uuid\"\n\tapiv1 \"github.com/uber/cadence-idl/go/proto/api/v1\""
  },
  {
    "path": "cmd/samples/recipes/crossdomain/wf.go",
    "chars": 3012,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"github.com/google/uuid\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workfl"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/README.md",
    "chars": 1016,
    "preview": "This sample workflow demos context propagation through a workflow. Details about context propagation are\navailable [here"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/activities.go",
    "chars": 261,
    "preview": "package main\n\nimport (\n\t\"context\"\n)\n\nconst (\n\tsampleActivityName = \"sampleActivity\"\n)\n\nfunc sampleActivity(ctx context.C"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/main.go",
    "chars": 1951,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.or"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/propagator.go",
    "chars": 2833,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\n\t\"go.uber.org/cadence/.gen/go/shared\"\n\t\"go.uber.org/cadence/workflow"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/workflow.go",
    "chars": 1097,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n// ApplicationName is the task lis"
  },
  {
    "path": "cmd/samples/recipes/ctxpropagation/workflow_test.go",
    "chars": 2216,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/.gen/go/shared\""
  },
  {
    "path": "cmd/samples/recipes/delaystart/delaystart_workflow.go",
    "chars": 2186,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/recipes/delaystart/delaystart_workflow_test.go",
    "chars": 821,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.u"
  },
  {
    "path": "cmd/samples/recipes/delaystart/main.go",
    "chars": 2326,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/dynamic/dynamic_workflow.go",
    "chars": 2271,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * The purpose of this "
  },
  {
    "path": "cmd/samples/recipes/dynamic/main.go",
    "chars": 1622,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/dynamic/workflow_test.go",
    "chars": 1045,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/c"
  },
  {
    "path": "cmd/samples/recipes/greetings/greetings.json",
    "chars": 10005,
    "preview": "[\n  {\n    \"eventId\": 1,\n    \"timestamp\": 1678403666710299250,\n    \"eventType\": \"WorkflowExecutionStarted\",\n    \"version\""
  },
  {
    "path": "cmd/samples/recipes/greetings/greetings_workflow.go",
    "chars": 1860,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This greetings sampl"
  },
  {
    "path": "cmd/samples/recipes/greetings/main.go",
    "chars": 1528,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/greetings/replay_test.go",
    "chars": 810,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/cadence/worker\"\n\t\"go.uber.org/zap/zaptest\"\n\n\t\"github.com/stretchr/testi"
  },
  {
    "path": "cmd/samples/recipes/greetings/shadow_test.go",
    "chars": 1265,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/worker\"\n\t\"go.ube"
  },
  {
    "path": "cmd/samples/recipes/greetings/workflow_test.go",
    "chars": 1713,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go."
  },
  {
    "path": "cmd/samples/recipes/helloworld/activity_logger_test.go",
    "chars": 1306,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/c"
  },
  {
    "path": "cmd/samples/recipes/helloworld/helloworld.json",
    "chars": 4355,
    "preview": "[\n  {\n    \"eventId\":1,\n    \"timestamp\":1558126752505445000,\n    \"eventType\":\"WorkflowExecutionStarted\",\n    \"version\":-2"
  },
  {
    "path": "cmd/samples/recipes/helloworld/helloworld_workflow.go",
    "chars": 2021,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/recipes/helloworld/helloworld_workflow_test.go",
    "chars": 747,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/"
  },
  {
    "path": "cmd/samples/recipes/helloworld/main.go",
    "chars": 2246,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/helloworld/replay_test.go",
    "chars": 809,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/cadence/worker\"\n\t\"go.uber.org/zap/zaptest\"\n\n\t\"github.com/stretchr/testi"
  },
  {
    "path": "cmd/samples/recipes/helloworld/shadow_test.go",
    "chars": 1254,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/worker\"\n\t\"go.ube"
  },
  {
    "path": "cmd/samples/recipes/localactivity/README.md",
    "chars": 1196,
    "preview": "This sample workflow demos how to use local activity to execute short/quick operations efficiently.\n\nlocal_activity_work"
  },
  {
    "path": "cmd/samples/recipes/localactivity/local_activity_workflow.go",
    "chars": 5732,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.o"
  },
  {
    "path": "cmd/samples/recipes/localactivity/local_activity_workflow_test.go",
    "chars": 2405,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/testify/suite\"\n\t\"go"
  },
  {
    "path": "cmd/samples/recipes/localactivity/main.go",
    "chars": 1956,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/mutex/README.md",
    "chars": 1499,
    "preview": "This mutex workflow demos an ability to lock/unlock a particular resource within a particular cadence domain\nso that oth"
  },
  {
    "path": "cmd/samples/recipes/mutex/main.go",
    "chars": 2227,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.or"
  },
  {
    "path": "cmd/samples/recipes/mutex/mutex_workflow.go",
    "chars": 6876,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"go.uber.org/cadence\"\n\t\"go.uber.o"
  },
  {
    "path": "cmd/samples/recipes/mutex/mutex_workflow_test.go",
    "chars": 2950,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretch"
  },
  {
    "path": "cmd/samples/recipes/pickfirst/main.go",
    "chars": 1462,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/pickfirst/pickfirst_workflow.go",
    "chars": 2999,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n)\n\n/**"
  },
  {
    "path": "cmd/samples/recipes/pickfirst/pickfirst_workflow_test.go",
    "chars": 1174,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/testify/"
  },
  {
    "path": "cmd/samples/recipes/query/README.md",
    "chars": 1112,
    "preview": "This sample workflow demos how to use query API to get the current state of running workflow.\n\nquery_workflow.go shows h"
  },
  {
    "path": "cmd/samples/recipes/query/main.go",
    "chars": 1642,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/query/query_workflow.go",
    "chars": 968,
    "preview": "package main\n\nimport (\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n)\n\n// ApplicationName is the task list for this sample\nc"
  },
  {
    "path": "cmd/samples/recipes/query/query_workflow_test.go",
    "chars": 887,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/testsuite\"\n)\n\nfu"
  },
  {
    "path": "cmd/samples/recipes/retryactivity/main.go",
    "chars": 1428,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/retryactivity/retry_activity_workflow.go",
    "chars": 2974,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/"
  },
  {
    "path": "cmd/samples/recipes/retryactivity/retry_activity_workflow_test.go",
    "chars": 1404,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/testify/"
  },
  {
    "path": "cmd/samples/recipes/searchattributes/README.md",
    "chars": 613,
    "preview": "This sample shows how to use search attributes. (Note this feature only works when running Cadence with ElasticSearch)\n\n"
  },
  {
    "path": "cmd/samples/recipes/searchattributes/main.go",
    "chars": 2019,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.or"
  },
  {
    "path": "cmd/samples/recipes/searchattributes/searchattributes_workflow.go",
    "chars": 5104,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/.gen/go/shared\"\n\t\""
  },
  {
    "path": "cmd/samples/recipes/searchattributes/searchattributes_workflow_test.go",
    "chars": 1459,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/testify/require\"\n\t\""
  },
  {
    "path": "cmd/samples/recipes/sideeffect/sideeffect_workflow.go",
    "chars": 2492,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence"
  },
  {
    "path": "cmd/samples/recipes/signalcounter/main.go",
    "chars": 1781,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/signalcounter/signal_counter_workflow.go",
    "chars": 1926,
    "preview": "package main\n\nimport (\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\n/**\n * This sample workflow continuously co"
  },
  {
    "path": "cmd/samples/recipes/signalcounter/workflow_test.go",
    "chars": 1107,
    "preview": "package main\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/testsuite\"\n\t\"go"
  },
  {
    "path": "cmd/samples/recipes/sleep/README.md",
    "chars": 2393,
    "preview": "# Sleep Workflow Sample\n\nThis sample workflow demonstrates how to use the `workflow.Sleep` function in Cadence workflows"
  },
  {
    "path": "cmd/samples/recipes/sleep/main.go",
    "chars": 1469,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/sleep/sleep_workflow.go",
    "chars": 1439,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/recipes/sleep/sleep_workflow_test.go",
    "chars": 798,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.u"
  },
  {
    "path": "cmd/samples/recipes/splitmerge/main.go",
    "chars": 1458,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/splitmerge/splitmerge_workflow.go",
    "chars": 2231,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/recipes/splitmerge/splitmerge_workflow_test.go",
    "chars": 1008,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/suite\"\n\t\"go.uber.org/cadence/testsuite\"\n)\n\ntype UnitTes"
  },
  {
    "path": "cmd/samples/recipes/timer/main.go",
    "chars": 1537,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/w"
  },
  {
    "path": "cmd/samples/recipes/timer/workflow.go",
    "chars": 2548,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n"
  },
  {
    "path": "cmd/samples/recipes/timer/workflow_test.go",
    "chars": 1752,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/mock\"\n\t\"github.com/stretchr/"
  },
  {
    "path": "cmd/samples/recipes/tracing/helloworld_workflow.go",
    "chars": 1212,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org"
  },
  {
    "path": "cmd/samples/recipes/tracing/main.go",
    "chars": 2486,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/opentracing/opentracing-go\"\n\t\"github.com/pborman/uuid\""
  },
  {
    "path": "cmd/samples/recipes/versioning/README.md",
    "chars": 6101,
    "preview": "# Versioning Workflow Example\n\nThis example demonstrates how to safely deploy versioned workflows using Cadence's versio"
  },
  {
    "path": "cmd/samples/recipes/versioning/main.go",
    "chars": 2687,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/worker\"\n\n\t\"gith"
  },
  {
    "path": "cmd/samples/recipes/versioning/versioned_workflow.go",
    "chars": 5730,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"github.com/uber-common/cadence-samples/cmd/samples/common\"\n\t\"go.uber.org/cadence/act"
  },
  {
    "path": "cmd/samples/recovery/README.md",
    "chars": 925,
    "preview": "### Recovery Sample\nThis sample implements a RecoveryWorkflow which is designed to restart all TripWorkflow executions w"
  },
  {
    "path": "cmd/samples/recovery/cache/cache.go",
    "chars": 1631,
    "preview": "package cache\n\nimport \"time\"\n\n// A Cache is a generalized interface to a cache.  See cache.LRU for a specific\n// impleme"
  },
  {
    "path": "cmd/samples/recovery/cache/lru.go",
    "chars": 4544,
    "preview": "package cache\n\nimport (\n\t\"container/list\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\t// ErrCacheFull is returned if Put fails d"
  },
  {
    "path": "cmd/samples/recovery/main.go",
    "chars": 3644,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/client\"\n\t\"go.uber.org/cadence/"
  },
  {
    "path": "cmd/samples/recovery/recovery_workflow.go",
    "chars": 12080,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/pborman/uuid\"\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cad"
  },
  {
    "path": "cmd/samples/recovery/trip_workflow.go",
    "chars": 2240,
    "preview": "package main\n\nimport (\n\t\"encoding/json\"\n\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n)\n\ntype (\n\t// UserState kept"
  },
  {
    "path": "config/development.yaml",
    "chars": 175,
    "preview": "# config for sample\ndomain: \"cadence-samples\"\nservice: \"cadence-frontend\"\nhost: \"localhost:7833\"\n# config for emitting m"
  },
  {
    "path": "go.mod",
    "chars": 3113,
    "preview": "module github.com/uber-common/cadence-samples\n\ngo 1.21\n\ntoolchain go1.24.2\n\nrequire (\n\tgithub.com/google/uuid v1.3.0\n\tgi"
  },
  {
    "path": "go.sum",
    "chars": 41875,
    "preview": "cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=\ncloud.google.com/go v0.34.0/go.mod h1"
  },
  {
    "path": "k8s/README.md",
    "chars": 3900,
    "preview": "# Cadence Samples Usage Guide\n\nThis guide explains how to build, deploy, and use the Cadence samples container for testi"
  },
  {
    "path": "k8s/cadence-samples-pod.yaml",
    "chars": 676,
    "preview": "apiVersion: v1\nkind: Pod\nmetadata:\n  name: cadence-samples\n  namespace: cadence # Replace with your cadence namespace\n  "
  },
  {
    "path": "k8s/docker/Dockerfile",
    "chars": 845,
    "preview": "FROM golang:1.21-alpine\n\n# Install all necessary dependencies for building and running\nRUN apk add --no-cache git make g"
  },
  {
    "path": "new_samples/README.md",
    "chars": 4160,
    "preview": "# Cadence Samples\n\nThis directory contains samples demonstrating various Cadence workflow concepts. Each sample is self-"
  },
  {
    "path": "new_samples/activities/README.md",
    "chars": 2785,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Activities Sample\n\n## Prerequisites\n\n0. Install Cadence"
  },
  {
    "path": "new_samples/activities/dynamic_workflow.go",
    "chars": 1135,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/zap\"\n\t\"t"
  },
  {
    "path": "new_samples/activities/generator/README.md",
    "chars": 1611,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Sample Generator\n\nThis folder is NOT part of the actual"
  },
  {
    "path": "new_samples/activities/generator/README_specific.md",
    "chars": 1499,
    "preview": "## Samples in this folder\n\nThis folder contains samples demonstrating various activity patterns in Cadence.\n\n### Dynamic"
  },
  {
    "path": "new_samples/activities/generator/generate.go",
    "chars": 421,
    "preview": "package main\n\nimport \"github.com/uber-common/cadence-samples/new_samples/template\"\n\nfunc main() {\n\t// Define the data fo"
  },
  {
    "path": "new_samples/activities/main.go",
    "chars": 293,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc m"
  },
  {
    "path": "new_samples/activities/parallel_pick_first_workflow.go",
    "chars": 2535,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"time\"\n)\n\ntype parall"
  },
  {
    "path": "new_samples/activities/worker.go",
    "chars": 3328,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\n// Package worker implements a Cadence worker with basic configuratio"
  },
  {
    "path": "new_samples/client_tls/README.md",
    "chars": 1782,
    "preview": "# Client TLS Sample\n\nThis sample demonstrates how to connect to a Cadence server using TLS (Transport Layer Security) fo"
  },
  {
    "path": "new_samples/client_tls/cadence_client.go",
    "chars": 1688,
    "preview": "package main\n\nimport (\n\tapiv1 \"github.com/uber/cadence-idl/go/proto/api/v1\"\n\t\"go.uber.org/cadence/.gen/go/cadence/workfl"
  },
  {
    "path": "new_samples/client_tls/main.go",
    "chars": 3140,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"go.uber.org/cadence/.gen/go/shared\"\n"
  },
  {
    "path": "new_samples/client_tls/tls_config.go",
    "chars": 1211,
    "preview": "package main\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"go.uber.org/yarpc/transport/grpc\"\n\t\"google.golang.or"
  },
  {
    "path": "new_samples/concurrency/README.md",
    "chars": 3542,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Concurrency Sample\n\n## Prerequisites\n\n0. Install Cadenc"
  },
  {
    "path": "new_samples/concurrency/batch_workflow.go",
    "chars": 2045,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n\n\t\"go.uber.org/cadence/workflow\"\n)\n\n// BatchWorkflowInput "
  },
  {
    "path": "new_samples/concurrency/batch_workflow_test.go",
    "chars": 722,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/cadence/testsuite\"\n)\n\nfunc Test_B"
  },
  {
    "path": "new_samples/concurrency/generator/README.md",
    "chars": 1611,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Sample Generator\n\nThis folder is NOT part of the actual"
  },
  {
    "path": "new_samples/concurrency/generator/README_specific.md",
    "chars": 2255,
    "preview": "## Samples in this folder\n\nThis folder contains samples demonstrating concurrency control patterns in Cadence.\n\n### Batc"
  },
  {
    "path": "new_samples/concurrency/generator/generate.go",
    "chars": 356,
    "preview": "package main\n\nimport \"github.com/uber-common/cadence-samples/new_samples/template\"\n\nfunc main() {\n\t// Define the data fo"
  },
  {
    "path": "new_samples/concurrency/main.go",
    "chars": 293,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc m"
  },
  {
    "path": "new_samples/concurrency/worker.go",
    "chars": 3040,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\n// Package worker implements a Cadence worker with basic configuratio"
  },
  {
    "path": "new_samples/data/README.md",
    "chars": 7371,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Data Sample\n\n## Prerequisites\n\n0. Install Cadence CLI. "
  },
  {
    "path": "new_samples/data/compressed_dataconverter_workflow.go",
    "chars": 11738,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n"
  },
  {
    "path": "new_samples/data/compressed_dataconverter_workflow_test.go",
    "chars": 1151,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/"
  },
  {
    "path": "new_samples/data/encrypted_dataconverter_workflow.go",
    "chars": 8014,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"encoding/json"
  },
  {
    "path": "new_samples/data/encrypted_dataconverter_workflow_test.go",
    "chars": 2413,
    "preview": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/"
  },
  {
    "path": "new_samples/data/generator/README.md",
    "chars": 1611,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Sample Generator\n\nThis folder is NOT part of the actual"
  },
  {
    "path": "new_samples/data/generator/README_specific.md",
    "chars": 6091,
    "preview": "## Data Converter Samples\n\nThis folder demonstrates three production-ready patterns for custom `DataConverter` implement"
  },
  {
    "path": "new_samples/data/generator/generate.go",
    "chars": 928,
    "preview": "package main\n\nimport \"github.com/uber-common/cadence-samples/new_samples/template\"\n\nfunc main() {\n\t// Define the data fo"
  },
  {
    "path": "new_samples/data/main.go",
    "chars": 293,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc m"
  },
  {
    "path": "new_samples/data/s3_dataconverter_workflow.go",
    "chars": 12533,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/sha256\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\""
  },
  {
    "path": "new_samples/data/s3_dataconverter_workflow_test.go",
    "chars": 4375,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/cadence/activ"
  },
  {
    "path": "new_samples/data/worker.go",
    "chars": 8516,
    "preview": "// Custom worker.go for Data samples - NOT generated\n// This sample requires custom DataConverters in worker options, on"
  },
  {
    "path": "new_samples/hello_world/README.md",
    "chars": 4155,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Hello World Sample\n\n## Prerequisites\n\n0. Install Cadenc"
  },
  {
    "path": "new_samples/hello_world/generator/README.md",
    "chars": 1611,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Sample Generator\n\nThis folder is NOT part of the actual"
  },
  {
    "path": "new_samples/hello_world/generator/README_specific.md",
    "chars": 2868,
    "preview": "### Start your workflow\n\nThis workflow takes an input message and greet you as response. Try the following CLI\n\n```bash\n"
  },
  {
    "path": "new_samples/hello_world/generator/generate.go",
    "chars": 356,
    "preview": "package main\n\nimport \"github.com/uber-common/cadence-samples/new_samples/template\"\n\nfunc main() {\n\t// Define the data fo"
  },
  {
    "path": "new_samples/hello_world/main.go",
    "chars": 293,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc m"
  },
  {
    "path": "new_samples/hello_world/worker.go",
    "chars": 3071,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\n// Package worker implements a Cadence worker with basic configuratio"
  },
  {
    "path": "new_samples/hello_world/workflow.go",
    "chars": 1235,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/workflow\"\n\t\"go.uber.org/z"
  },
  {
    "path": "new_samples/operations/README.md",
    "chars": 2495,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Operations Sample\n\n## Prerequisites\n\n0. Install Cadence"
  },
  {
    "path": "new_samples/operations/cancel_workflow.go",
    "chars": 2549,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go.uber.org/cadence\"\n\t\"go.uber.org/cadence/activity\"\n\t\"go.uber.org/cadence/wo"
  },
  {
    "path": "new_samples/operations/generator/README.md",
    "chars": 1611,
    "preview": "<!-- THIS IS A GENERATED FILE -->\n<!-- PLEASE DO NOT EDIT -->\n\n# Sample Generator\n\nThis folder is NOT part of the actual"
  },
  {
    "path": "new_samples/operations/generator/README_specific.md",
    "chars": 1209,
    "preview": "## Samples in this folder\n\nThis folder contains samples demonstrating workflow operations and lifecycle management in Ca"
  },
  {
    "path": "new_samples/operations/generator/generate.go",
    "chars": 404,
    "preview": "package main\n\nimport \"github.com/uber-common/cadence-samples/new_samples/template\"\n\nfunc main() {\n\t// Define the data fo"
  },
  {
    "path": "new_samples/operations/main.go",
    "chars": 293,
    "preview": "// THIS IS A GENERATED FILE\n// PLEASE DO NOT EDIT\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\nfunc m"
  }
]

// ... and 33 more files (download for full content)

About this extraction

This page contains the full source code of the uber-common/cadence-samples GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 233 files (617.6 KB), approximately 174.8k tokens, and a symbol index with 812 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!