-
Notifications
You must be signed in to change notification settings - Fork 6
/
ZeebeGrpcClient.ts
1487 lines (1412 loc) · 43.9 KB
/
ZeebeGrpcClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { readFileSync } from 'fs'
import * as path from 'path'
import chalk from 'chalk'
import d from 'debug'
import promiseRetry from 'promise-retry'
import { Duration, MaybeTimeDuration } from 'typed-duration'
import { v4 as uuid } from 'uuid'
import {
CamundaEnvironmentConfigurator,
CamundaPlatform8Configuration,
DeepPartial,
GetCustomCertificateBuffer,
LosslessDto,
RequireConfiguration,
constructOAuthProvider,
losslessStringify,
} from '../../lib'
import { IOAuthProvider } from '../../oauth'
import {
BpmnParser,
parseVariables,
parseVariablesAndCustomHeadersToJSON,
stringifyVariables,
} from '../lib'
import { ConnectionFactory } from '../lib/ConnectionFactory'
import { ConnectionStatusEvent } from '../lib/ConnectionStatusEvent'
import { CustomSSL } from '../lib/GrpcClient'
import { GrpcError } from '../lib/GrpcError'
import { ZBSimpleLogger } from '../lib/SimpleLogger'
import { StatefulLogInterceptor } from '../lib/StatefulLogInterceptor'
import { TypedEmitter } from '../lib/TypedEmitter'
import { ZBJsonLogger } from '../lib/ZBJsonLogger'
import { ZBStreamWorker } from '../lib/ZBStreamWorker'
import { Resource, getResourceContentAndName } 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,
ZBClientOptions,
ZBCustomLogger,
} from '../lib/interfaces-published-contract'
import { Utils } from '../lib/utils'
import { ZBWorker } from './ZBWorker'
const debug = d('camunda:zeebeclient')
const idColors = [
chalk.yellow,
chalk.green,
chalk.cyan,
chalk.magenta,
chalk.blue,
]
/**
* @description 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.
* @example
* ```
* const zbc = new ZeebeGrpcClient()
* zbc.topology().then(info =>
* console.log(JSON.stringify(info, null, 2))
* )
* ```
*/
export class ZeebeGrpcClient extends TypedEmitter<
typeof ConnectionStatusEvent
> {
public connectionTolerance!: MaybeTimeDuration
public connected?: boolean = undefined
public readied = false
public gatewayAddress: string
public loglevel: Loglevel
public onReady?: () => void
public onConnectionError?: (err: Error) => void
private logger!: StatefulLogInterceptor
private closePromise?: Promise<null>
private closing = false
// A gRPC channel for the ZBClient to execute commands on
private grpc: Promise<ZB.ZBGrpc>
private options: ZBClientOptions
private workerCount = 0
private workers: ZBWorker<any, any, any>[] = // eslint-disable-line @typescript-eslint/no-explicit-any
[]
private retry: boolean
private maxRetries: number
private maxRetryTimeout: MaybeTimeDuration
private oAuthProvider: IOAuthProvider
private useTLS: boolean
private stdout: ZBCustomLogger
private customSSL?: CustomSSL
private tenantId?: string
private config: CamundaPlatform8Configuration
private streamWorker?: ZBStreamWorker
constructor(options?: {
config?: DeepPartial<CamundaPlatform8Configuration>
oAuthProvider?: IOAuthProvider
}) {
super()
const config = CamundaEnvironmentConfigurator.mergeConfigWithEnvironment(
options?.config ?? {}
)
this.config = config
this.options = {} as ZBClientOptions
this.options.longPoll = Duration.seconds.of(
config.zeebeGrpcSettings.ZEEBE_GRPC_WORKER_LONGPOLL_SECONDS
)
this.options.pollInterval = Duration.milliseconds.of(
config.zeebeGrpcSettings.ZEEBE_GRPC_WORKER_POLL_INTERVAL_MS
)
this.retry = config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_RETRY
this.options.retry = this.retry
this.loglevel = config.zeebeGrpcSettings.ZEEBE_CLIENT_LOG_LEVEL as Loglevel
this.options.loglevel = this.loglevel
const logTypeFromEnvironment = () =>
({
JSON: ZBJsonLogger,
SIMPLE: ZBSimpleLogger,
})[config.zeebeGrpcSettings.ZEEBE_CLIENT_LOG_TYPE ?? 'NONE']
this.stdout = logTypeFromEnvironment() ?? ZBSimpleLogger
this.options.tenantId = config.CAMUNDA_TENANT_ID
this.tenantId = this.options.tenantId
this.gatewayAddress = RequireConfiguration(
config.ZEEBE_ADDRESS || config.ZEEBE_GRPC_ADDRESS,
'ZEEBE_GRPC_ADDRESS'
)
debug('Gateway address: ', this.gatewayAddress)
this.connectionTolerance = Duration.milliseconds.of(
config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_CONNECTION_TOLERANCE_MS
)
this.onConnectionError = this.options.onConnectionError
this.onReady = this.options.onReady
this.oAuthProvider =
options?.oAuthProvider ?? constructOAuthProvider(config)
this.maxRetries = config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_MAX_RETRIES
this.maxRetryTimeout = Duration.seconds.of(
config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_MAX_RETRY_TIMEOUT_SECONDS
)
this.useTLS = config.CAMUNDA_SECURE_CONNECTION
const certChainPath = config.CAMUNDA_CUSTOM_CERT_CHAIN_PATH
const privateKeyPath = config.CAMUNDA_CUSTOM_PRIVATE_KEY_PATH
this.grpc = GetCustomCertificateBuffer(config).then((rootCerts) => {
const customSSL = {
certChain: certChainPath ? readFileSync(certChainPath) : undefined,
privateKey: privateKeyPath ? readFileSync(privateKeyPath) : undefined,
rootCerts: rootCerts ? Buffer.from(rootCerts) : undefined,
}
this.customSSL = customSSL
this.options.customSSL = customSSL
const { grpcClient, log } = this.constructGrpcClient({
grpcConfig: {
namespace: this.options.logNamespace || 'ZBClient',
},
logConfig: {
_tag: 'ZBCLIENT',
loglevel: this.loglevel,
longPoll: Duration.milliseconds.from(this.options.longPoll),
namespace: this.options.logNamespace || 'ZBClient',
pollInterval: Duration.milliseconds.from(this.options.pollInterval),
stdout: this.stdout,
},
})
grpcClient.on(ConnectionStatusEvent.connectionError, (err: Error) => {
debug('grpcClient emitted error event to ZeebeGrpcClient, err: ', err)
this.readied = false
if (this.connected !== false) {
this.connected = false
this.onConnectionError?.(err)
this.emit(ConnectionStatusEvent.connectionError)
}
})
grpcClient.on(ConnectionStatusEvent.ready, () => {
debug('grpcClient emitted ready event to ZeebeGrpcClient')
this.connected = true
if (!this.readied) {
this.onReady?.()
this.emit(ConnectionStatusEvent.ready)
}
this.readied = true
})
this.logger = log
return grpcClient
})
// Send command to broker to eagerly fail / prove connection.
// This is useful for, for example: the Node-Red client, which wants to
// display the connection status.
const eagerConnection =
config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_EAGER_CONNECT
if (eagerConnection ?? false) {
this.topology()
.then((res) => {
this.logger.logDirect(chalk.blueBright('Zeebe cluster topology:'))
this.logger.logDirect(res.brokers)
// debug('Emitting ready event')
// this.emit(ConnectionStatusEvent.ready)
})
.catch((e) => {
// Swallow exception to avoid throwing if retries are off
if (e.thisWillNeverHappenYo) {
this.emit(ConnectionStatusEvent.unknown)
}
})
}
}
/**
* @description 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: {}
* ))
* )
* })
* ```
*/
public activateJobs<
Variables = ZB.IInputVariables,
CustomHeaders = ZB.ICustomHeaders,
>(
request: Grpc.ActivateJobsRequest & {
inputVariableDto?: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): Readonly<Variables>
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
customHeadersDto?: { new (...args: any[]): Readonly<CustomHeaders> }
}
): Promise<ZB.Job<Variables, CustomHeaders>[]> {
const { inputVariableDto, customHeadersDto, ...req } = request
const inputVariableDtoToUse =
inputVariableDto ??
(LosslessDto as {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (obj: any): Variables
})
const customHeadersDtoToUse =
customHeadersDto ??
(LosslessDto as {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (obj: any): CustomHeaders
})
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
const stream = await (await this.grpc).activateJobsStream(req)
stream.on('data', (res: Grpc.ActivateJobsResponse) => {
const jobs = res.jobs.map((job) =>
parseVariablesAndCustomHeadersToJSON<Variables, CustomHeaders>(
job,
inputVariableDtoToUse,
customHeadersDtoToUse
)
)
resolve(jobs)
})
} catch (e: unknown) {
reject(e)
}
})
}
/**
*
* @description Broadcast a Signal
* @example
* ```
* const zbc = new ZeebeGrpcClient()
*
* zbc.broadcastSignal({
* signalName: 'my-signal',
* variables: { reasonCode: 3 }
* })
*/
public async broadcastSignal(
req: ZB.BroadcastSignalReq
): Promise<ZB.BroadcastSignalRes> {
const request = {
signalName: req.signalName,
variables: JSON.stringify(req.variables ?? {}),
tenantId: req.tenantId ?? this.tenantId,
}
return this.executeOperation('broadcastSignal', async () =>
(await this.grpc).broadcastSignalSync(request)
)
}
/**
*
* @description 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}`)
* )
* ```
*/
public async cancelProcessInstance(
processInstanceKey: string | number
): Promise<void> {
Utils.validateNumber(processInstanceKey, 'processInstanceKey')
return this.executeOperation('cancelProcessInstance', async () =>
(await this.grpc).cancelProcessInstanceSync({
processInstanceKey,
})
)
}
/**
*
* @description 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
* })
* }
* }
* ```
*/
public createWorker<
WorkerInputVariables = ZB.IInputVariables,
CustomHeaderShape = ZB.ICustomHeaders,
WorkerOutputVariables = ZB.IOutputVariables,
>(
config: ZB.ZBWorkerConfig<
WorkerInputVariables,
CustomHeaderShape,
WorkerOutputVariables
>
): ZBWorker<WorkerInputVariables, CustomHeaderShape, WorkerOutputVariables> {
debug(`Creating worker for task type ${config.taskType}`)
if (this.closing) {
throw new Error('Client is closing. No worker creation allowed!')
}
const idColor = idColors[this.workerCount++ % idColors.length]
// Merge parent client options with worker override
const options = {
...this.options,
onConnectionError: undefined, // Do not inherit client handler
onReady: undefined, // Do not inherit client handler
...config,
}
// Give worker its own gRPC connection
const { grpcClient: workerGRPCClient, log } = this.constructGrpcClient({
grpcConfig: {
namespace: 'ZBWorker',
tasktype: config.taskType,
},
logConfig: {
_tag: 'ZBWORKER',
colorise: true,
id: config.id!,
loglevel: options.loglevel,
namespace: ['ZBWorker', options.logNamespace].join(' ').trim(),
pollInterval: options.longPoll,
stdout: options.stdout,
taskType: config.taskType,
},
})
const worker = new ZBWorker<
WorkerInputVariables,
CustomHeaderShape,
WorkerOutputVariables
>({
grpcClient: workerGRPCClient,
id: config.id || null,
idColor,
log,
options: { ...this.options, ...options },
taskHandler: config.taskHandler,
taskType: config.taskType,
zbClient: this,
tenantIds: config.tenantIds
? config.tenantIds
: this.tenantId
? [this.tenantId]
: undefined,
})
this.workers.push(worker)
return worker
}
/**
* @description 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
* )
* ```
*/
public async close(timeout?: number): Promise<null> {
debug('Closing Zeebe Client')
this.closePromise =
this.closePromise ||
new Promise((resolve) => {
// Prevent the creation of more workers
this.closing = true
Promise.all(this.workers.map((w) => w.close(timeout)))
.then(async () => (await this.grpc).close(timeout))
.then(async () => {
if (this.streamWorker) {
await this.streamWorker.close()
}
})
.then(async () => {
this.emit(ConnectionStatusEvent.close)
;(await this.grpc).removeAllListeners()
this.removeAllListeners()
resolve(null)
})
})
return this.closePromise
}
/**
*
* @description 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: {}
* ))
* )
* })
* ```
*/
public completeJob(
completeJobRequest: Grpc.CompleteJobRequest
): Promise<void> {
const withStringifiedVariables = stringifyVariables(completeJobRequest)
this.logger.logDebug(withStringifiedVariables)
return this.executeOperation('completeJob', async () =>
(await this.grpc).completeJobSync(withStringifiedVariables).catch((e) => {
if (e.code === GrpcError.NOT_FOUND) {
e.details +=
'. The process may have been cancelled, the job cancelled by an interrupting event, or the job already completed.' +
' For more detail, see: https://forum.zeebe.io/t/command-rejected-with-code-complete/908/17'
}
throw e
})
)
}
// tslint:disable: no-object-literal-type-assertion
/**
*
* @description 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))
* ```
*/
public createProcessInstance<
Variables extends ZB.JSONDoc = ZB.IProcessVariables,
>(
config: ZB.CreateProcessInstanceReq<Variables>
): Promise<Grpc.CreateProcessInstanceResponse> {
const request: ZB.CreateProcessInstanceReq<Variables> = {
bpmnProcessId: config.bpmnProcessId,
variables: config.variables,
version: config.version || -1,
startInstructions: config.startInstructions || [],
}
const createProcessInstanceRequest: Grpc.CreateProcessInstanceRequest =
stringifyVariables({
...request,
startInstructions: request.startInstructions!,
tenantId: config.tenantId ?? this.tenantId,
})
return this.executeOperation('createProcessInstance', async () =>
(await this.grpc).createProcessInstanceSync(createProcessInstanceRequest)
)
}
/**
*
* @description 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)
* ```
*/
public createProcessInstanceWithResult<
Variables extends ZB.JSONDoc = ZB.IProcessVariables,
Result = ZB.IOutputVariables,
>(
config: ZB.CreateProcessInstanceWithResultReq<Variables>
): Promise<Grpc.CreateProcessInstanceWithResultResponse<Result>> {
const request = {
bpmnProcessId: config.bpmnProcessId,
fetchVariables: config.fetchVariables,
requestTimeout: config.requestTimeout || 0,
variables: config.variables,
version: config.version || -1,
tenantId: config.tenantId ?? this.tenantId,
}
const createProcessInstanceRequest: Grpc.CreateProcessInstanceBaseRequest =
stringifyVariables({
bpmnProcessId: request.bpmnProcessId,
variables: request.variables,
version: request.version,
tenantId: request.tenantId ?? this.tenantId,
})
return this.executeOperation('createProcessInstanceWithResult', async () =>
(await this.grpc).createProcessInstanceWithResultSync({
fetchVariables: request.fetchVariables,
request: createProcessInstanceRequest,
requestTimeout: request.requestTimeout,
})
).then((res) =>
parseVariables<
Grpc.CreateProcessInstanceWithResultResponseOnWire,
Result
>(res)
)
}
/**
* 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,
}: {
resourceKey: string
}): Promise<Record<string, never>> {
return this.executeOperation('deleteResourceSync', async () =>
(await this.grpc).deleteResourceSync({ resourceKey })
)
}
/**
*
* @description 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')})
* ```
*/
public async deployResource(
resource:
| { processFilename: string; tenantId?: string }
| { name: string; process: Buffer; tenantId?: string }
): Promise<Grpc.DeployResourceResponse<Grpc.ProcessDeployment>>
public async deployResource(
resource:
| { decisionFilename: string; tenantId?: string }
| { name: string; decision: Buffer; tenantId?: string }
): Promise<Grpc.DeployResourceResponse<Grpc.DecisionDeployment>>
public async deployResource(
resource:
| { formFilename: string; tenantId?: string }
| { name: string; form: Buffer; tenantId?: string }
): Promise<Grpc.DeployResourceResponse<Grpc.FormDeployment>>
async deployResource(
resource: Resource
): Promise<
Grpc.DeployResourceResponse<
| Grpc.ProcessDeployment
| Grpc.DecisionDeployment
| Grpc.DecisionRequirementsDeployment
| Grpc.FormDeployment
>
> {
const { content, name } = getResourceContentAndName(resource)
return this.executeOperation('deployResource', async () =>
(await this.grpc).deployResourceSync({
resources: [
{
name,
content,
},
],
tenantId: resource.tenantId ?? this.tenantId,
})
)
}
/**
*
* @description 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',
* },
* ])
* ```
*/
public async deployResources(resources: Resource[], tenantId?: string) {
const resourcesToDeploy = resources.map((r) => {
const { content, name } = getResourceContentAndName(r)
return { name, content }
})
return this.executeOperation('deployResources', async () =>
(await this.grpc).deployResourceSync({
resources: resourcesToDeploy,
tenantId: tenantId ?? this.tenantId,
})
)
}
/**
*
* @description 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)))
*/
public evaluateDecision(
evaluateDecisionRequest: Grpc.EvaluateDecisionRequest
): Promise<Grpc.EvaluateDecisionResponse> {
// the gRPC API call needs a JSON string, but we accept a JSON object, so we transform it here
const variables = losslessStringify(
evaluateDecisionRequest.variables
) as unknown as ZB.JSONDoc
return this.executeOperation('evaluateDecision', async () =>
(await this.grpc).evaluateDecisionSync({
...evaluateDecisionRequest,
variables,
tenantId: evaluateDecisionRequest.tenantId ?? this.tenantId,
})
)
}
/**
*
* @description 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
* })
* ```
*/
public failJob(failJobRequest: Grpc.FailJobRequest): Promise<void> {
return this.executeOperation('failJob', async () =>
(await this.grpc).failJobSync(failJobRequest)
)
}
/**
* @description 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))
*
* ```
*/
public getServiceTypesFromBpmn(files: string | string[]) {
const fileArray = typeof files === 'string' ? [files] : files
return BpmnParser.getTaskTypes(BpmnParser.parseBpmn(fileArray))
}
/**
*
* @description 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}
* }]
* }]
* })
* )
* ```
*/
public modifyProcessInstance(
modifyProcessInstanceRequest: Grpc.ModifyProcessInstanceRequest
): Promise<Grpc.ModifyProcessInstanceResponse> {
return this.executeOperation('modifyProcessInstance', async () => {
// We accept JSONDoc for the variableInstructions, but the actual gRPC call needs stringified JSON, so transform it with a mutation
const req = Utils.deepClone(modifyProcessInstanceRequest)
req?.activateInstructions?.forEach((a) =>
a.variableInstructions.forEach(
(v) => (v.variables = losslessStringify(v.variables))
)
)
return (await this.grpc).modifyProcessInstanceSync({
...req,
})
})
}
/**
*
* @since 8.5.0
*/
public migrateProcessInstance(
migrateProcessInstanceRequest: Grpc.MigrateProcessInstanceRequest
): Promise<Grpc.MigrateProcessInstanceResponse> {
return this.executeOperation('migrateProcessInstance', async () =>
(await this.grpc).migrateProcessInstanceSync(
migrateProcessInstanceRequest
)
)
}
/**
* @description 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'
* }
* })
* ```
*/
public publishMessage<
ProcessVariables extends {
[key: string]: ZB.JSON
} = ZB.IProcessVariables,
>(
publishMessageRequest: Grpc.PublishMessageRequest<ProcessVariables>
): Promise<Grpc.PublishMessageResponse> {
return this.executeOperation('publishMessage', async () =>
(await this.grpc).publishMessageSync(
stringifyVariables({
...publishMessageRequest,
variables: publishMessageRequest.variables,
tenantId: publishMessageRequest.tenantId ?? this.tenantId,
})
)
)
}
/**
* @description 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'
* }
* })
* ```
*/
public publishStartMessage<
ProcessVariables extends ZB.IInputVariables = ZB.IProcessVariables,
>(
publishStartMessageRequest: Grpc.PublishStartMessageRequest<ProcessVariables>
): Promise<Grpc.PublishMessageResponse> {
/**
* 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
*/
const publishMessageRequest: Grpc.PublishMessageRequest = {
correlationKey: uuid(),
...publishStartMessageRequest,
tenantId: publishStartMessageRequest.tenantId ?? this.tenantId,
}
return this.executeOperation('publishStartMessage', async () =>
(await this.grpc).publishMessageSync(
stringifyVariables({
...publishMessageRequest,
variables: publishMessageRequest.variables || {},
})
)
)
}
/**
*
* @description 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
* }) {