Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
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 <noreply@anthropic.com>
  • Loading branch information
THardy98 and claude committed Oct 13, 2026
commit d14b5f5052bed9926a51ca0c54c8422a3a0829c0
133 changes: 131 additions & 2 deletions .github/scripts/cloud-namespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -58,9 +65,85 @@ async function withCloudClient(fn: (client: CloudOperationsClient) => Promise<vo
}
}

function rejections(results: readonly PromiseSettledResult<void>[]): unknown[] {
return results.filter((result) => result.status === 'rejected').map((result) => result.reason);
}

async function listNexusEndpoints(
client: CloudOperationsClient,
targetNamespaceId?: string
): Promise<CloudNexusEndpoint[]> {
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<string[]> {
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<void> {
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<void> {
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<void> {
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<void> {
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: {
Expand All @@ -81,8 +164,49 @@ async function create(): Promise<void> {
});
}

/**
* 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<void> {
// 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<void> {
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`);
Expand All @@ -94,14 +218,19 @@ async function deleteNamespace(namespace: string): Promise<void> {
});
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<void> {
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 <namespace>');
throw new Error('Usage: cloud-namespace.ts create | nexus-endpoints <namespace> | delete <namespace>');
}

main().catch((error) => {
Expand Down
12 changes: 11 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
28 changes: 19 additions & 9 deletions packages/test/src/helpers-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -34,6 +34,12 @@ import {
Worker,
} from '@temporalio/test-helpers';

import {
assertNexusEndpointInManifest,
NEXUS_ENDPOINT_PREFIX_ENV,
preCreatedNexusEndpointName,
} from './nexus-endpoints';

export { defaultSAKeys, createLocalTestEnvironment };

/**
Expand Down Expand Up @@ -155,9 +161,11 @@ export interface Helpers extends BaseHelpers {
assertWorkflowUpdateFailed(p: Promise<any>, causeConstructor: ErrorConstructor, message?: string): Promise<void>;
assertWorkflowFailedError(p: Promise<any>, causeConstructor: ErrorConstructor, message?: string): Promise<void>;
updateHasBeenAdmitted(handle: WorkflowHandle<workflow.Workflow>, updateId: string): Promise<boolean>;
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 }>;
}

/**
Expand Down Expand Up @@ -243,18 +251,20 @@ export function helpers(t: ExecutionContext<Context>, 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(() =>
testEnv.deleteNexusEndpoint(endpointIdentifier).catch(() => {
/* ignore cleanup errors */
})
);
return { endpointName, endpointIdentifier };
return { endpointName };
} catch (err) {
if (err instanceof Error) {
err.message = `Failed to register Nexus endpoint '${endpointName}': ${err.message}`;
Expand Down
117 changes: 117 additions & 0 deletions packages/test/src/nexus-endpoint-manifest.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, readonly string[]>> = {
'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',
],
};
Loading