import * as grpc from "@grpc/grpc-js"; import { TOrchestrator } from "../types/orchestrator.type"; import { TInput } from "../types/input.type"; import { OrchestrationState } from "../orchestration/orchestration-state"; import { PurgeResult } from "../orchestration/orchestration-purge-result"; import { PurgeInstanceCriteria } from "../orchestration/orchestration-purge-criteria"; import { PurgeInstanceOptions } from "../orchestration/orchestration-purge-options"; import { TerminateInstanceOptions } from "../orchestration/orchestration-terminate-options"; import { MetadataGenerator } from "../utils/grpc-helper.util"; import { OrchestrationQuery, ListInstanceIdsOptions } from "../orchestration/orchestration-query"; import { Page, AsyncPageable } from "../orchestration/page"; import { HistoryEvent } from "../orchestration/history-event"; import { Logger } from "../types/logger.type"; import { StartOrchestrationOptions } from "../task/options"; import { EntityInstanceId } from "../entities/entity-instance-id"; import { EntityMetadata } from "../entities/entity-metadata"; import { EntityQuery } from "../entities/entity-query"; import { SignalEntityOptions } from "../entities/signal-entity-options"; import { CleanEntityStorageRequest, CleanEntityStorageResult } from "../entities/clean-entity-storage"; export { MetadataGenerator } from "../utils/grpc-helper.util"; /** * Options for creating a TaskHubGrpcClient. */ export interface TaskHubGrpcClientOptions { /** The host address to connect to. Defaults to "localhost:4001". */ hostAddress?: string; /** gRPC channel options. */ options?: grpc.ChannelOptions; /** Whether to use TLS. Defaults to false. */ useTLS?: boolean; /** Optional pre-configured channel credentials. If provided, useTLS is ignored. */ credentials?: grpc.ChannelCredentials; /** Optional function to generate per-call metadata (for taskhub, auth tokens, etc.). */ metadataGenerator?: MetadataGenerator; /** Optional logger instance. Defaults to ConsoleLogger. */ logger?: Logger; /** * The default version to use when starting new orchestrations without an explicit version. * If specified, this will be used as the version for orchestrations that don't provide * their own version in StartOrchestrationOptions. */ defaultVersion?: string; } export declare class TaskHubGrpcClient { private _stub; private _metadataGenerator?; private _logger; private _defaultVersion?; /** * Creates a new TaskHubGrpcClient instance. * * @param options Configuration options for the client. */ constructor(options: TaskHubGrpcClientOptions); /** * Creates a new TaskHubGrpcClient instance. * * @param hostAddress The host address to connect to. Defaults to "localhost:4001". * @param options gRPC channel options. * @param useTLS Whether to use TLS. Defaults to false. * @param credentials Optional pre-configured channel credentials. If provided, useTLS is ignored. * @param metadataGenerator Optional function to generate per-call metadata (for taskhub, auth tokens, etc.). * @param logger Optional logger instance. Defaults to ConsoleLogger. * @deprecated Use the options object constructor instead. */ constructor(hostAddress?: string, options?: grpc.ChannelOptions, useTLS?: boolean, credentials?: grpc.ChannelCredentials, metadataGenerator?: MetadataGenerator, logger?: Logger); stop(): Promise; /** * Schedules a new orchestrator using the DurableTask client. * * @param {TOrchestrator | string} orchestrator - The orchestrator or the name of the orchestrator to be scheduled. * @return {Promise} A Promise resolving to the unique ID of the scheduled orchestrator instance. */ scheduleNewOrchestration(orchestrator: TOrchestrator | string, input?: TInput, instanceId?: string, startAt?: Date): Promise; /** * Schedules a new orchestrator using the DurableTask client. * * @param {TOrchestrator | string} orchestrator - The orchestrator or the name of the orchestrator to be scheduled. * @param {TInput} input - Optional input for the orchestrator. * @param {StartOrchestrationOptions} options - Options for instance ID, start time, and tags. * @return {Promise} A Promise resolving to the unique ID of the scheduled orchestrator instance. */ scheduleNewOrchestration(orchestrator: TOrchestrator | string, input?: TInput, options?: StartOrchestrationOptions): Promise; /** * Fetches orchestrator instance metadata from the configured durable store. * * @param {string} instanceId - The unique identifier of the orchestrator instance to fetch. * @param {boolean} fetchPayloads - Indicates whether to fetch the orchestrator instance's * inputs, outputs, and custom status (true) or omit them (false). * @returns {Promise} A Promise that resolves to a metadata record describing * the orchestrator instance and its execution status, or undefined * if the instance is not found. */ getOrchestrationState(instanceId: string, fetchPayloads?: boolean): Promise; /** * Waits for a orchestrator to start running and returns a {@link OrchestrationState} object * containing metadata about the started instance, and optionally, its input, output, * and custom status payloads. * * A "started" orchestrator instance refers to any instance not in the Pending state. * * If a orchestrator instance is already running when this method is called, it returns immediately. * * @param {string} instanceId - The unique identifier of the orchestrator instance to wait for. * @param {boolean} fetchPayloads - Indicates whether to fetch the orchestrator instance's * inputs, outputs (true) or omit them (false). * @param {number} timeout - The amount of time, in seconds, to wait for the orchestrator instance to start. * @returns {Promise} A Promise that resolves to the orchestrator instance metadata * or undefined if no such instance is found. */ waitForOrchestrationStart(instanceId: string, fetchPayloads?: boolean, timeout?: number): Promise; /** * Waits for a orchestrator to complete running and returns a {@link OrchestrationState} object * containing metadata about the completed instance, and optionally, its input, output, * and custom status payloads. * * A "completed" orchestrator instance refers to any instance in one of the terminal states. * For example, the Completed, Failed, or Terminated states. * * If a orchestrator instance is already running when this method is called, it returns immediately. * * @param {string} instanceId - The unique identifier of the orchestrator instance to wait for. * @param {boolean} fetchPayloads - Indicates whether to fetch the orchestrator instance's * inputs, outputs (true) or omit them (false). * @param {number} timeout - The amount of time, in seconds, to wait for the orchestrator instance to start. * @returns {Promise} A Promise that resolves to the orchestrator instance metadata * or undefined if no such instance is found. */ waitForOrchestrationCompletion(instanceId: string, fetchPayloads?: boolean, timeout?: number): Promise; /** * Sends an event notification message to an awaiting orchestrator instance. * * This method triggers the specified event in a running orchestrator instance, * allowing the orchestrator to respond to the event if it has defined event handlers. * * @param {string} instanceId - The unique identifier of the orchestrator instance that will handle the event. * @param {string} eventName - The name of the event. Event names are case-insensitive. * @param {any} [data] - An optional serializable data payload to include with the event. */ raiseOrchestrationEvent(instanceId: string, eventName: string, data?: any): Promise; /** * Terminates the orchestrator associated with the provided instance id. * * @param {string} instanceId - orchestrator instance id to terminate. * @param {any | TerminateInstanceOptions} outputOrOptions - The optional output to set for the terminated orchestrator instance, * or a TerminateInstanceOptions object created with `terminateOptions()` that can include both * output and recursive termination settings. * * @example * ```typescript * // Simple termination with output * await client.terminateOrchestration(instanceId, { reason: "cancelled" }); * * // Recursive termination with options (use terminateOptions helper) * import { terminateOptions } from "@microsoft/durabletask-js"; * await client.terminateOrchestration(instanceId, terminateOptions({ * output: { reason: "cancelled" }, * recursive: true * })); * ``` */ terminateOrchestration(instanceId: string, outputOrOptions?: any | TerminateInstanceOptions): Promise; suspendOrchestration(instanceId: string): Promise; resumeOrchestration(instanceId: string): Promise; /** * Rewinds a failed orchestration instance to a previous state to allow it to retry from the point of failure. * * This method is used to "rewind" a failed orchestration back to its last known good state, allowing it * to be replayed from that point. This is particularly useful for recovering from transient failures * or for debugging purposes. * * Only orchestration instances in the `Failed` state can be rewound. * * @param instanceId - The unique identifier of the orchestration instance to rewind. * @param reason - A reason string describing why the orchestration is being rewound. * @throws {Error} If the orchestration instance is not found. * @throws {Error} If the orchestration instance is in a state that does not allow rewinding. * @throws {Error} If the rewind operation is not supported by the backend. */ rewindInstance(instanceId: string, reason: string): Promise; /** * Restarts an existing orchestration instance with its original input. * * This method allows you to restart a completed, failed, or terminated orchestration * instance. The restarted orchestration will use the same input that was provided * when the orchestration was originally started. * * @param instanceId - The unique ID of the orchestration instance to restart. * @param restartWithNewInstanceId - If true, the restarted orchestration will be assigned * a new instance ID. If false (default), the same instance ID will be reused. * When reusing the same instance ID, the orchestration must be in a terminal state * (Completed, Failed, or Terminated). * @returns A Promise that resolves to the instance ID of the restarted orchestration. * This will be the same as the input instanceId if restartWithNewInstanceId is false, * or a new ID if restartWithNewInstanceId is true. * @throws Error if the orchestration instance is not found. * @throws Error if the orchestration cannot be restarted (e.g., it's still running * and restartWithNewInstanceId is false). */ restartOrchestration(instanceId: string, restartWithNewInstanceId?: boolean): Promise; /** * Purges orchestration instance metadata from the durable store. * * This method can be used to permanently delete orchestration metadata from the underlying storage provider, * including any stored inputs, outputs, and orchestration history records. This is often useful for implementing * data retention policies and for keeping storage costs minimal. Only orchestration instances in the * `Completed`, `Failed`, or `Terminated` state can be purged. * * If the target orchestration instance is not found in the data store, or if the instance is found but not in a * terminal state, then the returned {@link PurgeResult} will report that zero instances were purged. * Otherwise, the existing data will be purged, and the returned {@link PurgeResult} will report that one instance * was purged. * * @param value - The unique ID of the orchestration instance to purge or orchestration instance filter criteria used * to determine which instances to purge. * @param options - Optional options to control the purge behavior, such as recursive purging of sub-orchestrations. * @returns A Promise that resolves to a {@link PurgeResult} or `undefined` if the purge operation was not successful. */ purgeOrchestration(value: string | PurgeInstanceCriteria, options?: PurgeInstanceOptions): Promise; /** * Queries orchestration instances and returns an async iterable of results. * * This method supports querying orchestration instances by various filter criteria including * creation time range, runtime status, instance ID prefix, and task hub names. * * The results are returned as an AsyncPageable that supports both iteration over individual * items and iteration over pages. * * @example * ```typescript * // Iterate over all matching instances * const logger = new ConsoleLogger(); * const pageable = client.getAllInstances({ statuses: [OrchestrationStatus.COMPLETED] }); * for await (const instance of pageable) { * logger.info(instance.instanceId); * } * * // Iterate over pages * for await (const page of pageable.asPages()) { * logger.info(`Page has ${page.values.length} items`); * } * ``` * * @param filter - Optional filter criteria for the query. * @returns An AsyncPageable of OrchestrationState objects. */ getAllInstances(filter?: OrchestrationQuery): AsyncPageable; /** * Lists orchestration instance IDs that match the specified runtime status * and completed time range, using key-based pagination. * * This method is optimized for listing instance IDs without fetching full instance metadata, * making it more efficient when only instance IDs are needed. * * @example * ```typescript * // Get first page of completed instances * const page = await client.listInstanceIds({ * runtimeStatus: [OrchestrationStatus.COMPLETED], * pageSize: 50 * }); * * // Get next page using the continuation key * if (page.hasMoreResults) { * const nextPage = await client.listInstanceIds({ * runtimeStatus: [OrchestrationStatus.COMPLETED], * pageSize: 50, * lastInstanceKey: page.continuationToken * }); * } * ``` * * @param options - Optional filter criteria and pagination options. * @returns A Promise that resolves to a Page of instance IDs. */ listInstanceIds(options?: ListInstanceIdsOptions): Promise>; /** * Retrieves the history of the specified orchestration instance as a list of HistoryEvent objects. * * This method streams the history events from the backend and returns them as an array. * The history includes all events that occurred during the orchestration execution, * such as task scheduling, completion, failure, timer events, and more. * * If the orchestration instance does not exist, an empty array is returned. * * @param instanceId - The unique identifier of the orchestration instance. * @returns A Promise that resolves to an array of HistoryEvent objects representing * the orchestration's history. Returns an empty array if the instance is not found. * @throws {Error} If the instanceId is null or empty. * @throws {Error} If the operation is canceled. * @throws {Error} If an internal error occurs while retrieving the history. * * @example * ```typescript * const history = await client.getOrchestrationHistory(instanceId); * for (const event of history) { * console.log(`Event ${event.eventId}: ${event.type} at ${event.timestamp}`); * } * ``` */ getOrchestrationHistory(instanceId: string): Promise; /** * Signals an entity to perform an operation. * * This method sends a one-way message to an entity, triggering the specified operation. * The method returns as soon as the message has been reliably enqueued; it does not * wait for the operation to be processed by the receiving entity. * * @param id - The ID of the entity to signal. * @param operationName - The name of the operation to invoke. * @param input - Optional input data for the operation. * @param options - Optional signal options (e.g., scheduled time). */ signalEntity(id: EntityInstanceId, operationName: string, input?: unknown, options?: SignalEntityOptions): Promise; /** * Gets the metadata for an entity, optionally including its state. * * @param id - The ID of the entity to get. * @param includeState - Whether to include the entity's state in the response. Defaults to true. * @returns The entity metadata, or undefined if the entity does not exist. */ getEntity(id: EntityInstanceId, includeState?: boolean): Promise | undefined>; /** * Queries for entities matching the specified filter criteria. * * @param query - Optional query filter. If not provided, returns all entities. * @returns An AsyncPageable that can be iterated by items or by pages. * * @remarks * This method handles pagination automatically when iterating by items. * Use `.byPage()` to iterate page by page for more control. * * @example * // Iterate by items * for await (const entity of client.getEntities(query)) { * console.log(entity.id); * } * * @example * // Iterate by pages * for await (const page of client.getEntities(query).byPage()) { * console.log(`Got ${page.values.length} items`); * for (const entity of page.values) { * console.log(entity.id); * } * } */ getEntities(query?: EntityQuery): AsyncPageable>; /** * Cleans entity storage by removing empty entities and/or releasing orphaned locks. * * @param request - The clean request specifying what to clean. Defaults to removing empty entities and releasing orphaned locks. * @param continueUntilComplete - Whether to continue until all cleaning is done, or return after one batch. * @returns The result of the clean operation. */ cleanEntityStorage(request?: CleanEntityStorageRequest, continueUntilComplete?: boolean): Promise; /** * Converts a protobuf EntityMetadata to a typed EntityMetadata. */ private convertEntityMetadata; /** * Helper method to create an OrchestrationState from a protobuf OrchestrationState. */ private _createOrchestrationStateFromProto; }