-
Notifications
You must be signed in to change notification settings - Fork 47
/
durableorchestrationclient.ts
838 lines (745 loc) · 34 KB
/
durableorchestrationclient.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
// tslint:disable:member-access
import { HttpRequest } from "@azure/functions";
import axios, { AxiosInstance, AxiosResponse } from "axios";
import cloneDeep = require("lodash/cloneDeep");
import process = require("process");
import url = require("url");
import { isURL } from "validator";
import { Constants, DurableOrchestrationStatus, EntityId, EntityStateResponse,
GetStatusOptions, HttpCreationPayload, HttpManagementPayload,
IHttpRequest, IHttpResponse, IOrchestrationFunctionContext, OrchestrationClientInputData,
OrchestrationRuntimeStatus, PurgeHistoryResult, Utils,
} from "./classes";
import { WebhookUtils } from "./webhookutils";
const URL = url.URL;
/**
* Returns an OrchestrationClient instance.
* @param context The context object of the Azure function whose body
* calls this method.
* @example Get an orchestration client instance
* ```javascript
* const df = require("durable-functions");
*
* module.exports = async function (context, req) {
* const client = df.getClient(context);
* const instanceId = await client.startNew(req.params.functionName, undefined, req.body);
*
* return client.createCheckStatusResponse(req, instanceId);
* };
* ```
*/
export function getClient(context: unknown): DurableOrchestrationClient {
let clientData = getClientData(context as IOrchestrationFunctionContext);
if (!process.env.WEBSITE_HOSTNAME || process.env.WEBSITE_HOSTNAME.includes("0.0.0.0")) {
clientData = correctClientData(clientData);
}
return new DurableOrchestrationClient(clientData);
}
function getClientData(context: IOrchestrationFunctionContext): OrchestrationClientInputData {
if (context.bindings) {
const matchingInstances = Object.keys(context.bindings)
.map((key) => context.bindings[key])
.filter((val) => OrchestrationClientInputData.isOrchestrationClientInputData(val));
if (matchingInstances && matchingInstances.length > 0) {
return matchingInstances[0] as OrchestrationClientInputData;
}
}
throw new Error("An orchestration client function must have an orchestrationClient input binding. Check your function.json definition.");
}
function correctClientData(clientData: OrchestrationClientInputData): OrchestrationClientInputData {
const returnValue = cloneDeep(clientData);
returnValue.creationUrls = correctUrls(clientData.creationUrls) as HttpCreationPayload;
returnValue.managementUrls = correctUrls(clientData.managementUrls) as HttpManagementPayload;
return returnValue;
}
function correctUrls(obj: { [key: string]: string }): { [key: string]: string } {
const returnValue = cloneDeep(obj);
const keys = Object.getOwnPropertyNames(obj);
keys.forEach((key) => {
const value = obj[key];
if (isURL(value, {
protocols: ["http", "https"],
require_tld: false,
require_protocol: true,
})) {
const valueAsUrl = new url.URL(value);
returnValue[key] = value.replace(valueAsUrl.origin, Constants.DefaultLocalOrigin);
}
});
return returnValue;
}
/**
* Client for starting, querying, terminating and raising events to
* orchestration instances.
*/
export class DurableOrchestrationClient {
/**
* The name of the task hub configured on this orchestration client
* instance.
*/
public readonly taskHubName: string;
/** @hidden */
public readonly uniqueWebhookOrigins: string[];
private readonly axiosInstance: AxiosInstance;
private readonly eventNamePlaceholder = "{eventName}";
private readonly functionNamePlaceholder = "{functionName}";
private readonly instanceIdPlaceholder = "[/{instanceId}]";
private readonly reasonPlaceholder = "{text}";
private readonly createdTimeFromQueryKey = "createdTimeFrom";
private readonly createdTimeToQueryKey = "createdTimeTo";
private readonly runtimeStatusQueryKey = "runtimeStatus";
private readonly showHistoryQueryKey = "showHistory";
private readonly showHistoryOutputQueryKey = "showHistoryOutput";
private readonly showInputQueryKey = "showInput";
private urlValidationOptions: ValidatorJS.IsURLOptions = {
protocols: ["http", "https"],
require_tld: false,
require_protocol: true,
require_valid_protocol: true,
};
/**
* @param clientData The object representing the orchestrationClient input
* binding of the Azure function that will use this client.
*/
constructor(
private readonly clientData: OrchestrationClientInputData,
) {
if (!clientData) {
throw new TypeError(`clientData: Expected OrchestrationClientInputData but got ${typeof clientData}`);
}
this.axiosInstance = axios.create({
validateStatus: (status: number) => status < 600,
headers: {
post: {
"Content-Type": "application/json",
},
},
maxContentLength: Infinity,
});
this.taskHubName = this.clientData.taskHubName;
this.uniqueWebhookOrigins = this.extractUniqueWebhookOrigins(this.clientData);
}
/**
* Creates an HTTP response that is useful for checking the status of the
* specified instance.
* @param request The HTTP request that triggered the current orchestration
* instance.
* @param instanceId The ID of the orchestration instance to check.
* @returns An HTTP 202 response with a Location header and a payload
* containing instance management URLs.
*/
public createCheckStatusResponse(request: IHttpRequest | HttpRequest | undefined, instanceId: string): IHttpResponse {
const httpManagementPayload = this.getClientResponseLinks(request, instanceId);
return {
status: 202,
body: httpManagementPayload,
headers: {
"Content-Type": "application/json",
"Location": httpManagementPayload.statusQueryGetUri,
"Retry-After": 10,
},
};
}
/**
* Creates an [[HttpManagementPayload]] object that contains instance
* management HTTP endpoints.
* @param instanceId The ID of the orchestration instance to check.
*/
public createHttpManagementPayload(instanceId: string): HttpManagementPayload {
return this.getClientResponseLinks(undefined, instanceId);
}
/**
* Gets the status of the specified orchestration instance.
* @param instanceId The ID of the orchestration instance to query.
* @param showHistory Boolean marker for including execution history in the
* response.
* @param showHistoryOutput Boolean marker for including input and output
* in the execution history response.
*/
public async getStatus(
instanceId: string,
showHistory?: boolean,
showHistoryOutput?: boolean,
showInput?: boolean,
): Promise<DurableOrchestrationStatus> {
const options: GetStatusOptions = {
instanceId,
showHistory,
showHistoryOutput,
showInput,
};
const response = await this.getStatusInternal(options);
switch (response.status) {
case 200: // instance completed
case 202: // instance in progress
case 400: // instance failed or terminated
case 404: // instance not found or pending
case 500: // instance failed with unhandled exception
return response.data as DurableOrchestrationStatus;
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Gets the status of all orchestration instances.
*/
public async getStatusAll(): Promise<DurableOrchestrationStatus[]> {
const response = await this.getStatusInternal({});
switch (response.status) {
case 200:
return response.data as DurableOrchestrationStatus[];
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Gets the status of all orchestration instances that match the specified
* conditions.
* @param createdTimeFrom Return orchestration instances which were created
* after this Date.
* @param createdTimeTo Return orchestration instances which were created
* before this DateTime.
* @param runtimeStatus Return orchestration instances which match any of
* the runtimeStatus values in this array.
*/
public async getStatusBy(
createdTimeFrom: Date | undefined,
createdTimeTo: Date | undefined,
runtimeStatus: OrchestrationRuntimeStatus[],
): Promise<DurableOrchestrationStatus[]> {
const options: GetStatusOptions = {
createdTimeFrom,
createdTimeTo,
runtimeStatus,
};
const response = await this.getStatusInternal(options);
switch (response.status) {
case 200:
return response.data as DurableOrchestrationStatus[];
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Purge the history for a specific orchestration instance.
* @param instanceId The ID of the orchestration instance to purge.
*/
public async purgeInstanceHistory(instanceId: string): Promise<PurgeHistoryResult> {
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
requestUrl = new URL(`instances/${instanceId}`, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
const template = this.clientData.managementUrls.purgeHistoryDeleteUri;
const idPlaceholder = this.clientData.managementUrls.id;
requestUrl = template.replace(idPlaceholder, instanceId);
}
const response = await this.axiosInstance.delete(requestUrl);
switch (response.status) {
case 200: // instance found
return response.data as PurgeHistoryResult;
case 404: // instance not found
return new PurgeHistoryResult(0);
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Purge the orchestration history for instances that match the conditions.
* @param createdTimeFrom Start creation time for querying instances for
* purging.
* @param createdTimeTo End creation time for querying instances for
* purging.
* @param runtimeStatus List of runtime statuses for querying instances for
* purging. Only Completed, Terminated or Failed will be processed.
*/
public async purgeInstanceHistoryBy(
createdTimeFrom: Date,
createdTimeTo?: Date,
runtimeStatus?: OrchestrationRuntimeStatus[],
): Promise<PurgeHistoryResult> {
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = new URL("instances/", this.clientData.rpcBaseUrl).href;
const query: string[] = [];
if (createdTimeFrom) { query.push(`createdTimeFrom=${createdTimeFrom.toISOString()}`); }
if (createdTimeTo) { query.push(`createdTimeTo=${createdTimeTo.toISOString()}`); }
if (runtimeStatus && runtimeStatus.length > 0) {
const statusList: string = runtimeStatus.map((value) => value.toString()).join(",");
query.push(`runtimeStatus=${statusList}`);
}
if (query.length > 0) {
path += "?" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
const idPlaceholder = this.clientData.managementUrls.id;
requestUrl = this.clientData.managementUrls.statusQueryGetUri.replace(idPlaceholder, "");
if (!(createdTimeFrom instanceof Date)) {
throw new Error("createdTimeFrom must be a valid Date");
}
if (createdTimeFrom) {
requestUrl += `&${this.createdTimeFromQueryKey}=${createdTimeFrom.toISOString()}`;
}
if (createdTimeTo) {
requestUrl += `&${this.createdTimeToQueryKey}=${createdTimeTo.toISOString()}`;
}
if (runtimeStatus && runtimeStatus.length > 0) {
const statusesString = runtimeStatus
.map((value) => value.toString())
.reduce((acc, curr, i, arr) => {
return acc + (i > 0 ? "," : "") + curr;
});
requestUrl += `&${this.runtimeStatusQueryKey}=${statusesString}`;
}
}
const response = await this.axiosInstance.delete(requestUrl);
switch (response.status) {
case 200: // instance found
return response.data as PurgeHistoryResult;
case 404: // instance not found
return new PurgeHistoryResult(0);
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Sends an event notification message to a waiting orchestration instance.
* @param instanceId The ID of the orchestration instance that will handle
* the event.
* @param eventName The name of the event.
* @param eventData The JSON-serializable data associated with the event.
* @param taskHubName The TaskHubName of the orchestration that will handle
* the event.
* @param connectionName The name of the connection string associated with
* `taskHubName.`
* @returns A promise that resolves when the event notification message has
* been enqueued.
*
* In order to handle the event, the target orchestration instance must be
* waiting for an event named `eventName` using
* [[waitForExternalEvent]].
*
* If the specified instance is not found or not running, this operation
* will have no effect.
*/
public async raiseEvent(
instanceId: string,
eventName: string,
eventData: unknown,
taskHubName?: string,
connectionName?: string,
): Promise<void> {
if (!eventName) {
throw new Error("eventName must be a valid string.");
}
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = `instances/${instanceId}/raiseEvent/${eventName}`;
const query: string[] = [];
if (taskHubName) { query.push(`taskHub=${taskHubName}`); }
if (connectionName) { query.push(`connection=${connectionName}`); }
if (query.length > 0) {
path += "?" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
const idPlaceholder = this.clientData.managementUrls.id;
requestUrl = this.clientData.managementUrls.sendEventPostUri
.replace(idPlaceholder, instanceId)
.replace(this.eventNamePlaceholder, eventName);
if (taskHubName) {
requestUrl = requestUrl.replace(this.clientData.taskHubName, taskHubName);
}
if (connectionName) {
requestUrl = requestUrl.replace(/(connection=)([\w]+)/gi, "$1" + connectionName);
}
}
const response = await this.axiosInstance.post(requestUrl, JSON.stringify(eventData));
switch (response.status) {
case 202: // event accepted
case 410: // instance completed or failed
return;
case 404:
return Promise.reject(new Error(`No instance with ID '${instanceId}' found.`));
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Tries to read the current state of an entity. Returnes undefined if the
* entity does not exist, or if the JSON-serialized state of the entity is
* larger than 16KB.
* @param T The JSON-serializable type of the entity.
* @param entityId The target entity.
* @param taskHubName The TaskHubName of the target entity.
* @param connectionName The name of the connection string associated with
* [taskHubName].
* @returns A response containing the current state of the entity.
*/
public async readEntityState<T>(entityId: EntityId, taskHubName?: string, connectionName?: string): Promise<EntityStateResponse<T>> {
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = `entities/${entityId.name}/${entityId.key}`;
const query: string[] = [];
if (taskHubName) { query.push(`taskHub=${taskHubName}`); }
if (connectionName) { query.push(`connection=${connectionName}`); }
if (query.length > 0) {
path += "?" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
if (!(this.clientData.baseUrl && this.clientData.requiredQueryStringParameters)) {
throw new Error("Cannot use the readEntityState API with this version of the Durable Task Extension.");
}
requestUrl = WebhookUtils.getReadEntityUrl(
this.clientData.baseUrl,
this.clientData.requiredQueryStringParameters,
entityId.name,
entityId.key,
taskHubName,
connectionName);
}
const response = await this.axiosInstance.get(requestUrl);
switch (response.status) {
case 200: // entity exists
return new EntityStateResponse(true, response.data as T);
case 404: // entity does not exist
return new EntityStateResponse(false);
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Rewinds the specified failed orchestration instance with a reason.
* @param instanceId The ID of the orchestration instance to rewind.
* @param reason The reason for rewinding the orchestration instance.
* @returns A promise that resolves when the rewind message is enqueued.
*
* This feature is currently in preview.
*/
public async rewind(instanceId: string, reason: string, taskHubName?: string, connectionName?: string): Promise<void> {
const idPlaceholder = this.clientData.managementUrls.id;
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = `instances/${instanceId}/rewind?reason=${reason}`;
const query: string[] = [];
if (taskHubName) { query.push(`taskHub=${taskHubName}`); }
if (connectionName) { query.push(`connection=${connectionName}`); }
if (query.length > 0) {
path += "&" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
requestUrl = this.clientData.managementUrls.rewindPostUri
.replace(idPlaceholder, instanceId)
.replace(this.reasonPlaceholder, reason);
}
const response = await this.axiosInstance.post(requestUrl);
switch (response.status) {
case 202:
return;
case 404:
return Promise.reject(new Error(`No instance with ID '${instanceId}' found.`));
case 410:
return Promise.reject(new Error("The rewind operation is only supported on failed orchestration instances."));
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Signals an entity to perform an operation.
* @param entityId The target entity.
* @param operationName The name of the operation.
* @param operationContent The content for the operation.
* @param taskHubName The TaskHubName of the target entity.
* @param connectionName The name of the connection string associated with [taskHubName].
*/
public async signalEntity(
entityId: EntityId,
operationName?: string,
operationContent?: unknown,
taskHubName?: string,
connectionName?: string,
): Promise<void> {
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = `entities/${entityId.name}/${entityId.key}`;
const query: string[] = [];
if (operationName) { query.push(`op=${operationName}`); }
if (taskHubName) { query.push(`taskHub=${taskHubName}`); }
if (connectionName) { query.push(`connection=${connectionName}`); }
if (query.length > 0) {
path += "?" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
if (!(this.clientData.baseUrl && this.clientData.requiredQueryStringParameters)) {
throw new Error("Cannot use the signalEntity API with this version of the Durable Task Extension.");
}
requestUrl = WebhookUtils.getSignalEntityUrl(
this.clientData.baseUrl,
this.clientData.requiredQueryStringParameters,
entityId.name,
entityId.key,
operationName,
taskHubName,
connectionName);
}
const response = await this.axiosInstance.post(requestUrl, JSON.stringify(operationContent));
switch (response.status) {
case 202: // signal accepted
return;
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Starts a new instance of the specified orchestrator function.
*
* If an orchestration instance with the specified ID already exists, the
* existing instance will be silently replaced by this new instance.
* @param orchestratorFunctionName The name of the orchestrator function to
* start.
* @param instanceId The ID to use for the new orchestration instance. If
* no instanceId is specified, the Durable Functions extension will
* generate a random GUID (recommended).
* @param input JSON-serializable input value for the orchestrator
* function.
* @returns The ID of the new orchestration instance.
*/
public async startNew(orchestratorFunctionName: string, instanceId?: string, input?: unknown): Promise<string> {
if (!orchestratorFunctionName) {
throw new Error("orchestratorFunctionName must be a valid string.");
}
// TODO: Add support for specifying a task hub and a connection name
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
requestUrl = new URL(
`orchestrators/${orchestratorFunctionName}${(instanceId ? `/${instanceId}` : "")}`,
this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
requestUrl = this.clientData.creationUrls.createNewInstancePostUri;
requestUrl = requestUrl
.replace(this.functionNamePlaceholder, orchestratorFunctionName)
.replace(this.instanceIdPlaceholder, (instanceId ? `/${instanceId}` : ""));
}
const response = await this.axiosInstance.post(requestUrl, input !== undefined ? JSON.stringify(input) : "");
if (response.data && response.status <= 202) {
return (response.data as HttpManagementPayload).id;
} else {
return Promise.reject(this.createGenericError(response));
}
}
/**
* Terminates a running orchestration instance.
* @param instanceId The ID of the orchestration instance to terminate.
* @param reason The reason for terminating the orchestration instance.
* @returns A promise that resolves when the terminate message is enqueued.
*
* Terminating an orchestration instance has no effect on any in-flight
* activity function executions or sub-orchestrations that were started
* by the current orchestration instance.
*/
public async terminate(instanceId: string, reason: string): Promise<void> {
const idPlaceholder = this.clientData.managementUrls.id;
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
requestUrl = new URL(
`instances/${instanceId}/terminate?reason=${reason}`,
this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend path
requestUrl = this.clientData.managementUrls.terminatePostUri
.replace(idPlaceholder, instanceId)
.replace(this.reasonPlaceholder, reason);
}
const response = await this.axiosInstance.post(requestUrl);
switch (response.status) {
case 202: // terminate accepted
case 410: // instance completed or failed
return;
case 404:
return Promise.reject(new Error(`No instance with ID '${instanceId}' found.`));
default:
return Promise.reject(this.createGenericError(response));
}
}
/**
* Creates an HTTP response which either contains a payload of management
* URLs for a non-completed instance or contains the payload containing
* the output of the completed orchestration.
*
* If the orchestration does not complete within the specified timeout,
* then the HTTP response will be identical to that of
* [[createCheckStatusResponse]].
*
* @param request The HTTP request that triggered the current function.
* @param instanceId The unique ID of the instance to check.
* @param timeoutInMilliseconds Total allowed timeout for output from the
* durable function. The default value is 10 seconds.
* @param retryIntervalInMilliseconds The timeout between checks for output
* from the durable function. The default value is 1 second.
*/
public async waitForCompletionOrCreateCheckStatusResponse(
request: HttpRequest,
instanceId: string,
timeoutInMilliseconds: number = 10000,
retryIntervalInMilliseconds: number = 1000,
): Promise<IHttpResponse> {
if (retryIntervalInMilliseconds > timeoutInMilliseconds) {
throw new Error(`Total timeout ${timeoutInMilliseconds} (ms) should be bigger than retry timeout ${retryIntervalInMilliseconds} (ms)`);
}
const hrStart = process.hrtime();
while (true) {
const status = await this.getStatus(instanceId);
if (status) {
switch (status.runtimeStatus) {
case OrchestrationRuntimeStatus.Completed:
return this.createHttpResponse(200, status.output);
case OrchestrationRuntimeStatus.Canceled:
case OrchestrationRuntimeStatus.Terminated:
return this.createHttpResponse(200, status);
case OrchestrationRuntimeStatus.Failed:
return this.createHttpResponse(500, status);
}
}
const hrElapsed = process.hrtime(hrStart);
const hrElapsedMilliseconds = Utils.getHrMilliseconds(hrElapsed);
if (hrElapsedMilliseconds < timeoutInMilliseconds) {
const remainingTime = timeoutInMilliseconds - hrElapsedMilliseconds;
await Utils.sleep(remainingTime > retryIntervalInMilliseconds
? retryIntervalInMilliseconds
: remainingTime);
} else {
return this.createCheckStatusResponse(request, instanceId);
}
}
}
private createHttpResponse(statusCode: number, body: unknown): IHttpResponse {
const bodyAsJson = JSON.stringify(body);
return {
status: statusCode,
body: bodyAsJson,
headers: {
"Content-Type": "application/json",
},
};
}
private getClientResponseLinks(request: IHttpRequest | HttpRequest | undefined, instanceId: string): HttpManagementPayload {
const payload = { ...this.clientData.managementUrls };
(Object.keys(payload) as Array<(keyof HttpManagementPayload)>).forEach((key) => {
if (this.hasValidRequestUrl(request) && isURL(payload[key], this.urlValidationOptions)) {
const requestUrl = new url.URL((request as HttpRequest).url || (request as IHttpRequest).http.url);
const dataUrl = new url.URL(payload[key]);
payload[key] = payload[key].replace(dataUrl.origin, requestUrl.origin);
}
payload[key] = payload[key].replace(this.clientData.managementUrls.id, instanceId);
});
return payload;
}
private hasValidRequestUrl(request: IHttpRequest | HttpRequest | undefined): boolean {
const isHttpRequest = request !== undefined && (request as HttpRequest).url !== undefined;
const isIHttpRequest = request !== undefined && (request as IHttpRequest).http !== undefined;
return isHttpRequest || isIHttpRequest && (request as IHttpRequest).http.url !== undefined;
}
private extractUniqueWebhookOrigins(clientData: OrchestrationClientInputData): string[] {
const origins = this.extractWebhookOrigins(clientData.creationUrls)
.concat(this.extractWebhookOrigins(clientData.managementUrls));
const uniqueOrigins = origins.reduce<string[]>((acc, curr) => {
if (acc.indexOf(curr) === -1) {
acc.push(curr);
}
return acc;
}, []);
return uniqueOrigins;
}
private extractWebhookOrigins(obj: { [key: string]: string }): string[] {
const origins: string[] = [];
const keys = Object.getOwnPropertyNames(obj);
keys.forEach((key) => {
const value = obj[key];
if (isURL(value, this.urlValidationOptions)) {
const valueAsUrl = new url.URL(value);
const origin = valueAsUrl.origin;
origins.push(origin);
}
});
return origins;
}
private async getStatusInternal(options: GetStatusOptions): Promise<AxiosResponse> {
let requestUrl: string;
if (this.clientData.rpcBaseUrl) {
// Fast local RPC path
let path = new URL(`instances/${options.instanceId || ""}`, this.clientData.rpcBaseUrl).href;
const query: string[] = [];
if (options.taskHubName) { query.push(`taskHub=${options.taskHubName}`); }
if (options.connectionName) { query.push(`connection=${options.connectionName}`); }
if (options.showHistory) { query.push(`showHistory=${options.showHistory}`); }
if (options.showHistoryOutput) { query.push(`showHistoryOutput=${options.showHistoryOutput}`); }
if (options.showInput) { query.push(`showInput=${options.showInput}`); }
if (options.createdTimeFrom) { query.push(`createdTimeFrom=${options.createdTimeFrom.toISOString()}`); }
if (options.createdTimeTo) { query.push(`createdTimeTo=${options.createdTimeTo.toISOString()}`); }
if (options.runtimeStatus && options.runtimeStatus.length > 0) {
const statusList: string = options.runtimeStatus.map((value) => value.toString()).join(",");
query.push(`runtimeStatus=${statusList}`);
}
if (query.length > 0) {
path += "?" + query.join("&");
}
requestUrl = new URL(path, this.clientData.rpcBaseUrl).href;
} else {
// Legacy app frontend code path
const template = this.clientData.managementUrls.statusQueryGetUri;
const idPlaceholder = this.clientData.managementUrls.id;
requestUrl = template.replace(idPlaceholder, typeof(options.instanceId) === "string" ? options.instanceId : "");
if (options.taskHubName) {
requestUrl = requestUrl.replace(this.clientData.taskHubName, options.taskHubName);
}
if (options.connectionName) {
requestUrl = requestUrl.replace(/(connection=)([\w]+)/gi, "$1" + options.connectionName);
}
if (options.showHistory) {
requestUrl += `&${this.showHistoryQueryKey}=${options.showHistory}`;
}
if (options.showHistoryOutput) {
requestUrl += `&${this.showHistoryOutputQueryKey}=${options.showHistoryOutput}`;
}
if (options.createdTimeFrom) {
requestUrl += `&${this.createdTimeFromQueryKey}=${options.createdTimeFrom.toISOString()}`;
}
if (options.createdTimeTo) {
requestUrl += `&${this.createdTimeToQueryKey}=${options.createdTimeTo.toISOString()}`;
}
if (options.runtimeStatus && options.runtimeStatus.length > 0) {
const statusesString = options.runtimeStatus
.map((value) => value.toString())
.reduce((acc, curr, i, arr) => {
return acc + (i > 0 ? "," : "") + curr;
});
requestUrl += `&${this.runtimeStatusQueryKey}=${statusesString}`;
}
if (typeof options.showInput === "boolean") {
requestUrl += `&${this.showInputQueryKey}=${options.showInput}`;
}
}
return this.axiosInstance.get(requestUrl);
}
private createGenericError(response: AxiosResponse<any>): Error {
return new Error(`The operation failed with an unexpected status code: ${response.status}. Details: ${JSON.stringify(response.data)}`);
}
}