-
Notifications
You must be signed in to change notification settings - Fork 148
add infrequent polling sample, with benign application failure #422
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| node_modules | ||
| coverage | ||
| jest.config.js | ||
| lib | ||
| .eslintrc.js |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| const { builtinModules } = require('module'); | ||
|
|
||
| const ALLOWED_NODE_BUILTINS = new Set(['assert']); | ||
|
|
||
| module.exports = { | ||
| root: true, | ||
| parser: '@typescript-eslint/parser', | ||
| parserOptions: { | ||
| project: './tsconfig.json', | ||
| tsconfigRootDir: __dirname, | ||
| }, | ||
| plugins: ['@typescript-eslint', 'deprecation'], | ||
| extends: [ | ||
| 'eslint:recommended', | ||
| 'plugin:@typescript-eslint/eslint-recommended', | ||
| 'plugin:@typescript-eslint/recommended', | ||
| 'prettier', | ||
| ], | ||
| rules: { | ||
| // recommended for safety | ||
| '@typescript-eslint/no-floating-promises': 'error', // forgetting to await Activities and Workflow APIs is bad | ||
| 'deprecation/deprecation': 'warn', | ||
|
|
||
| // code style preference | ||
| 'object-shorthand': ['error', 'always'], | ||
|
|
||
| // relaxed rules, for convenience | ||
| '@typescript-eslint/no-unused-vars': [ | ||
| 'warn', | ||
| { | ||
| argsIgnorePattern: '^_', | ||
| varsIgnorePattern: '^_', | ||
| }, | ||
| ], | ||
| '@typescript-eslint/no-explicit-any': 'off', | ||
| }, | ||
| overrides: [ | ||
| { | ||
| files: ['src/workflows.ts', 'src/workflows-*.ts', 'src/workflows/*.ts'], | ||
| rules: { | ||
| 'no-restricted-imports': [ | ||
| 'error', | ||
| ...builtinModules.filter((m) => !ALLOWED_NODE_BUILTINS.has(m)).flatMap((m) => [m, `node:${m}`]), | ||
| ], | ||
| }, | ||
| }, | ||
| ], | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| lib | ||
| node_modules |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| package-lock=false |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| 22 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| To begin development, install the Temporal CLI: | ||
|
|
||
| Mac: {cyan brew install temporal} | ||
| Other: Download and extract the latest release from https://github.com/temporalio/cli/releases/latest | ||
|
|
||
| Start Temporal Server: | ||
|
|
||
| {cyan temporal server start-dev} | ||
|
|
||
| Use Node version 18+ (v22.x is recommended): | ||
|
|
||
| Mac: {cyan brew install node@22} | ||
| Other: https://nodejs.org/en/download/ | ||
|
|
||
| Then, in the project directory, using two other shells, run these commands: | ||
|
|
||
| {cyan npm run start.watch} | ||
| {cyan npm run workflow} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| lib |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| printWidth: 120 | ||
| singleQuote: true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # Frequently Polling Activity | ||
|
|
||
| This sample shows how we can implement frequent polling (1 second or faster) inside our Activity. The implementation is a loop that polls our service and then sleeps for the poll interval (1 second in the sample). | ||
|
|
||
| To ensure that polling Activity is restarted in a timely manner, we make sure that it heartbeats on every iteration. Note that heartbeating only works if we set the `heartbeat_timeout` to a shorter value than the Activity `start_to_close_timeout` timeout. | ||
|
|
||
| To run, first see [README.md](../../README.md) for prerequisites. | ||
|
|
||
| The Workflow will continue to poll the service and heartbeat on every iteration until it succeeds. | ||
|
|
||
| Note that with frequent polling, the Activity may execute for a long time, and it may be beneficial to set a Timeout on the Activity to avoid long-running Activities that are not heartbeating. | ||
|
|
||
| If the polling interval needs to be changed during runtime, the Activity needs to be canceled and a new instance with the updated arguments needs to be started. | ||
|
|
||
| ### Testing | ||
|
|
||
| - Jest: `npm run test`: | ||
| - [`src/test/workflows.test.ts`](./src/test/workflows.test.ts) | ||
|
|
||
| ### Running this sample | ||
|
|
||
| 1. `temporal server start-dev` to start [Temporal Server](https://github.com/temporalio/cli/#installation). | ||
| 2. `npm install` to install dependencies. | ||
| 3. `npm run start.watch` to start the Worker. | ||
| 4. In another shell, `npm run workflow` to run the Workflow Client. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ | ||
| module.exports = { | ||
| preset: 'ts-jest', | ||
| testEnvironment: 'node', | ||
| modulePathIgnorePatterns: ['lib'], | ||
| clearMocks: true, | ||
| collectCoverage: true, | ||
| coverageDirectory: 'coverage', | ||
| coveragePathIgnorePatterns: ['/node_modules/', '/lib/'], | ||
| coverageProvider: 'babel', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| { | ||
| "name": "temporal-polling-frequent", | ||
| "version": "0.1.0", | ||
| "private": true, | ||
| "scripts": { | ||
| "build": "tsc --build", | ||
| "build.watch": "tsc --build --watch", | ||
| "format": "prettier --write .", | ||
| "format:check": "prettier --check .", | ||
| "lint": "eslint .", | ||
| "start": "ts-node src/worker.ts", | ||
| "start.watch": "nodemon src/worker.ts", | ||
| "test": "jest", | ||
| "workflow": "ts-node src/client.ts" | ||
| }, | ||
| "nodemonConfig": { | ||
| "execMap": { | ||
| "ts": "ts-node" | ||
| }, | ||
| "ext": "ts", | ||
| "watch": [ | ||
| "src" | ||
| ] | ||
| }, | ||
| "dependencies": { | ||
| "@temporalio/activity": "^1.12.0", | ||
| "@temporalio/client": "^1.12.0", | ||
| "@temporalio/worker": "^1.12.0", | ||
| "@temporalio/workflow": "^1.12.0", | ||
| "nanoid": "3.x" | ||
| }, | ||
| "devDependencies": { | ||
| "@temporalio/testing": "^1.12.0", | ||
| "@tsconfig/node18": "^18.2.4", | ||
| "@types/jest": "^29.5.14", | ||
| "@types/mocha": "8.x", | ||
| "@types/node": "^22.9.1", | ||
| "@typescript-eslint/eslint-plugin": "^8.18.0", | ||
| "@typescript-eslint/parser": "^8.18.0", | ||
| "eslint": "^8.57.1", | ||
| "eslint-config-prettier": "^9.1.0", | ||
| "eslint-plugin-deprecation": "^3.0.0", | ||
| "jest": "^29.7.0", | ||
| "nodemon": "^3.1.7", | ||
| "prettier": "^3.4.2", | ||
| "ts-jest": "^29.2.5", | ||
| "ts-node": "^10.9.2", | ||
| "typescript": "^5.6.3" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import { ComposeGreetingInput, getServiceResult } from "./service"; | ||
| import { | ||
| ApplicationFailure, | ||
| ApplicationFailureCategory, | ||
| } from '@temporalio/common'; | ||
|
|
||
| export async function composeGreeting(input: ComposeGreetingInput): Promise<string> { | ||
| try { | ||
| return await getServiceResult(input); | ||
| } catch (err) { | ||
| const message = err instanceof Error ? err.message : String(err); | ||
| throw ApplicationFailure.create({ | ||
| message, | ||
| // Set the error as BENIGN to indicate it is an expected error. | ||
| // BENIGN errors have activity failure logs downgraded to DEBUG level | ||
| // and do not emit activity failure metrics. | ||
| category: ApplicationFailureCategory.BENIGN, | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| // @@@SNIPSTART typescript-polling-infrequent | ||
| import { Connection, Client } from '@temporalio/client'; | ||
| import { greetingWorkflow } from './workflows'; | ||
| import { nanoid } from 'nanoid'; | ||
|
|
||
| async function run() { | ||
| const connection = await Connection.connect({ address: 'localhost:7233' }); | ||
| const client = new Client({ connection }); | ||
|
|
||
| const handle = await client.workflow.start(greetingWorkflow, { | ||
| taskQueue: 'infrequent-activity-polling-task-queue', | ||
| workflowId: 'workflow-' + nanoid(), | ||
| args: ["Temporal"], | ||
| }); | ||
| console.log(`Started workflow ${handle.workflowId}`); | ||
|
|
||
| console.log(await handle.result()); | ||
| } | ||
|
|
||
| run().catch((err) => { | ||
| console.error(err); | ||
| process.exit(1); | ||
| }); | ||
| // @@@SNIPEND |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| import { activityInfo } from '@temporalio/activity'; | ||
|
|
||
| export interface ComposeGreetingInput { | ||
| greeting: string; | ||
| name: string; | ||
| } | ||
|
|
||
| const ERROR_ATTEMPTS = 5 | ||
| const attempts = new Map<string, number> (); | ||
|
|
||
| export async function getServiceResult(input: ComposeGreetingInput): Promise<string> { | ||
| const workflowId = activityInfo().workflowExecution.workflowId; | ||
| const currentCount = attempts.get(workflowId) ?? 0; | ||
| attempts.set(workflowId, currentCount + 1); | ||
|
|
||
| console.log(`Attempt ${attempts.get(workflowId)} of ${ERROR_ATTEMPTS} to invoke service`); | ||
| if (attempts.get(workflowId) === ERROR_ATTEMPTS) { | ||
| return `${input.greeting}, ${input.name}!` | ||
| } | ||
| throw new Error("service is down"); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { TestWorkflowEnvironment } from '@temporalio/testing'; | ||
| import { Worker } from '@temporalio/worker'; | ||
| import * as activities from '../activities'; | ||
| import type * as activitiesType from '../activities'; | ||
| import { greetingWorkflow } from '../workflows'; | ||
| import { nanoid } from 'nanoid'; | ||
|
|
||
| describe('frequent polling workflow', function () { | ||
| let testEnv: TestWorkflowEnvironment; | ||
| const taskQueue = 'frequent-activity-polling-task-queue'; | ||
|
|
||
| beforeAll(async () => { | ||
| testEnv = await TestWorkflowEnvironment.createLocal(); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await testEnv?.teardown(); | ||
| }); | ||
|
|
||
| it('runs returns expected greeting', async () => { | ||
| const { client, nativeConnection } = testEnv; | ||
|
|
||
| const mockActivities: typeof activitiesType = { | ||
| composeGreeting: jest.fn(activities.composeGreeting), | ||
| }; | ||
|
|
||
| const worker = await Worker.create({ | ||
| connection: nativeConnection, | ||
| workflowsPath: require.resolve('../workflows'), | ||
| activities: mockActivities, | ||
| taskQueue, | ||
| }); | ||
|
|
||
| expect(mockActivities.composeGreeting).toHaveBeenCalledTimes(0); | ||
|
|
||
| const result = await worker.runUntil( | ||
| client.workflow.execute(greetingWorkflow, { | ||
| args: ['Temporal'], | ||
| workflowId: nanoid(), | ||
| taskQueue, | ||
| }), | ||
| ); | ||
|
|
||
| assert.equal(result, 'Hello, Temporal!'); | ||
| // Check that the activity isn't being retried. The recurring polling is | ||
| // happeing within the activity. | ||
| expect(mockActivities.composeGreeting).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| // @@@SNIPSTART typescript-polling-infrequent | ||
| import { NativeConnection, Worker } from '@temporalio/worker'; | ||
| import * as activities from './activities'; | ||
|
|
||
| async function run() { | ||
| const connection = await NativeConnection.connect({ | ||
| address: 'localhost:7233', | ||
| }); | ||
| try { | ||
| const worker = await Worker.create({ | ||
| connection, | ||
| namespace: 'default', | ||
| taskQueue: 'infrequent-activity-polling-task-queue', | ||
| workflowsPath: require.resolve('./workflows'), | ||
| activities, | ||
| }); | ||
| await worker.run(); | ||
| } finally { | ||
| // Close the connection once the worker has stopped | ||
| await connection.close(); | ||
| } | ||
| } | ||
|
|
||
| run().catch((err) => { | ||
| console.error(err); | ||
| process.exit(1); | ||
| }); | ||
| // @@@SNIPEND |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| // @@@SNIPSTART typescript-polling-infrequent | ||
| import { proxyActivities } from '@temporalio/workflow'; | ||
| import type * as activities from './activities'; | ||
|
|
||
| const { composeGreeting } = proxyActivities<typeof activities>({ | ||
| startToCloseTimeout: '2s', | ||
| retry: { | ||
| initialInterval: '60s', | ||
| backoffCoefficient: 1.0, | ||
| }, | ||
| }); | ||
|
|
||
| export async function greetingWorkflow(name: string): Promise<string> { | ||
| return await composeGreeting({ | ||
| greeting: "Hello", | ||
| name, | ||
| }) | ||
| } | ||
| // @@@SNIPEND |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| { | ||
| "extends": "@tsconfig/node18/tsconfig.json", | ||
| "version": "5.6.3", | ||
| "compilerOptions": { | ||
| "lib": ["es2021"], | ||
| "declaration": true, | ||
| "declarationMap": true, | ||
| "sourceMap": true, | ||
| "rootDir": "./src", | ||
| "outDir": "./lib" | ||
| }, | ||
| "include": ["src/**/*.ts"] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This readme is talking about frequent polling, but the sample is infrequent?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
whoops, should be infrequent, fixed