@camunda8/sdk
Version:
[](https://www.npmjs.com/package/@camunda8/sdk)
745 lines (742 loc) • 27.2 kB
TypeScript
import { LosslessNumber } from 'lossless-json';
import { MaybeTimeDuration } from 'typed-duration';
import { CamundaPlatform8Configuration, DeepPartial } from '../../lib';
import { IHeadersProvider } from '../../oauth';
import { ConnectionStatusEvent } from '../lib/ConnectionStatusEvent';
import { TypedEmitter } from '../lib/TypedEmitter';
import { Resource } from '../lib/deployResource';
import * as ZB from '../lib/interfaces-1.0';
import { ZBWorkerTaskHandler } from '../lib/interfaces-1.0';
import * as Grpc from '../lib/interfaces-grpc-1.0';
import { Loglevel } from '../lib/interfaces-published-contract';
import { ZBWorker } from './ZBWorker';
/**
* Validates settings consistency and logs warnings for conflicting TLS configuration.
*
* @param config The Camunda Platform 8 configuration
*/
export declare function validateTlsSettings(config: CamundaPlatform8Configuration): void;
/**
* A client for interacting with a Zeebe broker. With the connection credentials set in the environment, you can use a "zero-conf" constructor with no arguments.
* All constructor parameters for configuration are optional. If no configuration is provided, the SDK will use environment variables to configure itself.
* See {@link CamundaSDKConfiguration} for the complete list of configuration parameters. Values can be passed in explicitly in code, or set via environment variables (recommended: separate configuration and application logic).
* Explicitly set values will override environment variables, which are merged into the configuration.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.topology().then(info =>
* console.log(JSON.stringify(info, null, 2))
* )
* ```
*/
export declare class ZeebeGrpcClient extends TypedEmitter<typeof ConnectionStatusEvent> {
connectionTolerance: MaybeTimeDuration;
/**
* connected is a ternary that indicates the connection status of the client.
* Undefined means "we don't know the connection status"
* False means "we know we are not connected"
* True means "we know we are connected"
*/
connected?: boolean;
readied: boolean;
gatewayAddress: string;
loglevel: Loglevel;
onReady?: () => void;
onConnectionError?: (err: Error) => void;
private logger;
private closePromise?;
private closing;
private grpc;
private options;
private workerCount;
private workers;
private retry;
private maxRetries;
private maxRetryTimeout;
private oAuthProvider;
private useTLS;
private stdout;
private customSSL?;
private tenantId?;
private config;
private streamWorker?;
constructor(options?: {
config?: DeepPartial<CamundaPlatform8Configuration>;
oAuthProvider?: IHeadersProvider;
});
/**
* `activateJobs` allows you to manually activate jobs, effectively building a worker; rather than using the ZBWorker class.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.activateJobs({
* maxJobsToActivate: 5,
* requestTimeout: 6000,
* timeout: 5 * 60 * 1000,
* type: 'process-payment',
* worker: 'my-worker-uuid'
* }).then(jobs =>
* jobs.forEach(job =>
* // business logic
* zbc.completeJob({
* jobKey: job.key,
* variables: {}
* ))
* )
* })
* ```
*/
activateJobs<Variables = ZB.IInputVariables, CustomHeaders = ZB.ICustomHeaders>(request: Grpc.ActivateJobsRequest & {
inputVariableDto?: {
new (...args: any[]): Readonly<Variables>;
};
customHeadersDto?: {
new (...args: any[]): Readonly<CustomHeaders>;
};
}): Promise<ZB.Job<Variables, CustomHeaders>[]>;
/**
*
* Broadcast a Signal
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.broadcastSignal({
* signalName: 'my-signal',
* variables: { reasonCode: 3 }
* })
*/
broadcastSignal(req: ZB.BroadcastSignalReq): Promise<ZB.BroadcastSignalRes>;
/**
*
* Cancel a process instance by process instance key.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.cancelProcessInstance(processInstanceId)
* .catch(
* (e: any) => console.log(`Error cancelling instance: ${e.message}`)
* )
* ```
*/
cancelProcessInstance(processInstanceKey: string, operationReference?: number | LosslessNumber): Promise<void>;
/**
*
* Create a worker that polls the gateway for jobs and executes a job handler when units of work are available.
* @example
* ```
* const zbc = new ZB.ZeebeGrpcClient()
*
* const zbWorker = zbc.createWorker({
* taskType: 'demo-service',
* taskHandler: myTaskHandler,
* })
*
* // A job handler must return one of job.complete, job.fail, job.error, or job.forward
* // Note: unhandled exceptions in the job handler cause the library to call job.fail
* async function myTaskHandler(job) {
* zbWorker.log('Task variables', job.variables)
*
* // Task worker business logic goes here
* const updateToBrokerVariables = {
* updatedProperty: 'newValue',
* }
*
* const res = await callExternalSystem(job.variables)
*
* if (res.code === 'SUCCESS') {
* return job.complete({
* ...updateToBrokerVariables,
* ...res.values
* })
* }
* if (res.code === 'BUSINESS_ERROR') {
* return job.error({
* code: res.errorCode,
* message: res.message
* })
* }
* if (res.code === 'ERROR') {
* return job.fail({
* errorMessage: res.message,
* retryBackOff: 2000
* })
* }
* }
* ```
*/
createWorker<WorkerInputVariables = ZB.IInputVariables, CustomHeaderShape = ZB.ICustomHeaders, WorkerOutputVariables = ZB.IOutputVariables>(config: ZB.ZBWorkerConfig<WorkerInputVariables, CustomHeaderShape, WorkerOutputVariables>): ZBWorker<WorkerInputVariables, CustomHeaderShape, WorkerOutputVariables>;
/**
* Gracefully shut down all workers, draining existing tasks, and return when it is safe to exit.
*
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.createWorker({
* taskType:
* })
*
* setTimeout(async () => {
* await zbc.close()
* console.log('All work completed.')
* }),
* 5 * 60 * 1000 // 5 mins
* )
* ```
*/
close(timeout?: number): Promise<null>;
/**
*
* Explicitly complete a job. The method is useful for manually constructing a worker.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.activateJobs({
* maxJobsToActivate: 5,
* requestTimeout: 6000,
* timeout: 5 * 60 * 1000,
* type: 'process-payment',
* worker: 'my-worker-uuid'
* }).then(jobs =>
* jobs.forEach(job =>
* // business logic
* zbc.completeJob({
* jobKey: job.key,
* variables: {}
* ))
* )
* })
* ```
*/
completeJob(completeJobRequest: Grpc.CompleteJobRequest): Promise<void>;
/**
*
* Create a new process instance. Asynchronously returns a process instance id.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.createProcessInstance({
* bpmnProcessId: 'onboarding-process',
* variables: {
* customerId: 'uuid-3455'
* },
* version: 5 // optional, will use latest by default
* }).then(res => console.log(JSON.stringify(res, null, 2)))
*
* zbc.createProcessInstance({
* bpmnProcessId: 'SkipFirstTask',
* variables: { id: random },
* startInstructions: [{elementId: 'second_service_task'}]
* }).then(res => (id = res.processInstanceKey))
* ```
*/
createProcessInstance<Variables extends ZB.JSONDoc = ZB.IProcessVariables>(config: ZB.CreateProcessInstanceReq<Variables>): Promise<Grpc.CreateProcessInstanceResponse>;
/**
*
* Create a process instance, and return a Promise that returns the outcome of the process.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.createProcessInstanceWithResult({
* bpmnProcessId: 'order-process',
* variables: {
* customerId: 123,
* invoiceId: 567
* }
* })
* .then(console.log)
* ```
*/
createProcessInstanceWithResult<Variables extends ZB.JSONDoc = ZB.IProcessVariables, Result = ZB.IOutputVariables>(config: ZB.CreateProcessInstanceWithResultReq<Variables>): Promise<Grpc.CreateProcessInstanceWithResultResponse<Result>>;
/**
* Delete a resource.
* @param resourceId - The key of the resource that should be deleted. This can either be the key of a process definition, the key of a decision requirements definition or the key of a form.
* @returns
*/
deleteResource({ resourceKey, operationReference, }: {
resourceKey: string;
operationReference?: number | LosslessNumber;
}): Promise<Record<string, never>>;
/**
*
* Deploys a single resources (e.g. process or decision model) to Zeebe.
*
* Errors:
* PERMISSION_DENIED:
* - if a deployment to an unauthorized tenant is performed
* INVALID_ARGUMENT:
* - no resources given.
* - if at least one resource is invalid. A resource is considered invalid if:
* - the content is not deserializable (e.g. detected as BPMN, but it's broken XML)
* - the content is invalid (e.g. an event-based gateway has an outgoing sequence flow to a task)
* - if multi-tenancy is enabled, and:
* - a tenant id is not provided
* - a tenant id with an invalid format is provided
* - if multi-tenancy is disabled and a tenant id is provided
* @example
* ```
* import {join} from 'path'
* const zbc = new ZeebeGrpcClient()
*
* zbc.deployResource({ processFilename: join(process.cwd(), 'bpmn', 'onboarding.bpmn' })
* zbc.deployResource({ decisionFilename: join(process.cwd(), 'dmn', 'approval.dmn')})
* ```
*/
deployResource(resource: {
processFilename: string;
tenantId?: string;
} | {
name: string;
process: Buffer;
tenantId?: string;
}): Promise<Grpc.DeployResourceResponse<Grpc.ProcessDeployment>>;
deployResource(resource: {
decisionFilename: string;
tenantId?: string;
} | {
name: string;
decision: Buffer;
tenantId?: string;
}): Promise<Grpc.DeployResourceResponse<Grpc.DecisionDeployment>>;
deployResource(resource: {
formFilename: string;
tenantId?: string;
} | {
name: string;
form: Buffer;
tenantId?: string;
}): Promise<Grpc.DeployResourceResponse<Grpc.FormDeployment>>;
/**
*
* Deploys one or more resources (e.g. processes or decision models) to Zeebe.
* Note that this is an atomic call, i.e. either all resources are deployed, or none of them are.
*
* Errors:
* PERMISSION_DENIED:
* - if a deployment to an unauthorized tenant is performed
* INVALID_ARGUMENT:
* - no resources given.
* - if at least one resource is invalid. A resource is considered invalid if:
* - the content is not deserializable (e.g. detected as BPMN, but it's broken XML)
* - the content is invalid (e.g. an event-based gateway has an outgoing sequence flow to a task)
* - if multi-tenancy is enabled, and:
* - a tenant id is not provided
* - a tenant id with an invalid format is provided
* - if multi-tenancy is disabled and a tenant id is provided
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* const result = await zbc.deployResources([
* {
* processFilename: './src/__tests__/testdata/Client-DeployWorkflow.bpmn',
* },
* {
* decisionFilename: './src/__tests__/testdata/quarantine-duration.dmn',
* },
* {
* form: fs.readFileSync('./src/__tests__/testdata/form_1.form'),
* name: 'form_1.form',
* },
* ])
* ```
*/
deployResources(resources: Resource[], tenantId?: string): Promise<Grpc.DeployResourceResponse<unknown>>;
/**
*
* Evaluates a decision. The decision to evaluate can be specified either by using its unique key (as returned by DeployResource), or using the decision ID. When using the decision ID, the latest deployed version of the decision is used.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.evaluateDecision({
* decisionId: 'my-decision',
* variables: { season: "Fall" }
* }).then(res => console.log(JSON.stringify(res, null, 2)))
*/
evaluateDecision(evaluateDecisionRequest: Grpc.EvaluateDecisionRequest): Promise<Grpc.EvaluateDecisionResponse>;
/**
*
* Fail a job. This is useful if you are using the decoupled completion pattern or building your own worker.
* For the retry count, the current count is available in the job metadata.
*
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.failJob( {
* jobKey: '345424343451',
* retries: 3,
* errorMessage: 'Could not get a response from the order invoicing API',
* retryBackOff: 30 * 1000 // optional, otherwise available for reactivation immediately
* })
* ```
*/
failJob(failJobRequest: Grpc.FailJobRequest): Promise<void>;
/**
* Return an array of task types contained in a BPMN file or array of BPMN files. This can be useful, for example, to do
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.getServiceTypesFromBpmn(['bpmn/onboarding.bpmn', 'bpmn/process-sale.bpmn'])
* .then(tasktypes => console.log('The task types are:', tasktypes))
*
* ```
*/
getServiceTypesFromBpmn(files: string | string[]): Promise<string[]>;
/**
*
* Modify a running process instance. This allows you to move the execution tokens, and change the variables. Added in 8.1.
* See the [gRPC protocol documentation](https://docs.camunda.io/docs/apis-clients/grpc/#modifyprocessinstance-rpc).
* @example
* ```
* zbc.createProcessInstance('SkipFirstTask', {}).then(res =>
* zbc.modifyProcessInstance({
* processInstanceKey: res.processInstanceKey,
* activateInstructions: [{
* elementId: 'second_service_task',
* ancestorElementInstanceKey: "-1",
* variableInstructions: [{
* scopeId: '',
* variables: { second: 1}
* }]
* }]
* })
* )
* ```
*/
modifyProcessInstance(modifyProcessInstanceRequest: ZB.ModifyProcessInstanceReq): Promise<Grpc.ModifyProcessInstanceResponse>;
/**
*
* @since 8.5.0
*/
migrateProcessInstance(migrateProcessInstanceRequest: ZB.MigrateProcessInstanceReq): Promise<Grpc.MigrateProcessInstanceResponse>;
/**
* Publish a message to the broker for correlation with a workflow instance. See [this tutorial](https://docs.camunda.io/docs/guides/message-correlation/) for a detailed description of message correlation.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.publishMessage({
* // Should match the "Message Name" in a BPMN Message Catch
* name: 'order_status',
* correlationKey: 'uuid-124-532-5432',
* variables: {
* event: 'PROCESSED'
* }
* })
* ```
*/
publishMessage<ProcessVariables extends {
[key: string]: ZB.JSON;
} = ZB.IProcessVariables>(publishMessageRequest: Grpc.PublishMessageRequest<ProcessVariables>): Promise<Grpc.PublishMessageResponse>;
/**
* Publish a message to the broker for correlation with a workflow message start event.
* For a message targeting a start event, the correlation key is not needed to target a specific running process instance.
* However, the hash of the correlationKey is used to determine the partition where this workflow will start.
* So we assign a random uuid to balance workflow instances created via start message across partitions.
*
* We make the correlationKey optional, because the caller can specify a correlationKey + messageId
* to guarantee an idempotent message.
*
* Multiple messages with the same correlationKey + messageId combination will only start a workflow once.
* See: https://github.com/zeebe-io/zeebe/issues/1012 and https://github.com/zeebe-io/zeebe/issues/1022
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.publishStartMessage({
* name: 'Start_New_Onboarding_Flow',
* variables: {
* customerId: 'uuid-348-234-8908'
* }
* })
*
* // To do the same in an idempotent fashion - note: only idempotent during the lifetime of the created instance.
* zbc.publishStartMessage({
* name: 'Start_New_Onboarding_Flow',
* messageId: 'uuid-348-234-8908', // use customerId to make process idempotent per customer
* variables: {
* customerId: 'uuid-348-234-8908'
* }
* })
* ```
*/
publishStartMessage<ProcessVariables extends ZB.IInputVariables = ZB.IProcessVariables>(publishStartMessageRequest: Grpc.PublishStartMessageRequest<ProcessVariables>): Promise<Grpc.PublishMessageResponse>;
/**
*
* Resolve an incident by incident key.
* @example
* ```
* type JSONObject = {[key: string]: string | number | boolean | JSONObject}
*
* const zbc = new ZeebeGrpcClient()
*
* async updateAndResolveIncident({
* processInstanceId,
* incidentKey,
* variables
* } : {
* processInstanceId: string,
* incidentKey: string,
* variables: JSONObject
* }) {
* await zbc.setVariables({
* elementInstanceKey: processInstanceId,
* variables
* })
* await zbc.updateRetries()
* zbc.resolveIncident({
* incidentKey
* })
* zbc.resolveIncident(incidentKey)
* }
*
* ```
*/
resolveIncident(resolveIncidentRequest: ZB.ResolveIncidentReq): Promise<void>;
/**
*
* Directly modify the variables is a process instance. This can be used with `resolveIncident` to update the process and resolve an incident.
* @example
* ```
* type JSONObject = {[key: string]: string | number | boolean | JSONObject}
*
* const zbc = new ZeebeGrpcClient()
*
* async function updateAndResolveIncident({
* incidentKey,
* processInstanceKey,
* jobKey,
* variableUpdate
* } : {
* incidentKey: string
* processInstanceKey: string
* jobKey: string
* variableUpdate: JSONObject
* }) {
* await zbc.setVariables({
* elementInstanceKey: processInstanceKey,
* variables: variableUpdate
* })
* await zbc.updateJobRetries({
* jobKey,
* retries: 1
* })
* return zbc.resolveIncident({
* incidentKey
* })
* }
* ```
*/
setVariables<Variables = ZB.IProcessVariables>(request: Grpc.SetVariablesRequest<Variables>): Promise<void>;
/**
*
* Create a worker that uses the StreamActivatedJobs RPC to activate jobs.
*
* The worker opens a stream for newly created jobs, then performs an initial
* backfill poll (via `activateJobs`) to pick up any jobs that were already
* queued before the stream was established. A low-frequency sidecar poll
* continues running alongside the stream as a safety net for re-queued jobs.
*
* @example
* ```
* const zbc = new ZB.ZeebeGrpcClient()
*
* const zbStreamWorker = zbc.streamJobs({
* type: 'demo-service',
* worker: 'my-worker-uuid',
* taskHandler: myTaskHandler,
* timeout: 30000 // 30 seconds
* })
*
* ....
* // Close the worker stream when done
* zbStreamWorker.close()
*
* // A job handler must return one of job.complete, job.fail, job.error, or job.forward
* // Note: unhandled exceptions in the job handler cause the library to call job.fail
* async function myTaskHandler(job) {
* zbWorker.log('Task variables', job.variables)
*
* // Task worker business logic goes here
* const updateToBrokerVariables = {
* updatedProperty: 'newValue',
* }
*
* const res = await callExternalSystem(job.variables)
*
* if (res.code === 'SUCCESS') {
* return job.complete({
* ...updateToBrokerVariables,
* ...res.values
* })
* }
* if (res.code === 'BUSINESS_ERROR') {
* return job.error({
* code: res.errorCode,
* message: res.message
* })
* }
* if (res.code === 'ERROR') {
* return job.fail({
* errorMessage: res.message,
* retryBackOff: 2000
* })
* }
* }
* ```
*/
streamJobs<WorkerInputVariables = ZB.IInputVariables, CustomHeaderShape = ZB.ICustomHeaders, WorkerOutputVariables = ZB.IOutputVariables>(req: Pick<Grpc.StreamActivatedJobsRequest, 'type' | 'worker' | 'timeout' | 'tenantIds'> & {
inputVariableDto?: {
new (...args: any[]): Readonly<WorkerInputVariables>;
};
customHeadersDto?: {
new (...args: any[]): Readonly<CustomHeaderShape>;
};
tenantIds?: string[];
fetchVariables?: string[];
/**
* Optional jitter in milliseconds. When provided, the worker will wait
* a random period up to this value before polling and opening the stream.
* Useful for staggering multiple stream workers.
*/
jitter?: number;
/**
* Maximum number of jobs to activate per poll cycle (both the initial
* backfill and the recurring sidecar polls). Defaults to 32.
*/
pollMaxJobsToActivate?: number;
/**
* Interval in milliseconds between sidecar poll cycles. The sidecar poll
* is a low-frequency safety net that picks up jobs the stream may have
* missed (e.g. jobs re-queued after a timeout). Each poll is a command on
* the broker, so keep this value high to minimise load.
*
* Defaults to 30000 (30 seconds). Set to 0 or -1 to disable recurring
* polling (the initial backfill poll still runs).
*/
pollInterval?: number;
taskHandler: ZBWorkerTaskHandler<WorkerInputVariables, CustomHeaderShape, WorkerOutputVariables>;
}): Promise<{
close: () => void;
}>;
/**
*
* Fail a job by throwing a business error (i.e. non-technical) that occurs while processing a job.
* The error is handled in the workflow by an error catch event.
* If there is no error catch event with the specified `errorCode` then an incident will be raised instead.
* This method is useful when building a worker, for example for the decoupled completion pattern.
* @example
* ```
* type JSONObject = {[key: string]: string | number | boolean | JSONObject}
*
* interface errorResult {
* resultType: 'ERROR' as 'ERROR'
* errorCode: string
* errorMessage: string
* }
*
* interface successResult {
* resultType: 'SUCCESS' as 'SUCCESS'
* variableUpdate: JSONObject
* }
*
* type Result = errorResult | successResult
*
* const zbc = new ZeebeGrpcClient()
*
*
* // This could be a listener on a return queue from an external system
* async function handleJob(jobKey: string, result: Result) {
* if (resultType === 'ERROR') {
* const { errorMessage, errorCode } = result
* zbc.throwError({
* jobKey,
* errorCode,
* errorMessage
* })
* } else {
* zbc.completeJob({
* jobKey,
* variables: result.variableUpdate
* })
* }
* }
* ```
*/
throwError(throwErrorRequest: Grpc.ThrowErrorRequest): Promise<void>;
/**
* Return the broker cluster topology.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.topology().then(res => console.res(JSON.stringify(res, null, 2)))
* ```
*/
topology(): Promise<Grpc.TopologyResponse>;
/**
*
* Update the number of retries for a Job. This is useful if a job has zero remaining retries and fails, raising an incident.
* @example
* ```
* type JSONObject = {[key: string]: string | number | boolean | JSONObject}
*
* const zbc = new ZeebeGrpcClient()
*
* async function updateAndResolveIncident({
* incidentKey,
* processInstanceKey,
* jobKey,
* variableUpdate
* } : {
* incidentKey: string
* processInstanceKey: string
* jobKey: string
* variableUpdate: JSONObject
* }) {
* await zbc.setVariables({
* elementInstanceKey: processInstanceKey,
* variables: variableUpdate
* })
* await zbc.updateJobRetries({
* jobKey,
* retries: 1
* })
* return zbc.resolveIncident({
* incidentKey
* })
* }
* ```
*/
updateJobRetries(updateJobRetriesRequest: ZB.UpdateJobRetriesReq): Promise<void>;
/**
Updates the deadline of a job using the timeout (in ms) provided. This can be used
for extending or shortening the job deadline.
Errors:
NOT_FOUND:
- no job exists with the given key
INVALID_STATE:
- no deadline exists for the given job key
*/
updateJobTimeout(updateJobTimeoutRequest: ZB.UpdateJobTimeoutReq): Promise<void>;
private constructGrpcClient;
/**
* If this.retry is set true, the operation will be wrapped in an configurable retry on exceptions
* of gRPC error code 14 - Transient Network Failure.
* See: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
* If this.retry is false, it will be executed with no retry, and the application should handle the exception.
* @param operation A gRPC command operation
*/
private executeOperation;
private _onConnectionError;
/**
* This function takes a gRPC operation that returns a Promise as a function, and invokes it.
* If the operation throws gRPC error 14, this function will continue to try it until it succeeds
* or retries are exhausted.
* @param operation A gRPC command operation that may fail if the broker is not available
*/
private retryOnFailure;
}