diff --git a/packages/test/package.json b/packages/test/package.json index 6cdabc78e..bc4fceee6 100644 --- a/packages/test/package.json +++ b/packages/test/package.json @@ -38,6 +38,7 @@ "@temporalio/cloud": "workspace:*", "@temporalio/common": "workspace:*", "@temporalio/core-bridge": "workspace:*", + "@temporalio/envconfig": "workspace:*", "@temporalio/interceptors-opentelemetry": "workspace:*", "@temporalio/nexus": "workspace:*", "@temporalio/nyc-test-coverage": "workspace:*", diff --git a/packages/test/src/helpers.ts b/packages/test/src/helpers.ts index d18462d12..c4b65093a 100644 --- a/packages/test/src/helpers.ts +++ b/packages/test/src/helpers.ts @@ -4,9 +4,14 @@ import * as grpc from '@grpc/grpc-js'; import asyncRetry from 'async-retry'; import type { Connection } from '@temporalio/client'; import { Client } from '@temporalio/client'; +import { loadClientConnectConfig } from '@temporalio/envconfig'; +import type { NativeConnectionOptions, WorkerOptions } from '@temporalio/worker'; +import { NativeConnection } from '@temporalio/worker'; import * as iface from '@temporalio/proto'; import { createBaseBundlerOptions, + isSet, + Worker, loadHistory as loadHistoryBase, saveHistory as saveHistoryBase, RUN_TIME_SKIPPING_TESTS, @@ -47,6 +52,45 @@ export const bundlerOptions = createBaseBundlerOptions([ require.resolve('./mock-native-worker'), ]); +/** + * Server connection settings for tests that manage connections outside a shared test environment. + * + * Chosen like `createTestWorkflowEnvironment()`, but never starts a server: envconfig when + * `TEMPORAL_TEST_ENV_CONFIG_SERVER` is set (e.g. on Cloud), otherwise `TEMPORAL_SERVICE_ADDRESS` or the default + * local address, in the `default` namespace. + */ +export function configuredConnectionOptions(): { namespace: string; connectionOptions: NativeConnectionOptions } { + if (isSet(process.env.TEMPORAL_TEST_ENV_CONFIG_SERVER, false)) { + const { namespace, connectionOptions } = loadClientConnectConfig(); + return { namespace: namespace ?? 'default', connectionOptions }; + } + return { namespace: 'default', connectionOptions: { address: process.env.TEMPORAL_SERVICE_ADDRESS } }; +} + +/** + * Create a Worker with a dedicated connection that the caller must close after the Worker stops. + */ +export async function createWorkerWithConnection( + options: Omit & Partial> +): Promise<{ worker: Awaited>; connection: NativeConnection }> { + const { namespace, connectionOptions } = configuredConnectionOptions(); + const connection = await NativeConnection.connect(connectionOptions); + try { + const worker = await Worker.create({ connection, namespace, ...options }); + return { worker, connection }; + } catch (err) { + await connection.close(); + throw err; + } +} + +/** + * A task queue name unique to this test run, so tests sharing a server or namespace never poll each other's tasks. + */ +export function uniqueTaskQueue(title: string): string { + return `${title.replace(/[^a-zA-Z0-9]+/g, '-')}-${randomUUID()}`; +} + // Some of our tests expect "default custom search attributes" to exists, which used to be the case // in all deployment with support for advanced visibility. However, this might no longer be true in // some environement (e.g. Temporal CLI). Use the operator service to create them if they're missing. diff --git a/packages/test/src/test-runtime.cloud-pending.ts b/packages/test/src/test-runtime-integration.ts similarity index 53% rename from packages/test/src/test-runtime.cloud-pending.ts rename to packages/test/src/test-runtime-integration.ts index c7070637d..0c046b274 100644 --- a/packages/test/src/test-runtime.cloud-pending.ts +++ b/packages/test/src/test-runtime-integration.ts @@ -1,60 +1,98 @@ /** - * Runtime integration tests that still construct implicit localhost clients and Workers. - * Tests run serially because Runtime is a singleton. + * Runtime integration tests. Tests run serially because Runtime is a singleton. + * + * These tests avoid a shared test environment so they can close every connection and verify that the + * Runtime shuts down automatically once no Workers or connections remain. */ import { randomUUID } from 'crypto'; import asyncRetry from 'async-retry'; -import { Client, WorkflowClient } from '@temporalio/client'; -import type { LogEntry } from '@temporalio/worker'; +import type { ExecutionContext } from 'ava'; +import { Client, Connection, WorkflowClient } from '@temporalio/client'; +import type { LogEntry, WorkerOptions } from '@temporalio/worker'; import { DefaultLogger, makeTelemetryFilterString, NativeConnection, Runtime } from '@temporalio/worker'; -import { RUN_INTEGRATION_TESTS, test, Worker } from './helpers'; +import { + createWorkerWithConnection, + configuredConnectionOptions, + RUN_INTEGRATION_TESTS, + test, + uniqueTaskQueue, + Worker, +} from './helpers'; import { createTestWorkflowBundle } from './helpers-integration'; import { defaultOptions } from './mock-native-worker'; import * as workflows from './workflows'; import { log5Times } from './workflows/runtime'; +const { namespace, connectionOptions } = configuredConnectionOptions(); + +function createWorker(options: Partial & Pick) { + return createWorkerWithConnection({ ...defaultOptions, ...options }); +} + +/** + * Connect a client that is not tracked by the Runtime, closed when the test ends. + */ +async function connectClient(t: ExecutionContext): Promise { + const connection = await Connection.connect(connectionOptions); + t.teardown(() => connection.close()); + return connection; +} + if (RUN_INTEGRATION_TESTS) { test.serial('Runtime tracks registered workers, shuts down and restarts as expected', async (t) => { - const worker1 = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); - const worker2 = await Worker.create({ ...defaultOptions, taskQueue: 'q2' }); + const taskQueue1 = uniqueTaskQueue(`${t.title} 1`); + const taskQueue2 = uniqueTaskQueue(`${t.title} 2`); + const { worker: worker1, connection: connection1 } = await createWorker({ taskQueue: taskQueue1 }); + const { worker: worker2, connection: connection2 } = await createWorker({ taskQueue: taskQueue2 }); + const runtime = Runtime.instance(); const worker1Drained = worker1.run(); const worker2Drained = worker2.run(); worker1.shutdown(); await worker1Drained; + await connection1.close(); + t.is(Runtime.instance(), runtime); - const client = new WorkflowClient(); - await client.execute(workflows.sleeper, { taskQueue: 'q2', workflowId: randomUUID(), args: [1] }); + const client = new WorkflowClient({ connection: await connectClient(t), namespace }); + await client.execute(workflows.sleeper, { taskQueue: taskQueue2, workflowId: randomUUID(), args: [1] }); worker2.shutdown(); await worker2Drained; + await connection2.close(); - const worker3 = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); + const { worker: worker3, connection: connection3 } = await createWorker({ taskQueue: taskQueue1 }); + t.not(Runtime.instance(), runtime); const worker3Drained = worker3.run(); - await client.execute('sleeper', { taskQueue: 'q1', workflowId: randomUUID(), args: [1] }); + await client.execute('sleeper', { taskQueue: taskQueue1, workflowId: randomUUID(), args: [1] }); worker3.shutdown(); await worker3Drained; - t.pass(); + await connection3.close(); }); test.serial('Runtime.install() remembers installed options after it has been shut down', async (t) => { const messages: string[] = []; const logger = new DefaultLogger('DEBUG', ({ message }) => messages.push(message)); - Runtime.install({ logger }); + const installedRuntime = Runtime.install({ logger }); { const runtime = Runtime.instance(); runtime.logger.info('before shutdown'); t.true(messages.includes('before shutdown')); } - const worker = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); const workerDrained = worker.run(); worker.shutdown(); await workerDrained; + await connection.close(); { - const runtime = Runtime.instance(); - runtime.logger.info('after shutdown'); - t.true(messages.includes('after shutdown')); - await runtime.shutdown(); + const nextConnection = await NativeConnection.connect(connectionOptions); + try { + const runtime = Runtime.instance(); + t.not(runtime, installedRuntime); + runtime.logger.info('after shutdown'); + t.true(messages.includes('after shutdown')); + } finally { + await nextConnection.close(); + } } }); @@ -65,9 +103,16 @@ if (RUN_INTEGRATION_TESTS) { logger, telemetryOptions: { logging: { forward: {}, filter: makeTelemetryFilterString({ core: 'DEBUG' }) } }, }); + const taskQueue = uniqueTaskQueue(t.title); + const client = new Client({ connection: await connectClient(t), namespace }); + const handle = await client.workflow.start('not-existant', { + taskQueue, + workflowId: randomUUID(), + workflowExecutionTimeout: '1m', + }); + t.teardown(() => handle.terminate('test cleanup')); + const { worker, connection } = await createWorker({ taskQueue }); try { - await new Client().workflow.start('not-existant', { taskQueue: 'q1', workflowId: randomUUID() }); - const worker = await Worker.create({ ...defaultOptions, taskQueue: 'q1' }); await worker.runUntil(() => asyncRetry( () => { @@ -80,18 +125,18 @@ if (RUN_INTEGRATION_TESTS) { const initWorkerEntry = logEntries.filter((x) => x.message === 'Initializing worker')?.[0]; t.true(initWorkerEntry !== undefined); - t.is(initWorkerEntry.meta?.['taskQueue'], 'q1'); + t.is(initWorkerEntry.meta?.['taskQueue'], taskQueue); const failingWftEntry = logEntries.filter((x) => x.message === 'Failing workflow task')?.[0]; t.true(failingWftEntry !== undefined); - t.is(failingWftEntry.meta?.['taskQueue'], 'q1'); + t.is(failingWftEntry.meta?.['taskQueue'], taskQueue); t.is(typeof failingWftEntry.meta?.['completion'], 'string'); t.is(typeof failingWftEntry.meta?.['failure'], 'string'); t.is(typeof failingWftEntry.meta?.['runId'], 'string'); t.is(typeof failingWftEntry.meta?.['workflowId'], 'string'); t.is(typeof failingWftEntry.meta?.['sdkComponent'], 'string'); } finally { - await Runtime.instance().shutdown(); + await connection.close(); } }); @@ -104,19 +149,21 @@ if (RUN_INTEGRATION_TESTS) { }, }); const bufferedLogger = runtime.logger; - const connection = await NativeConnection.connect(); + const connection = await NativeConnection.connect(connectionOptions); try { const taskQueue = `runtime-native-log-collector-preriodically-flushed-${randomUUID()}`; const worker = await Worker.create({ ...defaultOptions, connection, + namespace, taskQueue, workflowBundle: await createTestWorkflowBundle({ workflowsPath: require.resolve('./workflows/runtime') }), }); + const client = new Client({ connection: await connectClient(t), namespace }); await worker.runUntil(async () => { - await new Client().workflow.execute(log5Times, { taskQueue, workflowId: randomUUID() }); + await client.workflow.execute(log5Times, { taskQueue, workflowId: randomUUID() }); }); t.true(logEntries.some((x) => x.message.startsWith('workflow log '))); @@ -124,7 +171,6 @@ if (RUN_INTEGRATION_TESTS) { t.false(logEntries.some((x) => x.message.startsWith('final log'))); } finally { await connection.close(); - await runtime.shutdown(); } t.is(logEntries.filter((x) => x.message.startsWith('workflow log ')).length, 5); diff --git a/packages/test/src/test-worker-lifecycle-integration.ts b/packages/test/src/test-worker-lifecycle-integration.ts index 091b372cd..e555b7da0 100644 --- a/packages/test/src/test-worker-lifecycle-integration.ts +++ b/packages/test/src/test-worker-lifecycle-integration.ts @@ -1,106 +1,128 @@ -/** Worker lifecycle integration tests. */ +/** + * Worker lifecycle integration tests. + * + * Run against local servers or Cloud using explicitly supplied connections. Worker shutdown leaves + * these connections open; closing the last connection then shuts down the Runtime. + * Automatic closure of Worker-created connections is covered by test-worker-owned-connection.local.ts. + */ import { randomUUID } from 'crypto'; import { setTimeout } from 'timers/promises'; +import test from 'ava'; +import { Client, Connection } from '@temporalio/client'; +import type { WorkerOptions } from '@temporalio/worker'; import { PromiseCompletionTimeoutError, Runtime, TransportError, UnexpectedError } from '@temporalio/worker'; -import { isBun } from './helpers'; -import { helpers, makeTestFunction } from './helpers-integration'; +import { + createWorkerWithConnection, + isBun, + configuredConnectionOptions, + RUN_INTEGRATION_TESTS, + uniqueTaskQueue, +} from './helpers'; +import { defaultOptions } from './mock-native-worker'; import { fillMemory } from './workflows'; -const test = makeTestFunction({ workflowsPath: require.resolve('./workflows') }); +const { namespace, connectionOptions } = configuredConnectionOptions(); -// The shared TestWorkflowEnvironment keeps its native connections alive until the suite teardown, -// so these tests verify Worker shutdown without expecting Runtime._instance to clear per test. +function createWorker(options: Partial & Pick) { + return createWorkerWithConnection({ ...defaultOptions, ...options }); +} -test.serial('Worker shuts down gracefully', async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.is(worker.getState(), 'INITIALIZED'); - t.not(Runtime._instance, undefined); - const workerRun = worker.run(); - t.is(worker.getState(), 'RUNNING'); - process.emit('SIGINT', 'SIGINT'); - await new Promise((resolve) => process.nextTick(resolve)); - t.is(worker.getState(), 'DRAINING'); - await workerRun; - t.is(worker.getState(), 'STOPPED'); - await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); -}); +if (RUN_INTEGRATION_TESTS) { + test.serial('Worker shuts down gracefully', async (t) => { + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + t.is(worker.getState(), 'INITIALIZED'); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + process.emit('SIGINT', 'SIGINT'); + await new Promise((resolve) => process.nextTick(resolve)); + t.is(worker.getState(), 'DRAINING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); + t.not(Runtime._instance, undefined, 'The supplied connection keeps the Runtime alive after Worker shutdown'); + await connection.close(); + t.is(Runtime._instance, undefined, 'Closing the last supplied connection shuts down the Runtime'); + }); -test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.not(Runtime._instance, undefined); - const p = worker.runUntil( - new Promise(() => { - // A promise that will never unblock. - }) - ); - t.is(worker.getState(), 'RUNNING'); - worker.shutdown(); - t.is(worker.getState(), 'DRAINING'); - await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); - t.is(worker.getState(), 'STOPPED'); -}); + test.serial("Worker.runUntil doesn't hang if provided promise survives to Worker's shutdown", async (t) => { + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + const p = worker.runUntil( + new Promise(() => { + // A promise that will never unblock. + }) + ); + t.is(worker.getState(), 'RUNNING'); + worker.shutdown(); + t.is(worker.getState(), 'DRAINING'); + await t.throwsAsync(p, { instanceOf: PromiseCompletionTimeoutError }); + t.is(worker.getState(), 'STOPPED'); + t.not(Runtime._instance, undefined, 'The supplied connection keeps the Runtime alive after Worker shutdown'); + await connection.close(); + t.is(Runtime._instance, undefined, 'Closing the last supplied connection shuts down the Runtime'); + }); -test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { - const { createWorker } = helpers(t); - const worker = await createWorker(); - t.is(worker.getState(), 'INITIALIZED'); - process.emit('SIGINT', 'SIGINT'); - const workerRun = worker.run(); - t.is(worker.getState(), 'RUNNING'); - await workerRun; - t.is(worker.getState(), 'STOPPED'); -}); + test.serial('Worker shuts down gracefully if interrupted before running', async (t) => { + const { worker, connection } = await createWorker({ taskQueue: uniqueTaskQueue(t.title) }); + t.is(worker.getState(), 'INITIALIZED'); + process.emit('SIGINT', 'SIGINT'); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + await connection.close(); + }); -test.serial('Worker fails validation against unknown namespace', async (t) => { - const { createWorker } = helpers(t); - await t.throwsAsync( - createWorker({ - namespace: 'oogabooga', - }), - { - // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. - instanceOf: TransportError, - // Cloud credentials cannot describe namespaces outside their authorized scope. - message: /Namespace oogabooga (?:is not found|was not found or otherwise could not be described)/, - } - ); -}); + test.serial('Worker fails validation against unknown namespace', async (t) => { + await t.throwsAsync( + createWorker({ + taskQueue: uniqueTaskQueue(t.title), + namespace: 'oogabooga', + }), + { + // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. + instanceOf: TransportError, + // Cloud credentials cannot describe namespaces outside their authorized scope. + message: /Namespace oogabooga (?:is not found|was not found or otherwise could not be described)/, + } + ); + }); -(isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { - t.timeout(30_000); - const { taskQueue, createWorker } = helpers(t); - const client = t.context.env.client; - const worker = await createWorker(); + (isBun ? test.skip : test.serial)('Threaded VM gracely stops and fails on ERR_WORKER_OUT_OF_MEMORY', async (t) => { + t.timeout(30_000); + const taskQueue = uniqueTaskQueue(t.title); + const clientConnection = await Connection.connect(connectionOptions); + t.teardown(() => clientConnection.close()); + const client = new Client({ connection: clientConnection, namespace }); + const { worker, connection } = await createWorker({ taskQueue }); - client.workflow - .start(fillMemory, { - taskQueue, - workflowId: randomUUID(), - workflowExecutionTimeout: '30s', - }) - .catch(() => void 0); + client.workflow + .start(fillMemory, { + taskQueue, + workflowId: randomUUID(), + workflowExecutionTimeout: '30s', + }) + .catch(() => void 0); - const workerRun = worker.run(); - try { - await Promise.race([setTimeout(10_000), workerRun]); - if (worker.getState() === 'RUNNING') { - worker.shutdown(); - await workerRun; + const workerRun = worker.run(); + try { + await Promise.race([setTimeout(10_000), workerRun]); + if (worker.getState() === 'RUNNING') { + worker.shutdown(); + await workerRun; + } + t.log('Non-conclusive result: Worker did not fail as expected'); + t.pass(); + } catch (err) { + // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. + t.is((err as Error).name, UnexpectedError.name); + t.is( + (err as Error).message, + 'Workflow Worker Thread exited prematurely: Error [ERR_WORKER_OUT_OF_MEMORY]: ' + + 'Worker terminated due to reaching memory limit: JS heap out of memory' + ); + t.is(worker.getState(), 'FAILED'); + } finally { + await connection.close(); } - t.log('Non-conclusive result: Worker did not fail as expected'); - t.pass(); - } catch (err) { - // oxlint-disable-next-line typescript/no-deprecated -- Assert the internal worker error type. - t.is((err as Error).name, UnexpectedError.name); - t.is( - (err as Error).message, - 'Workflow Worker Thread exited prematurely: Error [ERR_WORKER_OUT_OF_MEMORY]: ' + - 'Worker terminated due to reaching memory limit: JS heap out of memory' - ); - t.is(worker.getState(), 'FAILED'); - } finally { - if (Runtime._instance) await Runtime._instance.shutdown(); - } -}); + }); +} diff --git a/packages/test/src/test-worker-owned-connection.local.ts b/packages/test/src/test-worker-owned-connection.local.ts new file mode 100644 index 000000000..e3bc6741f --- /dev/null +++ b/packages/test/src/test-worker-owned-connection.local.ts @@ -0,0 +1,40 @@ +import { PromiseCompletionTimeoutError, Runtime } from '@temporalio/worker'; +import { RUN_INTEGRATION_TESTS, test, uniqueTaskQueue, Worker } from './helpers'; +import { defaultOptions } from './mock-native-worker'; + +// These tests are local only as there is no way to provide options to the Worker created connection. +if (RUN_INTEGRATION_TESTS) { + test.serial('Worker closes its implicit connection and shuts down the Runtime', async (t) => { + const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); + t.is(worker.getState(), 'INITIALIZED'); + t.not(Runtime._instance, undefined); + const workerRun = worker.run(); + t.is(worker.getState(), 'RUNNING'); + process.emit('SIGINT', 'SIGINT'); + await new Promise((resolve) => process.nextTick(resolve)); + t.is(worker.getState(), 'DRAINING'); + await workerRun; + t.is(worker.getState(), 'STOPPED'); + await t.throwsAsync(worker.run(), { message: 'Poller was already started' }); + t.is(Runtime._instance, undefined, 'Worker shutdown closes its implicit connection and shuts down the Runtime'); + }); + + test.serial( + 'Worker.runUntil closes its implicit connection when the provided promise outlives shutdown', + async (t) => { + const worker = await Worker.create({ ...defaultOptions, taskQueue: uniqueTaskQueue(t.title) }); + t.not(Runtime._instance, undefined); + const workerRun = worker.runUntil( + new Promise(() => { + // Keep the promise pending so runUntil must time out after Worker shutdown. + }) + ); + t.is(worker.getState(), 'RUNNING'); + worker.shutdown(); + t.is(worker.getState(), 'DRAINING'); + await t.throwsAsync(workerRun, { instanceOf: PromiseCompletionTimeoutError }); + t.is(worker.getState(), 'STOPPED'); + t.is(Runtime._instance, undefined, 'runUntil closes the implicit connection and shuts down the Runtime'); + } + ); +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 640f84dfb..4f22c1de1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -758,6 +758,9 @@ importers: '@temporalio/core-bridge': specifier: workspace:* version: link:../core-bridge + '@temporalio/envconfig': + specifier: workspace:* + version: link:../envconfig '@temporalio/interceptors-opentelemetry': specifier: workspace:* version: link:../../contrib/interceptors-opentelemetry