Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .scripts/list-of-samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"nestjs-exchange-rates",
"nextjs-ecommerce-oneclick",
"patching-api",
"polling",
"production",
"protobufs",
"query-subscriptions",
Expand Down
5 changes: 5 additions & 0 deletions polling/infrequent/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
coverage
jest.config.js
lib
.eslintrc.js
48 changes: 48 additions & 0 deletions polling/infrequent/.eslintrc.js
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}`]),
],
},
},
],
};
2 changes: 2 additions & 0 deletions polling/infrequent/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
lib
node_modules
1 change: 1 addition & 0 deletions polling/infrequent/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
1 change: 1 addition & 0 deletions polling/infrequent/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22
18 changes: 18 additions & 0 deletions polling/infrequent/.post-create
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}
1 change: 1 addition & 0 deletions polling/infrequent/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lib
2 changes: 2 additions & 0 deletions polling/infrequent/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
printWidth: 120
singleQuote: true
25 changes: 25 additions & 0 deletions polling/infrequent/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Infrequently Polling Activity

This sample shows how we can implement infrequent 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 infrequent 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.
11 changes: 11 additions & 0 deletions polling/infrequent/jest.config.js
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',
};
50 changes: 50 additions & 0 deletions polling/infrequent/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "temporal-polling-infrequent",
"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"
}
}
20 changes: 20 additions & 0 deletions polling/infrequent/src/activities.ts
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,
});
}
}
24 changes: 24 additions & 0 deletions polling/infrequent/src/client.ts
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
21 changes: 21 additions & 0 deletions polling/infrequent/src/service.ts
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");
}
42 changes: 42 additions & 0 deletions polling/infrequent/src/test/workflows.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker } from '@temporalio/worker';
import * as activities from '../activities';
import { greetingWorkflow } from '../workflows';
import { nanoid } from 'nanoid';
import assert from 'assert';

describe('infrequent polling workflow', function () {
let testEnv: TestWorkflowEnvironment;
const taskQueue = 'infrequent-activity-polling-task-queue';

beforeAll(async () => {
testEnv = await TestWorkflowEnvironment.createTimeSkipping();
});

afterAll(async () => {
await testEnv?.teardown();
});

it('runs returns expected greeting', async () => {
const { client, nativeConnection } = testEnv;

const worker = await Worker.create({
connection: nativeConnection,
workflowsPath: require.resolve('../workflows'),
activities,
taskQueue,
});

const handle = await client.workflow.start(greetingWorkflow, {
args: ['Temporal'],
workflowId: nanoid(),
taskQueue,
});

await worker.runUntil(async () => {
await testEnv.sleep('241s');
const result = await handle.result();
assert.equal(result, 'Hello, Temporal!');
});
});
});
28 changes: 28 additions & 0 deletions polling/infrequent/src/worker.ts
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
19 changes: 19 additions & 0 deletions polling/infrequent/src/workflows.ts
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
13 changes: 13 additions & 0 deletions polling/infrequent/tsconfig.json
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"]
}
Loading