From 05e16d520531907989fc7e1344fe162d48f81701 Mon Sep 17 00:00:00 2001 From: Thomas Hardy Date: Mon, 12 Oct 2026 14:16:14 -0400 Subject: [PATCH 1/2] ci: probe whether the Cloud CI API key can manage Nexus endpoints TEMPORARY, not for merge. Creates and deletes one Nexus endpoint through the Cloud Ops API in the Cloud job, logging whether the CI API key is permitted to. Nexus suites can only run against Cloud if endpoints can be created this way, since Cloud rejects the OperatorService. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/cloud-namespace.ts | 40 +++++++++++++++++++++++++++++- .github/workflows/ci.yml | 8 ++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/.github/scripts/cloud-namespace.ts b/.github/scripts/cloud-namespace.ts index ab50fe1958..24e04039c2 100644 --- a/.github/scripts/cloud-namespace.ts +++ b/.github/scripts/cloud-namespace.ts @@ -97,11 +97,49 @@ async function deleteNamespace(namespace: string): Promise { }); } +// TEMP(nexus-probe): checks whether the CI API key may manage Nexus endpoints. Not for merge. +async function probeNexusEndpoint(namespace: string): Promise { + await withCloudClient(async (client) => { + const name = `sdk-typescript-ci-probe-${requiredEnv('GITHUB_RUN_ID')}-${requiredEnv('GITHUB_RUN_ATTEMPT')}`; + let created: temporal.api.cloud.cloudservice.v1.CreateNexusEndpointResponse; + try { + created = await client.cloudService.createNexusEndpoint({ + asyncOperationId: randomUUID(), + spec: { + name, + targetSpec: { workerTargetSpec: { namespaceId: namespace, taskQueue: 'nexus-probe' } }, + policySpecs: [{ allowedCloudNamespacePolicySpec: { namespaceId: namespace } }], + }, + }); + } catch (error) { + console.log(`NEXUS PROBE: createNexusEndpoint FAILED: ${(error as Error).message}`); + throw error; + } + console.log(`NEXUS PROBE: createNexusEndpoint accepted (endpoint ${created.endpointId})`); + if (!created.asyncOperation) throw new Error('Create endpoint response did not include an operation'); + await waitForOperation(client, created.asyncOperation); + console.log('NEXUS PROBE: endpoint creation fulfilled'); + + const existing = await client.cloudService.getNexusEndpoint({ endpointId: created.endpointId }); + const resourceVersion = existing.endpoint?.resourceVersion; + if (!resourceVersion) throw new Error(`Nexus endpoint ${created.endpointId} did not include a resource version`); + const deleted = await client.cloudService.deleteNexusEndpoint({ + endpointId: created.endpointId, + resourceVersion, + asyncOperationId: randomUUID(), + }); + if (!deleted.asyncOperation) throw new Error('Delete endpoint response did not include an operation'); + await waitForOperation(client, deleted.asyncOperation); + console.log('NEXUS PROBE: endpoint deleted'); + }); +} + async function main(): Promise { const [command, namespace] = process.argv.slice(2); if (command === 'create' && namespace === undefined) return await create(); if (command === 'delete' && namespace !== undefined) return await deleteNamespace(namespace); - throw new Error('Usage: cloud-namespace.ts create | delete '); + if (command === 'nexus-probe' && namespace !== undefined) return await probeNexusEndpoint(namespace); + throw new Error('Usage: cloud-namespace.ts create | delete | nexus-probe '); } main().catch((error) => { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a6eba0d44..9a92c87a41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -393,6 +393,14 @@ jobs: TEMPORAL_CLIENT_CLOUD_API_KEY: ${{ secrets.TEMPORAL_CLIENT_CLOUD_API_KEY }} TEMPORAL_CLIENT_CLOUD_API_VERSION: v0.19.1 + # TEMP(nexus-probe): does the CI API key allow managing Nexus endpoints? Not for merge. + - name: Probe Cloud Nexus endpoint permissions + continue-on-error: true + run: pnpm exec tsx .github/scripts/cloud-namespace.ts nexus-probe "${{ steps.create-cloud-namespace.outputs.namespace }}" + env: + TEMPORAL_CLIENT_CLOUD_API_KEY: ${{ secrets.TEMPORAL_CLIENT_CLOUD_API_KEY }} + TEMPORAL_CLIENT_CLOUD_API_VERSION: v0.19.1 + - name: Run tests against Temporal Cloud # Fail a hung suite while leaving job-level time for namespace cleanup and log upload. timeout-minutes: 20 From d14b5f5052bed9926a51ca0c54c8422a3a0829c0 Mon Sep 17 00:00:00 2001 From: Thomas Hardy Date: Tue, 13 Oct 2026 10:30:42 -0400 Subject: [PATCH 2/2] ci: create Nexus endpoints up front for Cloud tests Temporal Cloud only manages Nexus endpoints through the Cloud Ops API, and new endpoints take minutes to become callable, so tests cannot create their own. - List the task queue of every test that calls registerNexusEndpoint() in a checked-in manifest. registerNexusEndpoint() fails for a missing entry, so local runs catch new or renamed tests. - Add a `nexus-endpoints` command to cloud-namespace.ts. It creates one endpoint per task queue of the Cloud-eligible test files, named after the run's namespace, then calls each endpoint until it responds and waits 30s more, as the Nexus team's own Cloud tests do. - On Cloud, registerNexusEndpoint() returns the pre-created endpoint's name. - The delete step removes the run's endpoints before the namespace, and creation removes endpoints leaked by runs that died before cleanup. - Remove redundant endpoint deletion from test-nexus-workflow-caller; the helper's teardown already deletes the endpoint. - Run test-integration-extstore-nexus on Cloud as the first Nexus suite. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/cloud-namespace.ts | 133 ++++- .github/workflows/ci.yml | 12 +- packages/test/src/helpers-integration.ts | 28 +- packages/test/src/nexus-endpoint-manifest.ts | 117 ++++ packages/test/src/nexus-endpoint-readiness.ts | 108 ++++ packages/test/src/nexus-endpoints.ts | 51 ++ ....ts => test-integration-extstore-nexus.ts} | 0 packages/test/src/test-nexus-endpoints.ts | 37 ++ ...nexus-workflow-caller.cloud-unavailable.ts | 524 +++++++++--------- .../src/workflows/nexus-endpoint-probe.ts | 12 + 10 files changed, 738 insertions(+), 284 deletions(-) create mode 100644 packages/test/src/nexus-endpoint-manifest.ts create mode 100644 packages/test/src/nexus-endpoint-readiness.ts create mode 100644 packages/test/src/nexus-endpoints.ts rename packages/test/src/{test-integration-extstore-nexus.cloud-unavailable.ts => test-integration-extstore-nexus.ts} (100%) create mode 100644 packages/test/src/test-nexus-endpoints.ts create mode 100644 packages/test/src/workflows/nexus-endpoint-probe.ts diff --git a/.github/scripts/cloud-namespace.ts b/.github/scripts/cloud-namespace.ts index ab50fe1958..8637369e51 100644 --- a/.github/scripts/cloud-namespace.ts +++ b/.github/scripts/cloud-namespace.ts @@ -2,9 +2,16 @@ import { randomUUID } from 'node:crypto'; import { appendFile, readFile } from 'node:fs/promises'; import { CloudOperationsClient, CloudOperationsConnection } from '../../packages/cloud'; import { temporal } from '../../packages/proto'; +import { waitForNexusEndpointsReady } from '../../packages/test/lib/nexus-endpoint-readiness'; +import { nexusEndpointTaskQueues, preCreatedNexusEndpointName } from '../../packages/test/lib/nexus-endpoints'; +import { findCloudTestFiles } from '../../scripts/cloud-test-inventory'; const OPERATION_TIMEOUT_MS = 10 * 60 * 1_000; const OperationState = temporal.api.cloud.operation.v1.AsyncOperation.State; +// Names of the namespaces and Nexus endpoints that CI runs create start with this. +const CI_RESOURCE_PREFIX = 'sdk-typescript-ci-'; + +type CloudNexusEndpoint = temporal.api.cloud.nexus.v1.IEndpoint; function requiredEnv(name: string): string { const value = process.env[name]; @@ -58,9 +65,85 @@ async function withCloudClient(fn: (client: CloudOperationsClient) => Promise[]): unknown[] { + return results.filter((result) => result.status === 'rejected').map((result) => result.reason); +} + +async function listNexusEndpoints( + client: CloudOperationsClient, + targetNamespaceId?: string +): Promise { + const endpoints: CloudNexusEndpoint[] = []; + let pageToken = ''; + do { + const page = await client.cloudService.getNexusEndpoints({ targetNamespaceId, pageToken, pageSize: 1000 }); + endpoints.push(...page.endpoints); + pageToken = page.nextPageToken; + } while (pageToken); + return endpoints; +} + +async function listNamespaceIds(client: CloudOperationsClient): Promise { + const namespaces: string[] = []; + let pageToken = ''; + do { + const page = await client.cloudService.getNamespaces({ pageToken, pageSize: 1000 }); + namespaces.push(...page.namespaces.flatMap(({ namespace }) => (namespace ? [namespace] : []))); + pageToken = page.nextPageToken; + } while (pageToken); + return namespaces; +} + +async function createNexusEndpoint( + client: CloudOperationsClient, + namespace: string, + name: string, + taskQueue: string +): Promise { + const result = await client.cloudService.createNexusEndpoint({ + asyncOperationId: randomUUID(), + spec: { + name, + targetSpec: { workerTargetSpec: { namespaceId: namespace, taskQueue } }, + policySpecs: [{ allowedCloudNamespacePolicySpec: { namespaceId: namespace } }], + }, + }); + if (!result.asyncOperation) throw new Error(`Create Nexus endpoint ${name} response did not include an operation`); + await waitForOperation(client, result.asyncOperation); +} + +async function deleteNexusEndpoint(client: CloudOperationsClient, endpoint: CloudNexusEndpoint): Promise { + const { id: endpointId, resourceVersion } = endpoint; + if (!endpointId || !resourceVersion) { + throw new Error(`Nexus endpoint ${endpoint.spec?.name} did not include an ID and resource version`); + } + const result = await client.cloudService.deleteNexusEndpoint({ + endpointId, + resourceVersion, + asyncOperationId: randomUUID(), + }); + if (!result.asyncOperation) + throw new Error(`Delete Nexus endpoint ${endpointId} response did not include an operation`); + await waitForOperation(client, result.asyncOperation); +} + +/** + * Delete endpoints left behind by CI runs that died before cleanup, since they count against the account's endpoint + * limit. Endpoints are listed before namespaces, so an endpoint whose namespace is missing cannot belong to a live run. + */ +async function deleteLeakedNexusEndpoints(client: CloudOperationsClient): Promise { + const endpoints = (await listNexusEndpoints(client)).filter(({ spec }) => spec?.name?.startsWith(CI_RESOURCE_PREFIX)); + const namespaces = new Set(await listNamespaceIds(client)); + const leaked = endpoints.filter(({ spec }) => !namespaces.has(spec?.targetSpec?.workerTargetSpec?.namespaceId ?? '')); + const errors = rejections(await Promise.allSettled(leaked.map((endpoint) => deleteNexusEndpoint(client, endpoint)))); + // Best effort: another run may be deleting the same endpoints, and a later run will retry the rest. + for (const error of errors) console.warn(`Could not delete a leaked Nexus endpoint: ${error}`); + console.log(`Deleted ${leaked.length - errors.length} of ${leaked.length} leaked Nexus endpoints`); +} + async function create(): Promise { await withCloudClient(async (client) => { - const namespaceName = `sdk-typescript-ci-${requiredEnv('GITHUB_RUN_ID')}-${requiredEnv('GITHUB_RUN_ATTEMPT')}`; + const namespaceName = `${CI_RESOURCE_PREFIX}${requiredEnv('GITHUB_RUN_ID')}-${requiredEnv('GITHUB_RUN_ATTEMPT')}`; const result = await client.cloudService.createNamespace({ asyncOperationId: randomUUID(), spec: { @@ -81,8 +164,49 @@ async function create(): Promise { }); } +/** + * Create the Nexus endpoints that Cloud-eligible test files need (see `packages/test/src/nexus-endpoints.ts`), wait + * until they are callable, and output the name prefix that tests use to find them. + */ +async function createNexusEndpoints(namespace: string): Promise { + // Endpoint names are unique per account, so start them with the run's namespace name. + const prefix = namespace.split('.')[0]; + const endpoints = nexusEndpointTaskQueues(await findCloudTestFiles()).map((taskQueue) => ({ + name: preCreatedNexusEndpointName(prefix, taskQueue), + taskQueue, + })); + + await withCloudClient(async (client) => { + await deleteLeakedNexusEndpoints(client); + await Promise.all(endpoints.map(({ name, taskQueue }) => createNexusEndpoint(client, namespace, name, taskQueue))); + }); + + console.log(`Created ${endpoints.length} Nexus endpoints; waiting until they are callable`); + if (endpoints.length > 0) { + await waitForNexusEndpointsReady( + { + disableFile: true, + overrideEnvVars: { + TEMPORAL_ADDRESS: `${namespace}.tmprl.cloud:7233`, + TEMPORAL_NAMESPACE: namespace, + TEMPORAL_TLS_CLIENT_CERT_PATH: requiredEnv('TEMPORAL_TLS_CLIENT_CERT_PATH'), + TEMPORAL_TLS_CLIENT_KEY_PATH: requiredEnv('TEMPORAL_TLS_CLIENT_KEY_PATH'), + }, + }, + endpoints + ); + } + await appendFile(requiredEnv('GITHUB_OUTPUT'), `prefix=${prefix}\n`); +} + async function deleteNamespace(namespace: string): Promise { await withCloudClient(async (client) => { + // Endpoints are account resources that outlive the namespace they route to. + const endpoints = await listNexusEndpoints(client, namespace); + const endpointErrors = rejections( + await Promise.allSettled(endpoints.map((endpoint) => deleteNexusEndpoint(client, endpoint))) + ); + const existing = await client.cloudService.getNamespace({ namespace }); const resourceVersion = existing.namespace?.resourceVersion; if (!resourceVersion) throw new Error(`Cloud namespace ${namespace} did not include a resource version`); @@ -94,14 +218,19 @@ async function deleteNamespace(namespace: string): Promise { }); if (!result.asyncOperation) throw new Error('Delete namespace response did not include an operation'); await waitForOperation(client, result.asyncOperation); + + if (endpointErrors.length > 0) { + throw new AggregateError(endpointErrors, `Failed to delete Nexus endpoints for ${namespace}`); + } }); } async function main(): Promise { const [command, namespace] = process.argv.slice(2); if (command === 'create' && namespace === undefined) return await create(); + if (command === 'nexus-endpoints' && namespace !== undefined) return await createNexusEndpoints(namespace); if (command === 'delete' && namespace !== undefined) return await deleteNamespace(namespace); - throw new Error('Usage: cloud-namespace.ts create | delete '); + throw new Error('Usage: cloud-namespace.ts create | nexus-endpoints | delete '); } main().catch((error) => { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a6eba0d44..468eb31179 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -393,6 +393,15 @@ jobs: TEMPORAL_CLIENT_CLOUD_API_KEY: ${{ secrets.TEMPORAL_CLIENT_CLOUD_API_KEY }} TEMPORAL_CLIENT_CLOUD_API_VERSION: v0.19.1 + # Cloud only manages Nexus endpoints through the Cloud Ops API, and they take minutes to become callable, so + # create every endpoint the tests need up front (see packages/test/src/nexus-endpoints.ts). + - name: Create Cloud Nexus endpoints + id: create-cloud-nexus-endpoints + run: pnpm exec tsx .github/scripts/cloud-namespace.ts nexus-endpoints "${{ steps.create-cloud-namespace.outputs.namespace }}" + env: + TEMPORAL_CLIENT_CLOUD_API_KEY: ${{ secrets.TEMPORAL_CLIENT_CLOUD_API_KEY }} + TEMPORAL_CLIENT_CLOUD_API_VERSION: v0.19.1 + - name: Run tests against Temporal Cloud # Fail a hung suite while leaving job-level time for namespace cleanup and log upload. timeout-minutes: 20 @@ -403,8 +412,9 @@ jobs: TEMPORAL_TEST_ENV_CONFIG_SERVER: true TEMPORAL_ADDRESS: ${{ steps.create-cloud-namespace.outputs.namespace }}.tmprl.cloud:7233 TEMPORAL_NAMESPACE: ${{ steps.create-cloud-namespace.outputs.namespace }} + TEMPORAL_TEST_NEXUS_ENDPOINT_PREFIX: ${{ steps.create-cloud-nexus-endpoints.outputs.prefix }} - - name: Delete Cloud namespace + - name: Delete Cloud namespace and Nexus endpoints if: ${{ always() && steps.create-cloud-namespace.outputs.namespace != '' }} run: pnpm exec tsx .github/scripts/cloud-namespace.ts delete "${{ steps.create-cloud-namespace.outputs.namespace }}" env: diff --git a/packages/test/src/helpers-integration.ts b/packages/test/src/helpers-integration.ts index 8e8ee1527a..98dcf70eca 100644 --- a/packages/test/src/helpers-integration.ts +++ b/packages/test/src/helpers-integration.ts @@ -2,7 +2,7 @@ import { status as grpcStatus } from '@grpc/grpc-js'; import type { ErrorConstructor, ExecutionContext, TestFn } from 'ava'; import type { WorkflowHandle } from '@temporalio/client'; import { isGrpcServiceError, WorkflowFailedError, WorkflowUpdateFailedError } from '@temporalio/client'; -import type { LocalTestWorkflowEnvironmentOptions, NexusEndpointIdentifier } from '@temporalio/testing'; +import type { LocalTestWorkflowEnvironmentOptions } from '@temporalio/testing'; import type { BundlerPlugin, LogEntry, @@ -34,6 +34,12 @@ import { Worker, } from '@temporalio/test-helpers'; +import { + assertNexusEndpointInManifest, + NEXUS_ENDPOINT_PREFIX_ENV, + preCreatedNexusEndpointName, +} from './nexus-endpoints'; + export { defaultSAKeys, createLocalTestEnvironment }; /** @@ -155,9 +161,11 @@ export interface Helpers extends BaseHelpers { assertWorkflowUpdateFailed(p: Promise, causeConstructor: ErrorConstructor, message?: string): Promise; assertWorkflowFailedError(p: Promise, causeConstructor: ErrorConstructor, message?: string): Promise; updateHasBeenAdmitted(handle: WorkflowHandle, updateId: string): Promise; - registerNexusEndpoint( - suffix?: string - ): Promise<{ endpointName: string; endpointIdentifier: NexusEndpointIdentifier }>; + /** + * Get a Nexus endpoint that routes to this test's task queue. Creates the endpoint unless it was created before + * the run (see `nexus-endpoints.ts`); either way, the task queue must be listed in the endpoint manifest. + */ + registerNexusEndpoint(): Promise<{ endpointName: string }>; } /** @@ -243,10 +251,12 @@ export function helpers(t: ExecutionContext, env?: TestWorkflowEnvironm throw err; } }, - async registerNexusEndpoint( - suffix?: string - ): Promise<{ endpointName: string; endpointIdentifier: NexusEndpointIdentifier }> { - const endpointName = (suffix ? `${taskQueue}-${suffix}` : taskQueue).replaceAll('_', '-'); + async registerNexusEndpoint(): Promise<{ endpointName: string }> { + assertNexusEndpointInManifest(anyTest.meta.file, taskQueue); + const preCreatedPrefix = process.env[NEXUS_ENDPOINT_PREFIX_ENV]; + if (preCreatedPrefix) return { endpointName: preCreatedNexusEndpointName(preCreatedPrefix, taskQueue) }; + + const endpointName = taskQueue.replaceAll('_', '-'); try { const endpointIdentifier = await testEnv.createNexusEndpoint(endpointName, taskQueue); t.teardown(() => @@ -254,7 +264,7 @@ export function helpers(t: ExecutionContext, env?: TestWorkflowEnvironm /* ignore cleanup errors */ }) ); - return { endpointName, endpointIdentifier }; + return { endpointName }; } catch (err) { if (err instanceof Error) { err.message = `Failed to register Nexus endpoint '${endpointName}': ${err.message}`; diff --git a/packages/test/src/nexus-endpoint-manifest.ts b/packages/test/src/nexus-endpoint-manifest.ts new file mode 100644 index 0000000000..c3a9825715 --- /dev/null +++ b/packages/test/src/nexus-endpoint-manifest.ts @@ -0,0 +1,117 @@ +/** + * Task queues of the tests that call `registerNexusEndpoint()`, keyed by test file (see `nexusSuiteName`). + * + * Cloud runs create one endpoint per task queue before the tests start, for every Cloud-eligible file. + * `registerNexusEndpoint()` fails for a task queue missing from this list, on every server, so local runs catch a + * new or renamed test. + */ +export const nexusEndpointManifest: Readonly> = { + 'test-integration-extstore-nexus': [ + 'a-transient-retrieve-failure-on-the-nexus-task-fails-it-retryably-and-recovers', + 'a-transient-store-failure-on-the-nexus-result-fails-it-retryably-and-recovers', + 'nexus-operation-input-is-offloaded-and-retrieved-for-the-handler-invocation', + 'nexus-operation-sync-result-is-offloaded-and-retrieved-for-the-caller', + ], + 'test-nexus-codec-converter-errors': [ + 'nexus-operation-codec-failure-is-retried', + 'nexus-operation-codec-handlererror-is-propagated-as-is', + 'nexus-operation-codec-payloadvalidationerror-is-a-non-retryable-bad-request', + 'nexus-operation-converter-failure-is-not-retried', + 'nexus-operation-converter-handlererror-is-propagated-as-is', + 'nexus-operation-converter-payloadvalidationerror-is-a-non-retryable-bad-request', + ], + 'test-nexus-operation-timeouts': [ + 'scheduletostarttimeout-fires-when-nexus-operation-never-starts', + 'starttoclosetimeout-fires-when-async-nexus-operation-never-completes', + ], + 'test-nexus-query-operation': [ + 'query-nexus-operation-attaches-the-response-link-to-the-caller-s-nexusoperationcompleted-event', + 'query-nexus-operation-returns-the-queried-result', + ], + 'test-nexus-signal-linking': [ + 'async-nexus-operation-that-signals-propagates-the-response-link-onto-nexusoperationstarted', + 'one-nexus-operation-signaling-multiple-callees-lands-a-response-link-per-callee', + 'signal-and-signalwithstart-from-a-nexus-handler-forward-links-and-propagate-response-links', + ], + 'test-nexus-standalone': [ + 'cancel-operation', + 'count-and-list-operations', + 'describe-operation', + 'detached-standalone-nexus-handle-hydrates-result-using-output-typeinfo', + 'execute-operation', + 'failure-propagation', + 'get-handle-by-id', + 'id-conflict-policy-use-existing-returns-existing-run', + 'id-reuse-policy-reject-duplicate-after-close-throws-alreadystartederror', + 'interceptor-integration', + 'standalone-nexus-interceptors-can-supply-operation-typeinfo', + 'standalone-nexus-worker-decodes-nested-payloads-in-a-marked-system-nexus-input', + 'standalone-nexus-worker-retrieves-external-storage-references-nested-in-a-marked-system-nexus-input', + 'start-async-operation-and-poll-result', + 'start-sync-operation-and-get-result', + 'string-standalone-nexus-execute-hydrates-input-and-result-using-service-typeinfo', + 'terminate-operation', + 'typeinfo-hydrates-standalone-start-input-and-retained-handle-result', + 'workflowrunoperation-workflow-run-has-nexus-operation-token-header', + ], + 'test-nexus-temporal-operation': [ + 'temporaloperationhandler-activity-conflict-failure-is-non-retryable', + 'temporaloperationhandler-activity-has-nexus-operation-token-header', + 'temporaloperationhandler-activity-links-are-not-duplicated', + 'temporaloperationhandler-activity-reject-duplicate-failure-is-non-retryable', + 'temporaloperationhandler-allows-retry-after-failed-async-start', + 'temporaloperationhandler-async-and-sync-happy-paths-caller-workflow', + 'temporaloperationhandler-cancel-delegates-to-provided-cancelworkflowrun-handler', + 'temporaloperationhandler-cancels-backing-activity', + 'temporaloperationhandler-default-cancelworkflowrun-cancels-backing-workflow', + 'temporaloperationhandler-invokes-custom-cancelactivity', + 'temporaloperationhandler-links-a-standalone-nexus-operation-and-its-backing-activity', + 'temporaloperationhandler-links-a-workflow-invoked-nexus-operation-and-its-backing-activity', + 'temporaloperationhandler-propagates-backing-activity-failure', + 'temporaloperationhandler-rejects-multiple-async-starts-activity-then-activity', + 'temporaloperationhandler-rejects-multiple-async-starts-activity-then-workflow', + 'temporaloperationhandler-rejects-multiple-async-starts-workflow-then-activity', + 'temporaloperationhandler-rejects-multiple-async-starts-workflow-then-workflow', + 'temporaloperationhandler-start-typed-standalone-activity', + 'temporaloperationhandler-start-untyped-standalone-activity', + 'temporaloperationhandler-workflow-conflict-failure-is-non-retryable', + 'temporaloperationhandler-workflow-reject-duplicate-failure-is-non-retryable', + 'temporaloperationhandler-workflow-run-has-nexus-operation-token-header', + ], + 'test-nexus-update-operation': [ + 'updateworkflow-nexus-operation-pending-update-completes-asynchronously-via-callback', + 'updateworkflow-nexus-operation-same-update-id-is-idempotent', + 'updateworkflow-nexus-operation-update-against-a-completed-workflow-does-not-succeed', + 'updateworkflow-nexus-operation-update-on-a-startworkflow-handle-is-rejected', + 'updateworkflow-nexus-operation-valid-update-succeeds-and-returns-the-update-result', + 'updateworkflow-nexus-operation-validation-failure-surfaces-as-a-failed-operation', + ], + 'test-nexus-workflow-caller': [ + 'async-operation-handler-happy-path-via-workflowrunoperationhandler', + 'calling-a-nonexistent-service-returns-not-found', + 'cancel-operation-handler-errors-caller-workflow', + 'getclient-is-available-in-handler-context-caller-workflow', + 'inbound-canceloperation-interceptor-can-modify-input', + 'inbound-startoperation-interceptor-can-modify-input-and-result', + 'logger-is-available-in-handler-context-caller-workflow', + 'nexus-sync-and-async-operations-from-a-workflow', + 'nexus-typeinfo-hydrates-asynchronous-backing-workflow-input-and-caller-result', + 'nexus-typeinfo-hydrates-synchronous-handler-input-and-caller-result', + 'nexusserviceclient-is-type-safe-in-regard-to-operation-definitions', + 'operation-handler-cancellation-via-workflow-cancel', + 'operationinfo-is-available-in-handler-context-caller-workflow', + 'requestdeadline-is-available-in-cancel-operation-context', + 'requestdeadline-is-available-in-start-operation-context', + 'start-operation-handler-errors-caller-workflow', + 'sync-operation-handler-happy-path-caller-workflow', + 'workflow-nexus-interceptor-can-supply-operation-typeinfo', + 'workflowrunoperationhandler-attaches-links-and-callbacks-caller-workflow', + ], + 'test-workflow-nexus-cancellation': [ + 'workflow-calling-nexus-operation-with-cancellation-type-abandon-properly-cancels', + 'workflow-calling-nexus-operation-with-cancellation-type-try-cancel-properly-cancels', + 'workflow-calling-nexus-operation-with-cancellation-type-wait-cancellation-completed-properly-cancels', + 'workflow-calling-nexus-operation-with-cancellation-type-wait-cancellation-requested-doesn-t-wait-for-completion', + 'workflow-calling-nexus-operation-with-cancellation-type-wait-cancellation-requested-properly-fails', + ], +}; diff --git a/packages/test/src/nexus-endpoint-readiness.ts b/packages/test/src/nexus-endpoint-readiness.ts new file mode 100644 index 0000000000..2d4147ca40 --- /dev/null +++ b/packages/test/src/nexus-endpoint-readiness.ts @@ -0,0 +1,108 @@ +/** + * Readiness check for Nexus endpoints that `.github/scripts/cloud-namespace.ts` creates for a Cloud test run. + * + * Cloud propagates endpoints through eventually consistent registry caches, and the Cloud Ops API cannot report + * when that has finished. Like the Nexus team's own Cloud tests, call each endpoint from the target namespace until a + * call succeeds, then wait a while longer for the remaining caches to refresh. + */ +import { setTimeout as sleep } from 'node:timers/promises'; +import * as nexus from 'nexus-rpc'; +import { Client, Connection, WorkflowFailedError } from '@temporalio/client'; +import type { LoadClientProfileOptions } from '@temporalio/envconfig'; +import { loadClientConnectConfig } from '@temporalio/envconfig'; +import { NativeConnection, Worker } from '@temporalio/worker'; +import { nexusEndpointProbeCaller, nexusEndpointProbeService } from './workflows/nexus-endpoint-probe'; + +export interface NexusEndpointTarget { + name: string; + /** Task queue in the configured namespace that the endpoint routes to. */ + taskQueue: string; +} + +const CALLER_TASK_QUEUE = 'nexus-endpoint-probe-caller'; + +// The Nexus team's test budget: retry every 200ms for up to 3 minutes, then wait 30 seconds once a call succeeds. +const READY_TIMEOUT_MS = 3 * 60_000; +const SETTLE_MS = 30_000; +const RETRY_DELAY_MS = 200; +// Bounds an attempt that never completes, e.g. while the caller's workflow task fails on an unknown endpoint. +const ATTEMPT_TIMEOUT = '15s'; + +async function callUntilReady(client: Client, endpointName: string): Promise { + const startedAt = Date.now(); + const deadline = startedAt + READY_TIMEOUT_MS; + for (let attempt = 1; ; attempt++) { + try { + const result = await client.workflow.execute(nexusEndpointProbeCaller, { + taskQueue: CALLER_TASK_QUEUE, + workflowId: `${endpointName}-${attempt}`, + args: [endpointName, endpointName], + workflowExecutionTimeout: ATTEMPT_TIMEOUT, + }); + if (result !== endpointName) { + throw new Error(`Nexus endpoint ${endpointName} echoed ${JSON.stringify(result)}`); + } + console.log(`Nexus endpoint ${endpointName} responded after ${Date.now() - startedAt}ms (${attempt} attempts)`); + return; + } catch (error) { + if (!(error instanceof WorkflowFailedError)) throw error; + if (Date.now() + RETRY_DELAY_MS >= deadline) { + throw new Error(`Nexus endpoint ${endpointName} did not respond within ${READY_TIMEOUT_MS}ms`, { + cause: error, + }); + } + await sleep(RETRY_DELAY_MS); + } + } +} + +/** + * Wait until every endpoint in `endpoints` routes calls from the configured namespace to its task queue. + * + * @param envconfigOpts - Selects the namespace and connection, as for the tests themselves. + */ +export async function waitForNexusEndpointsReady( + envconfigOpts: LoadClientProfileOptions, + endpoints: readonly NexusEndpointTarget[] +): Promise { + const { namespace, connectionOptions } = loadClientConnectConfig(envconfigOpts); + const { address, apiKey, metadata, tls } = connectionOptions; + const connection = await Connection.connect({ address, apiKey, metadata, tls }); + try { + const nativeConnection = await NativeConnection.connect({ address, apiKey, metadata, tls }); + try { + const echoHandler = nexus.serviceHandler(nexusEndpointProbeService, { echo: async (_ctx, input) => input }); + const workers = await Promise.all([ + Worker.create({ + connection: nativeConnection, + namespace, + taskQueue: CALLER_TASK_QUEUE, + workflowsPath: require.resolve('./workflows/nexus-endpoint-probe'), + }), + // One handler worker per endpoint, each with a single poller to keep the number of open polls down. + ...endpoints.map(({ taskQueue }) => + Worker.create({ + connection: nativeConnection, + namespace, + taskQueue, + nexusServices: [echoHandler], + nexusTaskPollerBehavior: { type: 'simple-maximum', maximum: 1 }, + }) + ), + ]); + const client = new Client({ connection, namespace }); + const probes = Promise.all(endpoints.map(({ name }) => callUntilReady(client, name))); + // Let every worker shut down before reporting a failure and closing the connections. + const results = await Promise.allSettled(workers.map((worker) => worker.runUntil(probes))); + const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected'); + if (failure) throw failure.reason; + } finally { + await nativeConnection.close(); + } + } finally { + await connection.close(); + } + + console.log(`All ${endpoints.length} Nexus endpoints responded; waiting ${SETTLE_MS}ms for the remaining caches`); + await sleep(SETTLE_MS); +} diff --git a/packages/test/src/nexus-endpoints.ts b/packages/test/src/nexus-endpoints.ts new file mode 100644 index 0000000000..f3dec53dd3 --- /dev/null +++ b/packages/test/src/nexus-endpoints.ts @@ -0,0 +1,51 @@ +/** + * Which Nexus endpoints the integration tests need, and how a test finds its endpoint. + * + * Locally, `registerNexusEndpoint()` creates each endpoint through the OperatorService. Temporal Cloud only allows + * endpoint management through the Cloud Ops API, and new endpoints take minutes to propagate. So for Cloud runs, + * `.github/scripts/cloud-namespace.ts` creates every endpoint in the manifest up front, and tests compute the name + * of their endpoint instead of creating it. + */ +// Bare specifiers: test files bundle this module into workflow code, and the bundler ignores these. +import { createHash } from 'crypto'; +import { basename } from 'path'; +import { nexusEndpointManifest } from './nexus-endpoint-manifest'; + +/** Set when endpoints were created before the run; their names start with this prefix. */ +export const NEXUS_ENDPOINT_PREFIX_ENV = 'TEMPORAL_TEST_NEXUS_ENDPOINT_PREFIX'; + +/** + * Manifest key for a test file path or `file:` URL: the file name without suffixes such as `.cloud-unavailable`, or + * extension. + */ +export function nexusSuiteName(testFile: string): string { + return basename(testFile).split('.')[0]; +} + +/** + * Name of the pre-created endpoint that routes to `taskQueue`. Task queues come from test titles, which are too + * long and loosely formatted to use in endpoint names directly. + */ +export function preCreatedNexusEndpointName(prefix: string, taskQueue: string): string { + return `${prefix}-${createHash('sha256').update(taskQueue).digest('hex').slice(0, 16)}`; +} + +/** Fail unless the manifest lists `taskQueue` for `testFile`, so that every server a test runs on has its endpoint. */ +export function assertNexusEndpointInManifest(testFile: string, taskQueue: string): void { + const suite = nexusSuiteName(testFile); + if (!nexusEndpointManifest[suite]?.includes(taskQueue)) { + throw new Error( + `Task queue '${taskQueue}' is missing from the Nexus endpoint manifest. ` + + `Add it under '${suite}' in packages/test/src/nexus-endpoint-manifest.ts so that Cloud runs create its endpoint.` + ); + } +} + +/** Task queues that need an endpoint when running `testFiles`. */ +export function nexusEndpointTaskQueues(testFiles: readonly string[]): string[] { + const taskQueues = new Set(); + for (const testFile of testFiles) { + for (const taskQueue of nexusEndpointManifest[nexusSuiteName(testFile)] ?? []) taskQueues.add(taskQueue); + } + return [...taskQueues].sort(); +} diff --git a/packages/test/src/test-integration-extstore-nexus.cloud-unavailable.ts b/packages/test/src/test-integration-extstore-nexus.ts similarity index 100% rename from packages/test/src/test-integration-extstore-nexus.cloud-unavailable.ts rename to packages/test/src/test-integration-extstore-nexus.ts diff --git a/packages/test/src/test-nexus-endpoints.ts b/packages/test/src/test-nexus-endpoints.ts new file mode 100644 index 0000000000..c167560ac4 --- /dev/null +++ b/packages/test/src/test-nexus-endpoints.ts @@ -0,0 +1,37 @@ +import test from 'ava'; +import { nexusEndpointManifest } from './nexus-endpoint-manifest'; +import { + assertNexusEndpointInManifest, + nexusEndpointTaskQueues, + nexusSuiteName, + preCreatedNexusEndpointName, +} from './nexus-endpoints'; + +test('nexusSuiteName strips directories, availability suffixes, and extensions', (t) => { + t.is( + nexusSuiteName('file:///repo/packages/test/lib/test-nexus-standalone.cloud-unavailable.js'), + 'test-nexus-standalone' + ); + t.is(nexusSuiteName('./lib/test-nexus-query-operation.js'), 'test-nexus-query-operation'); +}); + +test('pre-created endpoint names are valid Cloud endpoint names and unique per task queue', (t) => { + const taskQueues = nexusEndpointTaskQueues(Object.keys(nexusEndpointManifest)); + const names = taskQueues.map((taskQueue) => preCreatedNexusEndpointName('sdk-typescript-ci-1-1', taskQueue)); + for (const name of names) t.regex(name, /^[a-z][a-z0-9-]*[a-z0-9]$/); + t.is(new Set(names).size, taskQueues.length); +}); + +test('no task queue appears in more than one suite', (t) => { + const suites = Object.values(nexusEndpointManifest); + const total = suites.reduce((count, taskQueues) => count + taskQueues.length, 0); + t.is(nexusEndpointTaskQueues(Object.keys(nexusEndpointManifest)).length, total); +}); + +test('assertNexusEndpointInManifest rejects task queues missing from the manifest', (t) => { + const [suite, taskQueues] = Object.entries(nexusEndpointManifest)[0]; + t.notThrows(() => assertNexusEndpointInManifest(`./lib/${suite}.cloud-unavailable.js`, taskQueues[0])); + t.throws(() => assertNexusEndpointInManifest(`./lib/${suite}.js`, 'not-in-the-manifest'), { + message: /'not-in-the-manifest' is missing from the Nexus endpoint manifest/, + }); +}); diff --git a/packages/test/src/test-nexus-workflow-caller.cloud-unavailable.ts b/packages/test/src/test-nexus-workflow-caller.cloud-unavailable.ts index 4159fb95b7..7697f0cc87 100644 --- a/packages/test/src/test-nexus-workflow-caller.cloud-unavailable.ts +++ b/packages/test/src/test-nexus-workflow-caller.cloud-unavailable.ts @@ -821,315 +821,295 @@ test('WorkflowRunOperationHandler attaches links and callbacks - caller workflow test('Nexus sync and async Operations from a Workflow', async (t) => { const { createWorker, executeWorkflow, registerNexusEndpoint } = helpers(t); - const { endpointName, endpointIdentifier } = await registerNexusEndpoint(); - try { - const worker = await createWorker({ - nexusServices: [ - nexus.serviceHandler(multiOpService, { - async syncOp(_ctx, action) { - if (action === 'pass') { - return action; - } - if (action === 'throwHandlerError') { - throw new nexus.HandlerError('INTERNAL', 'test asked to fail', { retryableOverride: false }); - } - throw new nexus.HandlerError('BAD_REQUEST', 'invalid action'); - }, - asyncOp: new temporalnexus.WorkflowRunOperationHandler(async (ctx, action) => { - if (action === 'throwOperationError') { - throw new nexus.OperationError('failed', 'some message'); - } - if (action === 'throwApplicationFailure') { - throw ApplicationFailure.create({ - nonRetryable: true, - message: 'test asked to fail', - type: 'IntentionalError', - details: ['a detail'], - }); - } - return await temporalnexus.startWorkflow(ctx, multiOpHandler, { - workflowId: randomUUID(), - args: [action], + const { endpointName } = await registerNexusEndpoint(); + const worker = await createWorker({ + nexusServices: [ + nexus.serviceHandler(multiOpService, { + async syncOp(_ctx, action) { + if (action === 'pass') { + return action; + } + if (action === 'throwHandlerError') { + throw new nexus.HandlerError('INTERNAL', 'test asked to fail', { retryableOverride: false }); + } + throw new nexus.HandlerError('BAD_REQUEST', 'invalid action'); + }, + asyncOp: new temporalnexus.WorkflowRunOperationHandler(async (ctx, action) => { + if (action === 'throwOperationError') { + throw new nexus.OperationError('failed', 'some message'); + } + if (action === 'throwApplicationFailure') { + throw ApplicationFailure.create({ + nonRetryable: true, + message: 'test asked to fail', + type: 'IntentionalError', + details: ['a detail'], }); - }), + } + return await temporalnexus.startWorkflow(ctx, multiOpHandler, { + workflowId: randomUUID(), + args: [action], + }); }), - ], + }), + ], + }); + await worker.runUntil(async () => { + let res = await executeWorkflow(multiOpCaller, { + args: [endpointName, 'syncOp', 'pass'], }); - await worker.runUntil(async () => { - let res = await executeWorkflow(multiOpCaller, { - args: [endpointName, 'syncOp', 'pass'], - }); - t.is(res, 'pass'); - let err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'syncOp', 'throwHandlerError'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof nexus.HandlerError && - err.cause.cause.type === 'INTERNAL' - ); + t.is(res, 'pass'); + let err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'syncOp', 'throwHandlerError'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof nexus.HandlerError && + err.cause.cause.type === 'INTERNAL' + ); - res = await executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'pass'], - }); - t.is(res, 'pass'); - err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'waitForCancel'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof CancelledFailure - ); + res = await executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'pass'], + }); + t.is(res, 'pass'); + err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'waitForCancel'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof CancelledFailure + ); - err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'throwOperationError'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof ApplicationFailure - ); + err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'throwOperationError'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof ApplicationFailure + ); - err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'throwApplicationFailure'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - assert(err instanceof WorkflowFailedError); - assert(err.cause instanceof NexusOperationFailure); - assert(err.cause.cause instanceof nexus.HandlerError); - t.is(err.cause.cause.type, 'INTERNAL'); - const appFailure = unwrapHandlerErrorCause(err.cause.cause); - assert(appFailure instanceof ApplicationFailure); - t.is(appFailure.message, 'test asked to fail'); - t.deepEqual(appFailure.details, ['a detail']); - - err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'failWorkflow'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof ApplicationFailure && - err.cause.cause.message === 'test asked to fail' && - err.cause.cause.details?.length === 1 && - err.cause.cause.details[0] === 'a detail' - ); - }); - } finally { - await t.context.env.deleteNexusEndpoint(endpointIdentifier); - } + err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'throwApplicationFailure'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + assert(err instanceof WorkflowFailedError); + assert(err.cause instanceof NexusOperationFailure); + assert(err.cause.cause instanceof nexus.HandlerError); + t.is(err.cause.cause.type, 'INTERNAL'); + const appFailure = unwrapHandlerErrorCause(err.cause.cause); + assert(appFailure instanceof ApplicationFailure); + t.is(appFailure.message, 'test asked to fail'); + t.deepEqual(appFailure.details, ['a detail']); + + err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'failWorkflow'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof ApplicationFailure && + err.cause.cause.message === 'test asked to fail' && + err.cause.cause.details?.length === 1 && + err.cause.cause.details[0] === 'a detail' + ); + }); }); test('calling a nonexistent service returns NOT_FOUND', async (t) => { const { createWorker, executeWorkflow, registerNexusEndpoint } = helpers(t); - const { endpointName, endpointIdentifier } = await registerNexusEndpoint(); - try { - const worker = await createWorker({ - nexusServices: [ - nexus.serviceHandler(multiOpService, { - async syncOp(_ctx, input) { - return input; - }, - asyncOp: { - async start() { - throw new Error('not implemented'); - }, - async cancel() {}, + const { endpointName } = await registerNexusEndpoint(); + const worker = await createWorker({ + nexusServices: [ + nexus.serviceHandler(multiOpService, { + async syncOp(_ctx, input) { + return input; + }, + asyncOp: { + async start() { + throw new Error('not implemented'); }, + async cancel() {}, + }, + }), + ], + }); + await worker.runUntil(async () => { + const err = await t.throwsAsync( + () => + executeWorkflow(callNonExistentService, { + args: [endpointName], }), - ], - }); - await worker.runUntil(async () => { - const err = await t.throwsAsync( - () => - executeWorkflow(callNonExistentService, { - args: [endpointName], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof nexus.HandlerError && - err.cause.cause.type === 'NOT_FOUND' - ); - }); - } finally { - await t.context.env.deleteNexusEndpoint(endpointIdentifier); - } + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof nexus.HandlerError && + err.cause.cause.type === 'NOT_FOUND' + ); + }); }); test('inbound startOperation interceptor can modify input and result', async (t) => { const { createWorker, executeWorkflow, registerNexusEndpoint } = helpers(t); - const { endpointName, endpointIdentifier } = await registerNexusEndpoint(); - try { - const observedResults: nexus.HandlerStartOperationResult[] = []; - const worker = await createWorker({ - nexusServices: [ - nexus.serviceHandler(multiOpService, { - async syncOp(_ctx, input) { - return input; + const { endpointName } = await registerNexusEndpoint(); + const observedResults: nexus.HandlerStartOperationResult[] = []; + const worker = await createWorker({ + nexusServices: [ + nexus.serviceHandler(multiOpService, { + async syncOp(_ctx, input) { + return input; + }, + asyncOp: new temporalnexus.WorkflowRunOperationHandler(async (ctx, input) => { + return await temporalnexus.startWorkflow(ctx, multiOpHandler, { workflowId: randomUUID(), args: [input] }); + }), + }), + ], + interceptors: { + nexus: [ + () => ({ + inbound: { + async startOperation(input, next) { + const output = await next({ ...input, input: input.input + ' modified' }); + const { result } = output; + observedResults.push(result); + if (!result.isAsync) { + return { result: nexus.HandlerStartOperationResult.sync(result.value + ' intercepted') }; + } + return output; + }, }, - asyncOp: new temporalnexus.WorkflowRunOperationHandler(async (ctx, input) => { - return await temporalnexus.startWorkflow(ctx, multiOpHandler, { workflowId: randomUUID(), args: [input] }); - }), }), ], - interceptors: { - nexus: [ - () => ({ - inbound: { - async startOperation(input, next) { - const output = await next({ ...input, input: input.input + ' modified' }); - const { result } = output; - observedResults.push(result); - if (!result.isAsync) { - return { result: nexus.HandlerStartOperationResult.sync(result.value + ' intercepted') }; - } - return output; - }, - }, - }), - ], - }, - }); - await worker.runUntil(async () => { - const res = await executeWorkflow(multiOpCaller, { - args: [endpointName, 'syncOp', 'hello'], - }); - t.is(res, 'hello modified intercepted'); + }, + }); + await worker.runUntil(async () => { + const res = await executeWorkflow(multiOpCaller, { + args: [endpointName, 'syncOp', 'hello'], }); - t.is(observedResults.length, 1); - const result = observedResults[0]; - t.false(result.isAsync); - if (!result.isAsync) { - t.is(result.value, 'hello modified'); - } - } finally { - await t.context.env.deleteNexusEndpoint(endpointIdentifier); + t.is(res, 'hello modified intercepted'); + }); + t.is(observedResults.length, 1); + const result = observedResults[0]; + t.false(result.isAsync); + if (!result.isAsync) { + t.is(result.value, 'hello modified'); } }); test('inbound cancelOperation interceptor can modify input', async (t) => { const { createWorker, executeWorkflow, registerNexusEndpoint } = helpers(t); - const { endpointName, endpointIdentifier } = await registerNexusEndpoint(); - try { - const receivedTokens: string[] = []; - const worker = await createWorker({ - nexusServices: [ - nexus.serviceHandler(multiOpService, { - async syncOp(_ctx, input) { - return input; + const { endpointName } = await registerNexusEndpoint(); + const receivedTokens: string[] = []; + const worker = await createWorker({ + nexusServices: [ + nexus.serviceHandler(multiOpService, { + async syncOp(_ctx, input) { + return input; + }, + asyncOp: { + async start(_ctx, _input) { + return nexus.HandlerStartOperationResult.async('original-token'); }, - asyncOp: { - async start(_ctx, _input) { - return nexus.HandlerStartOperationResult.async('original-token'); - }, - async cancel(_ctx, token) { - receivedTokens.push(token); + async cancel(_ctx, token) { + receivedTokens.push(token); + }, + }, + }), + ], + interceptors: { + nexus: [ + () => ({ + inbound: { + async cancelOperation(input, next) { + return await next({ ...input, token: input.token + '-modified' }); }, }, }), ], - interceptors: { - nexus: [ - () => ({ - inbound: { - async cancelOperation(input, next) { - return await next({ ...input, token: input.token + '-modified' }); - }, - }, - }), - ], - }, - }); - await worker.runUntil(async () => { - const err = await t.throwsAsync( - () => - executeWorkflow(multiOpCaller, { - args: [endpointName, 'asyncOp', 'waitForCancel', 'WAIT_CANCELLATION_REQUESTED'], - }), - { - instanceOf: WorkflowFailedError, - } - ); - t.true( - err instanceof WorkflowFailedError && - err.cause instanceof NexusOperationFailure && - err.cause.cause instanceof CancelledFailure - ); - }); - t.is(receivedTokens.length, 1); - t.is(receivedTokens[0], 'original-token-modified'); - } finally { - await t.context.env.deleteNexusEndpoint(endpointIdentifier); - } + }, + }); + await worker.runUntil(async () => { + const err = await t.throwsAsync( + () => + executeWorkflow(multiOpCaller, { + args: [endpointName, 'asyncOp', 'waitForCancel', 'WAIT_CANCELLATION_REQUESTED'], + }), + { + instanceOf: WorkflowFailedError, + } + ); + t.true( + err instanceof WorkflowFailedError && + err.cause instanceof NexusOperationFailure && + err.cause.cause instanceof CancelledFailure + ); + }); + t.is(receivedTokens.length, 1); + t.is(receivedTokens[0], 'original-token-modified'); }); test('NexusServiceClient is type-safe in regard to Operation Definitions', async (t) => { const { createWorker, executeWorkflow, registerNexusEndpoint } = helpers(t); - const { endpointName, endpointIdentifier } = await registerNexusEndpoint(); - try { - // We intentionally use different property names here, to assert that the client side sent the - // correct op name to the server (i.e. the operation's name, not the operation property name). - const typeSafetyHandlerService = nexus.service('typeSafetyService', { - implicitImpl: nexus.operation({ name: 'implicit' }), - explicitImpl: nexus.operation({ name: 'my-custom-operation-name' }), - }); + const { endpointName } = await registerNexusEndpoint(); + // We intentionally use different property names here, to assert that the client side sent the + // correct op name to the server (i.e. the operation's name, not the operation property name). + const typeSafetyHandlerService = nexus.service('typeSafetyService', { + implicitImpl: nexus.operation({ name: 'implicit' }), + explicitImpl: nexus.operation({ name: 'my-custom-operation-name' }), + }); - const worker = await createWorker({ - nexusServices: [ - nexus.serviceHandler(typeSafetyHandlerService, { - implicitImpl: async (_ctx, input) => input, - explicitImpl: async (_ctx, input) => input, - }), - ], - }); - await worker.runUntil(async () => { - await executeWorkflow(clientOperationTypeSafetyCheckerWorkflow, { - args: [endpointName], - }); + const worker = await createWorker({ + nexusServices: [ + nexus.serviceHandler(typeSafetyHandlerService, { + implicitImpl: async (_ctx, input) => input, + explicitImpl: async (_ctx, input) => input, + }), + ], + }); + await worker.runUntil(async () => { + await executeWorkflow(clientOperationTypeSafetyCheckerWorkflow, { + args: [endpointName], }); + }); - // Most of the checks here would be exposed as compile-time errors, - // and `executeWorkflow` will have thrown if any runtime error. - t.pass(); - } finally { - await t.context.env.deleteNexusEndpoint(endpointIdentifier); - } + // Most of the checks here would be exposed as compile-time errors, + // and `executeWorkflow` will have thrown if any runtime error. + t.pass(); }); //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/packages/test/src/workflows/nexus-endpoint-probe.ts b/packages/test/src/workflows/nexus-endpoint-probe.ts new file mode 100644 index 0000000000..552cfba9a4 --- /dev/null +++ b/packages/test/src/workflows/nexus-endpoint-probe.ts @@ -0,0 +1,12 @@ +import * as nexus from 'nexus-rpc'; +import * as workflow from '@temporalio/workflow'; + +export const nexusEndpointProbeService = nexus.service('nexus-endpoint-probe', { + echo: nexus.operation(), +}); + +/** Call the probe service's echo operation through `endpoint`. Used to check that an endpoint is routable. */ +export async function nexusEndpointProbeCaller(endpoint: string, input: string): Promise { + const client = workflow.createNexusServiceClient({ endpoint, service: nexusEndpointProbeService }); + return await client.executeOperation('echo', input, { scheduleToCloseTimeout: '10s' }); +}