@azure/core-lro 2.2.5-alpha.20220415.2 → 2.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18,8 +18,8 @@ class PollerStoppedError extends Error {
18
18
  }
19
19
  }
20
20
  /**
21
- * When a poller is cancelled through the `cancelOperation` method,
22
- * the poller will be rejected with an instance of the PollerCancelledError.
21
+ * When the operation is cancelled, the poller will be rejected with an instance
22
+ * of the PollerCancelledError.
23
23
  */
24
24
  class PollerCancelledError extends Error {
25
25
  constructor(message) {
@@ -193,29 +193,18 @@ class Poller {
193
193
  * @param options - Optional properties passed to the operation's update method.
194
194
  */
195
195
  async pollOnce(options = {}) {
196
- try {
197
- if (!this.isDone()) {
196
+ if (!this.isDone()) {
197
+ try {
198
198
  this.operation = await this.operation.update({
199
199
  abortSignal: options.abortSignal,
200
200
  fireProgress: this.fireProgress.bind(this),
201
201
  });
202
- if (this.isDone() && this.resolve) {
203
- // If the poller has finished polling, this means we now have a result.
204
- // However, it can be the case that TResult is instantiated to void, so
205
- // we are not expecting a result anyway. To assert that we might not
206
- // have a result eventually after finishing polling, we cast the result
207
- // to TResult.
208
- this.resolve(this.operation.state.result);
209
- }
210
202
  }
211
- }
212
- catch (e) {
213
- this.operation.state.error = e;
214
- if (this.reject) {
215
- this.reject(e);
203
+ catch (e) {
204
+ this.operation.state.error = e;
216
205
  }
217
- throw e;
218
206
  }
207
+ this.processUpdatedState();
219
208
  }
220
209
  /**
221
210
  * fireProgress calls the functions passed in via onProgress the method of the poller.
@@ -231,14 +220,10 @@ class Poller {
231
220
  }
232
221
  }
233
222
  /**
234
- * Invokes the underlying operation's cancel method, and rejects the
235
- * pollUntilDone promise.
223
+ * Invokes the underlying operation's cancel method.
236
224
  */
237
225
  async cancelOnce(options = {}) {
238
226
  this.operation = await this.operation.cancel(options);
239
- if (this.reject) {
240
- this.reject(new PollerCancelledError("Poller cancelled"));
241
- }
242
227
  }
243
228
  /**
244
229
  * Returns a promise that will resolve once a single polling request finishes.
@@ -258,6 +243,27 @@ class Poller {
258
243
  }
259
244
  return this.pollOncePromise;
260
245
  }
246
+ processUpdatedState() {
247
+ if (this.operation.state.error) {
248
+ this.stopped = true;
249
+ this.reject(this.operation.state.error);
250
+ throw this.operation.state.error;
251
+ }
252
+ if (this.operation.state.isCancelled) {
253
+ this.stopped = true;
254
+ const error = new PollerCancelledError("Poller cancelled");
255
+ this.reject(error);
256
+ throw error;
257
+ }
258
+ else if (this.isDone() && this.resolve) {
259
+ // If the poller has finished polling, this means we now have a result.
260
+ // However, it can be the case that TResult is instantiated to void, so
261
+ // we are not expecting a result anyway. To assert that we might not
262
+ // have a result eventually after finishing polling, we cast the result
263
+ // to TResult.
264
+ this.resolve(this.operation.state.result);
265
+ }
266
+ }
261
267
  /**
262
268
  * Returns a promise that will resolve once the underlying operation is completed.
263
269
  */
@@ -265,6 +271,9 @@ class Poller {
265
271
  if (this.stopped) {
266
272
  this.startPolling().catch(this.reject);
267
273
  }
274
+ // This is needed because the state could have been updated by
275
+ // `cancelOperation`, e.g. the operation is canceled or an error occurred.
276
+ this.processUpdatedState();
268
277
  return this.promise;
269
278
  }
270
279
  /**
@@ -313,9 +322,6 @@ class Poller {
313
322
  * @param options - Optional properties passed to the operation's update method.
314
323
  */
315
324
  cancelOperation(options = {}) {
316
- if (!this.stopped) {
317
- this.stopped = true;
318
- }
319
325
  if (!this.cancelPromise) {
320
326
  this.cancelPromise = this.cancelOnce(options);
321
327
  }
@@ -395,16 +401,40 @@ class Poller {
395
401
  }
396
402
 
397
403
  // Copyright (c) Microsoft Corporation.
398
- // Licensed under the MIT license.
399
404
  /**
400
- * Detects where the continuation token is and returns it. Notice that azure-asyncoperation
401
- * must be checked first before the other location headers because there are scenarios
402
- * where both azure-asyncoperation and location could be present in the same response but
403
- * azure-asyncoperation should be the one to use for polling.
405
+ * The `@azure/logger` configuration for this package.
406
+ * @internal
404
407
  */
405
- function getPollingUrl(rawResponse, defaultPath) {
406
- var _a, _b, _c;
407
- return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getOperationLocation(rawResponse)) !== null && _b !== void 0 ? _b : getLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath);
408
+ const logger = logger$1.createClientLogger("core-lro");
409
+
410
+ // Copyright (c) Microsoft Corporation.
411
+ function throwIfUndefined(input, options = {}) {
412
+ var _a;
413
+ if (input === undefined) {
414
+ throw new Error((_a = options.errorMessage) !== null && _a !== void 0 ? _a : "undefined variable");
415
+ }
416
+ return input;
417
+ }
418
+ function updatePollingUrl(inputs) {
419
+ var _a, _b;
420
+ const { info, rawResponse } = inputs;
421
+ switch (info.mode) {
422
+ case "OperationLocation": {
423
+ const operationLocation = getOperationLocation(rawResponse);
424
+ const azureAsyncOperation = getAzureAsyncOperation(rawResponse);
425
+ info.pollingUrl =
426
+ (_a = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation })) !== null && _a !== void 0 ? _a : throwIfUndefined(info.pollingUrl);
427
+ break;
428
+ }
429
+ case "ResourceLocation": {
430
+ info.pollingUrl = (_b = getLocation(rawResponse)) !== null && _b !== void 0 ? _b : throwIfUndefined(info.pollingUrl);
431
+ break;
432
+ }
433
+ }
434
+ }
435
+ function getOperationLocationPollingUrl(inputs) {
436
+ const { azureAsyncOperation, operationLocation } = inputs;
437
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
408
438
  }
409
439
  function getLocation(rawResponse) {
410
440
  return rawResponse.headers["location"];
@@ -415,39 +445,65 @@ function getOperationLocation(rawResponse) {
415
445
  function getAzureAsyncOperation(rawResponse) {
416
446
  return rawResponse.headers["azure-asyncoperation"];
417
447
  }
418
- function findResourceLocation(requestMethod, rawResponse, requestPath) {
448
+ function findResourceLocation(inputs) {
449
+ const { location, requestMethod, requestPath, lroResourceLocationConfig } = inputs;
419
450
  switch (requestMethod) {
420
451
  case "PUT": {
421
452
  return requestPath;
422
453
  }
423
- case "POST":
424
- case "PATCH": {
425
- return getLocation(rawResponse);
454
+ case "DELETE": {
455
+ return undefined;
426
456
  }
427
457
  default: {
428
- return undefined;
458
+ switch (lroResourceLocationConfig) {
459
+ case "azure-async-operation": {
460
+ return undefined;
461
+ }
462
+ case "original-uri": {
463
+ return requestPath;
464
+ }
465
+ case "location":
466
+ default: {
467
+ return location;
468
+ }
469
+ }
429
470
  }
430
471
  }
431
472
  }
432
- function inferLroMode(requestPath, requestMethod, rawResponse) {
433
- if (getAzureAsyncOperation(rawResponse) !== undefined ||
434
- getOperationLocation(rawResponse) !== undefined) {
473
+ function inferLroMode(inputs) {
474
+ const { rawResponse, requestMethod, requestPath, lroResourceLocationConfig } = inputs;
475
+ const operationLocation = getOperationLocation(rawResponse);
476
+ const azureAsyncOperation = getAzureAsyncOperation(rawResponse);
477
+ const location = getLocation(rawResponse);
478
+ if (operationLocation !== undefined || azureAsyncOperation !== undefined) {
435
479
  return {
436
- mode: "Location",
437
- resourceLocation: findResourceLocation(requestMethod, rawResponse, requestPath),
480
+ mode: "OperationLocation",
481
+ pollingUrl: operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation,
482
+ resourceLocation: findResourceLocation({
483
+ requestMethod,
484
+ location,
485
+ requestPath,
486
+ lroResourceLocationConfig,
487
+ }),
438
488
  };
439
489
  }
440
- else if (getLocation(rawResponse) !== undefined) {
490
+ else if (location !== undefined) {
441
491
  return {
442
- mode: "Location",
492
+ mode: "ResourceLocation",
493
+ pollingUrl: location,
443
494
  };
444
495
  }
445
- else if (["PUT", "PATCH"].includes(requestMethod)) {
496
+ else if (requestMethod === "PUT") {
446
497
  return {
447
498
  mode: "Body",
499
+ pollingUrl: requestPath,
500
+ };
501
+ }
502
+ else {
503
+ return {
504
+ mode: "None",
448
505
  };
449
506
  }
450
- return {};
451
507
  }
452
508
  class SimpleRestError extends Error {
453
509
  constructor(message, statusCode) {
@@ -457,122 +513,86 @@ class SimpleRestError extends Error {
457
513
  Object.setPrototypeOf(this, SimpleRestError.prototype);
458
514
  }
459
515
  }
460
- function isUnexpectedInitialResponse(rawResponse) {
461
- const code = rawResponse.statusCode;
462
- if (![203, 204, 202, 201, 200, 500].includes(code)) {
463
- throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code);
464
- }
465
- return false;
466
- }
467
- function isUnexpectedPollingResponse(rawResponse) {
516
+ function throwIfError(rawResponse) {
468
517
  const code = rawResponse.statusCode;
469
- if (![202, 201, 200, 500].includes(code)) {
518
+ if (code >= 400) {
470
519
  throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code);
471
520
  }
472
- return false;
473
521
  }
474
-
475
- // Copyright (c) Microsoft Corporation.
476
- // Licensed under the MIT license.
477
- const successStates = ["succeeded"];
478
- const failureStates = ["failed", "canceled", "cancelled"];
479
-
480
- // Copyright (c) Microsoft Corporation.
522
+ function getStatus(rawResponse) {
523
+ var _a;
524
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
525
+ return typeof status === "string" ? status.toLowerCase() : "succeeded";
526
+ }
481
527
  function getProvisioningState(rawResponse) {
482
528
  var _a, _b;
483
529
  const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
484
530
  const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
485
531
  return typeof state === "string" ? state.toLowerCase() : "succeeded";
486
532
  }
487
- function isBodyPollingDone(rawResponse) {
488
- const state = getProvisioningState(rawResponse);
489
- if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) {
490
- throw new Error(`The long running operation has failed. The provisioning state: ${state}.`);
533
+ function isCanceled(operation) {
534
+ const { state, operationStatus } = operation;
535
+ if (["canceled", "cancelled"].includes(operationStatus)) {
536
+ state.isCancelled = true;
537
+ return true;
491
538
  }
492
- return successStates.includes(state);
493
- }
494
- /**
495
- * Creates a polling strategy based on BodyPolling which uses the provisioning state
496
- * from the result to determine the current operation state
497
- */
498
- function processBodyPollingOperationResult(response) {
499
- return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) });
500
- }
501
-
502
- // Copyright (c) Microsoft Corporation.
503
- /**
504
- * The `@azure/logger` configuration for this package.
505
- * @internal
506
- */
507
- const logger = logger$1.createClientLogger("core-lro");
508
-
509
- // Copyright (c) Microsoft Corporation.
510
- function isPollingDone(rawResponse) {
511
- var _a;
512
- if (isUnexpectedPollingResponse(rawResponse) || rawResponse.statusCode === 202) {
513
- return false;
514
- }
515
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
516
- const state = typeof status === "string" ? status.toLowerCase() : "succeeded";
517
- if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) {
518
- throw new Error(`The long running operation has failed. The provisioning state: ${state}.`);
519
- }
520
- return successStates.includes(state);
539
+ return false;
521
540
  }
522
- /**
523
- * Sends a request to the URI of the provisioned resource if needed.
524
- */
525
- async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) {
526
- switch (lroResourceLocationConfig) {
527
- case "original-uri":
528
- return lro.sendPollRequest(lro.requestPath);
529
- case "azure-async-operation":
530
- return undefined;
531
- case "location":
532
- default:
533
- return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath);
541
+ function isTerminal(operation) {
542
+ const { state, operationStatus } = operation;
543
+ if (operationStatus === "failed") {
544
+ throw new Error(`The long-running operation has failed.`);
534
545
  }
546
+ return operationStatus === "succeeded" || isCanceled({ state, operationStatus });
535
547
  }
536
- function processLocationPollingOperationResult(lro, resourceLocation, lroResourceLocationConfig) {
537
- return (response) => {
538
- if (isPollingDone(response.rawResponse)) {
539
- if (resourceLocation === undefined) {
540
- return Object.assign(Object.assign({}, response), { done: true });
541
- }
542
- else {
543
- return Object.assign(Object.assign({}, response), { done: false, next: async () => {
544
- const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig);
545
- return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true });
546
- } });
547
- }
548
- }
549
- return Object.assign(Object.assign({}, response), { done: false });
550
- };
551
- }
552
-
553
- // Copyright (c) Microsoft Corporation.
554
- // Licensed under the MIT license.
555
- function processPassthroughOperationResult(response) {
556
- return Object.assign(Object.assign({}, response), { done: true });
557
- }
558
-
559
- // Copyright (c) Microsoft Corporation.
560
- /**
561
- * creates a stepping function that maps an LRO state to another.
562
- */
563
- function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) {
564
- switch (config.mode) {
565
- case "Location": {
566
- return processLocationPollingOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig);
548
+ function getOperationStatus(result) {
549
+ const { rawResponse, state, info, responseKind = "Polling" } = result;
550
+ throwIfError(rawResponse);
551
+ switch (info.mode) {
552
+ case "OperationLocation": {
553
+ const operationStatus = getStatus(rawResponse);
554
+ return {
555
+ operationStatus,
556
+ shouldStopPolling: responseKind === "Polling" && isTerminal({ state, operationStatus }),
557
+ };
567
558
  }
568
559
  case "Body": {
569
- return processBodyPollingOperationResult;
560
+ const operationStatus = getProvisioningState(rawResponse);
561
+ return {
562
+ operationStatus,
563
+ shouldStopPolling: isTerminal({ state, operationStatus }),
564
+ };
570
565
  }
571
- default: {
572
- return processPassthroughOperationResult;
566
+ case "ResourceLocation": {
567
+ const operationStatus = rawResponse.statusCode;
568
+ return {
569
+ operationStatus,
570
+ shouldStopPolling: responseKind === "Polling" && operationStatus !== 202,
571
+ };
572
+ }
573
+ case "None": {
574
+ return {
575
+ shouldStopPolling: true,
576
+ };
573
577
  }
574
578
  }
575
579
  }
580
+ function shouldStopPolling(result) {
581
+ const { rawResponse, state, info, responseKind = "Polling" } = result;
582
+ const { shouldStopPolling: isPollingStopped, operationStatus } = getOperationStatus({
583
+ info,
584
+ rawResponse,
585
+ state,
586
+ responseKind,
587
+ });
588
+ if (operationStatus) {
589
+ logger.verbose(`LRO: Status:\n\tPolling from: ${info.pollingUrl}\n\tOperation status: ${operationStatus}\n\tPolling status: ${isPollingStopped ? "Stopped" : "Running"}`);
590
+ }
591
+ else {
592
+ logger.verbose(`LRO: Status: Not an LRO`);
593
+ }
594
+ return isPollingStopped;
595
+ }
576
596
  /**
577
597
  * Creates a polling operation.
578
598
  */
@@ -598,29 +618,53 @@ function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) {
598
618
  }
599
619
  return defaultIntervalInMs;
600
620
  }
621
+ function buildResult(inputs) {
622
+ const { processResult, response, state } = inputs;
623
+ return processResult ? processResult(response, state) : response;
624
+ }
601
625
  /**
602
626
  * Creates a callback to be used to initialize the polling operation state.
603
- * @param state - of the polling operation
604
- * @param operationSpec - of the LRO
605
- * @param callback - callback to be called when the operation is done
606
- * @returns callback that initializes the state of the polling operation
607
627
  */
608
- function createInitializeState(state, requestPath, requestMethod) {
628
+ function createStateInitializer(inputs) {
629
+ const { requestMethod, requestPath, state, lroResourceLocationConfig, processResult } = inputs;
609
630
  return (response) => {
610
- if (isUnexpectedInitialResponse(response.rawResponse))
611
- ;
612
- state.initialRawResponse = response.rawResponse;
631
+ const { rawResponse } = response;
613
632
  state.isStarted = true;
614
- state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath);
615
- state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse);
616
- /** short circuit polling if body polling is done in the initial request */
617
- if (state.config.mode === undefined ||
618
- (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) {
619
- state.result = response.flatResponse;
633
+ state.config = inferLroMode({
634
+ rawResponse,
635
+ requestPath,
636
+ requestMethod,
637
+ lroResourceLocationConfig,
638
+ });
639
+ logger.verbose(`LRO: Operation description:`, state.config);
640
+ /** short circuit before polling */
641
+ if (shouldStopPolling({
642
+ rawResponse,
643
+ state,
644
+ info: state.config,
645
+ responseKind: "Initial",
646
+ })) {
647
+ state.result = buildResult({
648
+ response: response.flatResponse,
649
+ state: state,
650
+ processResult,
651
+ });
620
652
  state.isCompleted = true;
621
653
  }
622
- logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`);
623
- return Boolean(state.isCompleted);
654
+ };
655
+ }
656
+ function createGetLroStatusFromResponse(inputs) {
657
+ const { lro, state, info } = inputs;
658
+ const location = info.resourceLocation;
659
+ return (response) => {
660
+ const isTerminalStatus = shouldStopPolling({
661
+ info,
662
+ rawResponse: response.rawResponse,
663
+ state,
664
+ });
665
+ return Object.assign(Object.assign({}, response), { done: isTerminalStatus && !location, next: !(isTerminalStatus && location)
666
+ ? undefined
667
+ : () => lro.sendPollRequest(location).then((res) => (Object.assign(Object.assign({}, res), { done: true }))) });
624
668
  };
625
669
  }
626
670
 
@@ -657,39 +701,53 @@ class GenericPollOperation {
657
701
  const state = this.state;
658
702
  let lastResponse = undefined;
659
703
  if (!state.isStarted) {
660
- const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod);
704
+ const initializeState = createStateInitializer({
705
+ state,
706
+ requestPath: this.lro.requestPath,
707
+ requestMethod: this.lro.requestMethod,
708
+ lroResourceLocationConfig: this.lroResourceLocationConfig,
709
+ processResult: this.processResult,
710
+ });
661
711
  lastResponse = await this.lro.sendInitialRequest();
662
712
  initializeState(lastResponse);
663
713
  }
664
714
  if (!state.isCompleted) {
665
- if (!this.poll || !this.getLroStatusFromResponse) {
666
- if (!state.config) {
667
- throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed.");
668
- }
715
+ const config = throwIfUndefined(state.config, {
716
+ errorMessage: "Bad state: LRO mode is undefined. Check if the serialized state is well-formed.",
717
+ });
718
+ if (!this.poll) {
719
+ this.poll = createPoll(this.lro);
720
+ }
721
+ if (!this.getLroStatusFromResponse) {
669
722
  const isDone = this.isDone;
670
723
  this.getLroStatusFromResponse = isDone
671
724
  ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) }))
672
- : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig);
673
- this.poll = createPoll(this.lro);
725
+ : createGetLroStatusFromResponse({
726
+ lro: this.lro,
727
+ info: config,
728
+ state: this.state,
729
+ });
674
730
  }
675
- if (!state.pollingURL) {
676
- throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed.");
677
- }
678
- const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse);
679
- logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`);
731
+ const currentState = await this.poll(throwIfUndefined(config.pollingUrl), this.pollerConfig, this.getLroStatusFromResponse);
680
732
  if (currentState.done) {
681
- state.result = this.processResult
682
- ? this.processResult(currentState.flatResponse, state)
683
- : currentState.flatResponse;
733
+ state.result = buildResult({
734
+ response: currentState.flatResponse,
735
+ state,
736
+ processResult: this.processResult,
737
+ });
684
738
  state.isCompleted = true;
685
739
  }
686
740
  else {
687
741
  this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll;
688
- state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL);
742
+ updatePollingUrl({
743
+ rawResponse: currentState.rawResponse,
744
+ info: config,
745
+ });
746
+ /** for backward compatability */
747
+ state.pollingURL = config.pollingUrl;
689
748
  }
690
749
  lastResponse = currentState;
691
750
  }
692
- logger.verbose(`LRO: current state: ${JSON.stringify(state)}`);
693
751
  if (lastResponse) {
694
752
  (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse);
695
753
  }
@@ -700,7 +758,7 @@ class GenericPollOperation {
700
758
  return this;
701
759
  }
702
760
  async cancel() {
703
- this.state.isCancelled = true;
761
+ logger.error("`cancelOperation` is deprecated because it wasn't implemented");
704
762
  return this;
705
763
  }
706
764
  /**