@azure/core-lro 2.3.0-beta.1 → 2.3.0

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.
Files changed (56) hide show
  1. package/dist/index.js +720 -391
  2. package/dist/index.js.map +1 -1
  3. package/dist-esm/src/{lroEngine → http}/models.js +0 -0
  4. package/dist-esm/src/http/models.js.map +1 -0
  5. package/dist-esm/src/http/operation.js +228 -0
  6. package/dist-esm/src/http/operation.js.map +1 -0
  7. package/dist-esm/src/http/poller.js +47 -0
  8. package/dist-esm/src/http/poller.js.map +1 -0
  9. package/dist-esm/src/index.js +16 -3
  10. package/dist-esm/src/index.js.map +1 -1
  11. package/dist-esm/src/{lroEngine → legacy/lroEngine}/index.js +0 -0
  12. package/dist-esm/src/legacy/lroEngine/index.js.map +1 -0
  13. package/dist-esm/src/{lroEngine → legacy/lroEngine}/lroEngine.js +4 -10
  14. package/dist-esm/src/legacy/lroEngine/lroEngine.js.map +1 -0
  15. package/dist-esm/src/legacy/lroEngine/models.js +4 -0
  16. package/dist-esm/src/legacy/lroEngine/models.js.map +1 -0
  17. package/dist-esm/src/legacy/lroEngine/operation.js +81 -0
  18. package/dist-esm/src/legacy/lroEngine/operation.js.map +1 -0
  19. package/dist-esm/src/legacy/models.js +4 -0
  20. package/dist-esm/src/legacy/models.js.map +1 -0
  21. package/dist-esm/src/{pollOperation.js → legacy/pollOperation.js} +0 -0
  22. package/dist-esm/src/legacy/pollOperation.js.map +1 -0
  23. package/dist-esm/src/{poller.js → legacy/poller.js} +36 -30
  24. package/dist-esm/src/legacy/poller.js.map +1 -0
  25. package/dist-esm/src/{lroEngine/logger.js → logger.js} +0 -0
  26. package/dist-esm/src/logger.js.map +1 -0
  27. package/dist-esm/src/poller/constants.js +11 -0
  28. package/dist-esm/src/poller/constants.js.map +1 -0
  29. package/dist-esm/src/poller/models.js +4 -0
  30. package/dist-esm/src/poller/models.js.map +1 -0
  31. package/dist-esm/src/poller/operation.js +131 -0
  32. package/dist-esm/src/poller/operation.js.map +1 -0
  33. package/dist-esm/src/poller/poller.js +140 -0
  34. package/dist-esm/src/poller/poller.js.map +1 -0
  35. package/dist-esm/src/poller/util/delayMs.js +52 -0
  36. package/dist-esm/src/poller/util/delayMs.js.map +1 -0
  37. package/package.json +3 -8
  38. package/types/core-lro.d.ts +145 -21
  39. package/dist-esm/src/lroEngine/bodyPolling.js +0 -21
  40. package/dist-esm/src/lroEngine/bodyPolling.js.map +0 -1
  41. package/dist-esm/src/lroEngine/index.js.map +0 -1
  42. package/dist-esm/src/lroEngine/locationPolling.js +0 -50
  43. package/dist-esm/src/lroEngine/locationPolling.js.map +0 -1
  44. package/dist-esm/src/lroEngine/logger.js.map +0 -1
  45. package/dist-esm/src/lroEngine/lroEngine.js.map +0 -1
  46. package/dist-esm/src/lroEngine/models.js.map +0 -1
  47. package/dist-esm/src/lroEngine/operation.js +0 -101
  48. package/dist-esm/src/lroEngine/operation.js.map +0 -1
  49. package/dist-esm/src/lroEngine/passthrough.js +0 -6
  50. package/dist-esm/src/lroEngine/passthrough.js.map +0 -1
  51. package/dist-esm/src/lroEngine/requestUtils.js +0 -102
  52. package/dist-esm/src/lroEngine/requestUtils.js.map +0 -1
  53. package/dist-esm/src/lroEngine/stateMachine.js +0 -78
  54. package/dist-esm/src/lroEngine/stateMachine.js.map +0 -1
  55. package/dist-esm/src/pollOperation.js.map +0 -1
  56. package/dist-esm/src/poller.js.map +0 -1
@@ -0,0 +1,131 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { logger } from "../logger";
4
+ import { terminalStates } from "./constants";
5
+ /**
6
+ * Deserializes the state
7
+ */
8
+ export function deserializeState(serializedState) {
9
+ try {
10
+ return JSON.parse(serializedState).state;
11
+ }
12
+ catch (e) {
13
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
14
+ }
15
+ }
16
+ function setStateError(inputs) {
17
+ const { state, stateProxy } = inputs;
18
+ return (error) => {
19
+ stateProxy.setError(state, error);
20
+ stateProxy.setFailed(state);
21
+ throw error;
22
+ };
23
+ }
24
+ function processOperationStatus(result) {
25
+ const { state, stateProxy, status } = result;
26
+ logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${terminalStates.includes(status) ? "Stopped" : "Running"}`);
27
+ switch (status) {
28
+ case "succeeded": {
29
+ stateProxy.setSucceeded(state);
30
+ break;
31
+ }
32
+ case "failed": {
33
+ stateProxy.setError(state, new Error(`The long-running operation has failed`));
34
+ stateProxy.setFailed(state);
35
+ break;
36
+ }
37
+ case "canceled": {
38
+ stateProxy.setCanceled(state);
39
+ break;
40
+ }
41
+ }
42
+ }
43
+ function buildResult(inputs) {
44
+ const { processResult, response, state } = inputs;
45
+ return processResult ? processResult(response, state) : response;
46
+ }
47
+ /**
48
+ * Initiates the long-running operation.
49
+ */
50
+ export async function initOperation(inputs) {
51
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation } = inputs;
52
+ const { operationLocation, resourceLocation, metadata, response } = await init();
53
+ if (operationLocation)
54
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
55
+ const config = {
56
+ metadata,
57
+ operationLocation,
58
+ resourceLocation,
59
+ };
60
+ logger.verbose(`LRO: Operation description:`, config);
61
+ const state = stateProxy.initState(config);
62
+ const status = getOperationStatus(response, state);
63
+ if (status === "succeeded" || operationLocation === undefined) {
64
+ stateProxy.setSucceeded(state);
65
+ stateProxy.setResult(state, buildResult({
66
+ response,
67
+ state,
68
+ processResult,
69
+ }));
70
+ }
71
+ return state;
72
+ }
73
+ async function pollOperationHelper(inputs) {
74
+ const { poll, state, stateProxy, operationLocation, resourceLocation, getOperationStatus, options, } = inputs;
75
+ const response = await poll(operationLocation, options).catch(setStateError({
76
+ state,
77
+ stateProxy,
78
+ }));
79
+ const status = getOperationStatus(response, state);
80
+ processOperationStatus({
81
+ status,
82
+ state,
83
+ stateProxy,
84
+ });
85
+ if (status === "succeeded" && resourceLocation !== undefined) {
86
+ return {
87
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy })),
88
+ status,
89
+ };
90
+ }
91
+ return { response, status };
92
+ }
93
+ /** Polls the long-running operation. */
94
+ export async function pollOperation(inputs) {
95
+ const { poll, state, stateProxy, options, getOperationStatus, getOperationLocation, withOperationLocation, getPollingInterval, processResult, updateState, setDelay, isDone, } = inputs;
96
+ const { operationLocation, resourceLocation } = state.config;
97
+ if (operationLocation !== undefined) {
98
+ const { response, status } = await pollOperationHelper({
99
+ poll,
100
+ getOperationStatus,
101
+ state,
102
+ stateProxy,
103
+ operationLocation,
104
+ resourceLocation,
105
+ options,
106
+ });
107
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
108
+ (isDone === undefined && ["succeeded", "canceled"].includes(status))) {
109
+ stateProxy.setResult(state, buildResult({
110
+ response,
111
+ state,
112
+ processResult,
113
+ }));
114
+ }
115
+ else {
116
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
117
+ if (intervalInMs)
118
+ setDelay(intervalInMs);
119
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
120
+ if (location !== undefined) {
121
+ const isUpdated = operationLocation !== location;
122
+ state.config.operationLocation = location;
123
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
124
+ }
125
+ else
126
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
127
+ }
128
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
129
+ }
130
+ }
131
+ //# sourceMappingURL=operation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operation.js","sourceRoot":"","sources":["../../../src/poller/operation.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAGlC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,E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aAAN,MAAM,uBAAN,MAAM,CAAG,QAAQ,EAAE,KAAK,CAAC;YACzB,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EACpE;YACA,UAAU,CAAC,SAAS,CAClB,KAAK,EACL,WAAW,CAAC;gBACV,QAAQ;gBACR,KAAK;gBACL,aAAa;aACd,CAAC,CACH,CAAC;SACH;aAAM;YACL,MAAM,YAAY,GAAG,kBAAkB,aAAlB,kBAAkB,uBAAlB,kBAAkB,CAAG,QAAQ,CAAC,CAAC;YACpD,IAAI,YAAY;gBAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;YACzC,MAAM,QAAQ,GAAG,oBAAoB,aAApB,oBAAoB,uBAApB,oBAAoB,CAAG,QAAQ,EAAE,KAAK,CAAC,CAAC;YACzD,IAAI,QAAQ,KAAK,SAAS,EAAE;gBAC1B,MAAM,SAAS,GAAG,iBAAiB,KAAK,QAAQ,CAAC;gBACjD,KAAK,CAAC,MAAM,CAAC,iBAAiB,GAAG,QAAQ,CAAC;gBAC1C,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAG,QAAQ,EAAE,SAAS,CAAC,CAAC;aAC9C;;gBAAM,qBAAqB,aAArB,qBAAqB,uBAArB,qBAAqB,CAAG,iBAAiB,EAAE,KAAK,CAAC,CAAC;SAC1D;QACD,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAG,KAAK,EAAE,QAAQ,CAAC,CAAC;KAChC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { Operation, OperationStatus, RestorableOperationState, StateProxy } from \"./models\";\nimport { logger } from \"../logger\";\nimport { terminalStates } from \"./constants\";\n\n/**\n * Deserializes the state\n */\nexport function deserializeState<TState>(\n serializedState: string\n): RestorableOperationState<TState> {\n try {\n return JSON.parse(serializedState).state;\n } catch (e) {\n throw new Error(`Unable to deserialize input state: ${serializedState}`);\n }\n}\n\nfunction setStateError<TState, TResult>(inputs: {\n state: TState;\n stateProxy: StateProxy<TState, TResult>;\n}): (error: Error) => never {\n const { state, stateProxy } = inputs;\n return (error: Error) => {\n stateProxy.setError(state, error);\n stateProxy.setFailed(state);\n throw error;\n };\n}\n\nfunction processOperationStatus<TState, TResult>(result: {\n status: OperationStatus;\n state: RestorableOperationState<TState>;\n stateProxy: StateProxy<TState, TResult>;\n}): void {\n const { state, stateProxy, status } = result;\n logger.verbose(\n `LRO: Status:\\n\\tPolling from: ${\n state.config.operationLocation\n }\\n\\tOperation status: ${status}\\n\\tPolling status: ${\n terminalStates.includes(status) ? \"Stopped\" : \"Running\"\n }`\n );\n switch (status) {\n case \"succeeded\": {\n stateProxy.setSucceeded(state);\n break;\n }\n case \"failed\": {\n stateProxy.setError(state, new Error(`The long-running operation has failed`));\n stateProxy.setFailed(state);\n break;\n }\n case \"canceled\": {\n stateProxy.setCanceled(state);\n break;\n }\n }\n}\n\nfunction buildResult<TResponse, TResult, TState>(inputs: {\n response: TResponse;\n state: TState;\n processResult?: (result: TResponse, state: TState) => TResult;\n}): TResult {\n const { processResult, response, state } = inputs;\n return processResult ? processResult(response, state) : (response as unknown as TResult);\n}\n\n/**\n * Initiates the long-running operation.\n */\nexport async function initOperation<TResponse, TResult, TState>(inputs: {\n init: Operation<TResponse, unknown>[\"init\"];\n stateProxy: StateProxy<TState, TResult>;\n getOperationStatus: (\n response: TResponse,\n state: RestorableOperationState<TState>\n ) => OperationStatus;\n processResult?: (result: TResponse, state: TState) => TResult;\n withOperationLocation?: (operationLocation: string, isUpdated: boolean) => void;\n}): Promise<RestorableOperationState<TState>> {\n const { init, stateProxy, processResult, getOperationStatus, withOperationLocation } = inputs;\n const { operationLocation, resourceLocation, metadata, response } = await init();\n if (operationLocation) withOperationLocation?.(operationLocation, false);\n const config = {\n metadata,\n operationLocation,\n resourceLocation,\n };\n logger.verbose(`LRO: Operation description:`, config);\n const state = stateProxy.initState(config);\n const status = getOperationStatus(response, state);\n if (status === \"succeeded\" || operationLocation === undefined) {\n stateProxy.setSucceeded(state);\n stateProxy.setResult(\n state,\n buildResult({\n response,\n state,\n processResult,\n })\n );\n }\n return state;\n}\n\nasync function pollOperationHelper<TResponse, TState, TResult, TOptions>(inputs: {\n poll: Operation<TResponse, TOptions>[\"poll\"];\n stateProxy: StateProxy<TState, TResult>;\n state: RestorableOperationState<TState>;\n operationLocation: string;\n resourceLocation?: string;\n getOperationStatus: (\n response: TResponse,\n state: RestorableOperationState<TState>\n ) => OperationStatus;\n options?: TOptions;\n}): Promise<{\n status: OperationStatus;\n response: TResponse;\n}> {\n const {\n poll,\n state,\n stateProxy,\n operationLocation,\n resourceLocation,\n getOperationStatus,\n options,\n } = inputs;\n const response = await poll(operationLocation, options).catch(\n setStateError({\n state,\n stateProxy,\n })\n );\n const status = getOperationStatus(response, state);\n processOperationStatus({\n status,\n state,\n stateProxy,\n });\n if (status === \"succeeded\" && resourceLocation !== undefined) {\n return {\n response: await poll(resourceLocation).catch(setStateError({ state, stateProxy })),\n status,\n };\n }\n return { response, status };\n}\n\n/** Polls the long-running operation. */\nexport async function pollOperation<TResponse, TState, TResult, TOptions>(inputs: {\n poll: Operation<TResponse, TOptions>[\"poll\"];\n stateProxy: StateProxy<TState, TResult>;\n state: RestorableOperationState<TState>;\n getOperationStatus: (\n response: TResponse,\n state: RestorableOperationState<TState>\n ) => OperationStatus;\n getPollingInterval?: (response: TResponse) => number | undefined;\n setDelay: (intervalInMs: number) => void;\n getOperationLocation?: (\n response: TResponse,\n state: RestorableOperationState<TState>\n ) => string | undefined;\n withOperationLocation?: (operationLocation: string, isUpdated: boolean) => void;\n processResult?: (result: TResponse, state: TState) => TResult;\n updateState?: (state: TState, lastResponse: TResponse) => void;\n isDone?: (lastResponse: TResponse, state: TState) => boolean;\n options?: TOptions;\n}): Promise<void> {\n const {\n poll,\n state,\n stateProxy,\n options,\n getOperationStatus,\n getOperationLocation,\n withOperationLocation,\n getPollingInterval,\n processResult,\n updateState,\n setDelay,\n isDone,\n } = inputs;\n const { operationLocation, resourceLocation } = state.config;\n if (operationLocation !== undefined) {\n const { response, status } = await pollOperationHelper({\n poll,\n getOperationStatus,\n state,\n stateProxy,\n operationLocation,\n resourceLocation,\n options,\n });\n if (\n isDone?.(response, state) ||\n (isDone === undefined && [\"succeeded\", \"canceled\"].includes(status))\n ) {\n stateProxy.setResult(\n state,\n buildResult({\n response,\n state,\n processResult,\n })\n );\n } else {\n const intervalInMs = getPollingInterval?.(response);\n if (intervalInMs) setDelay(intervalInMs);\n const location = getOperationLocation?.(response, state);\n if (location !== undefined) {\n const isUpdated = operationLocation !== location;\n state.config.operationLocation = location;\n withOperationLocation?.(location, isUpdated);\n } else withOperationLocation?.(operationLocation, false);\n }\n updateState?.(state, response);\n }\n}\n"]}
@@ -0,0 +1,140 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { AbortController } from "@azure/abort-controller";
4
+ import { deserializeState, initOperation, pollOperation } from "./operation";
5
+ import { POLL_INTERVAL_IN_MS } from "./constants";
6
+ import { delayMs } from "./util/delayMs";
7
+ const createStateProxy = () => ({
8
+ /**
9
+ * The state at this point is created to be of type OperationState<TResult>.
10
+ * It will be updated later to be of type TState when the
11
+ * customer-provided callback, `updateState`, is called during polling.
12
+ */
13
+ initState: (config) => ({ status: "running", config }),
14
+ setCanceled: (state) => (state.status = "canceled"),
15
+ setError: (state, error) => (state.error = error),
16
+ setResult: (state, result) => (state.result = result),
17
+ setRunning: (state) => (state.status = "running"),
18
+ setSucceeded: (state) => (state.status = "succeeded"),
19
+ setFailed: (state) => (state.status = "failed"),
20
+ getError: (state) => state.error,
21
+ getResult: (state) => state.result,
22
+ isCanceled: (state) => state.status === "canceled",
23
+ isFailed: (state) => state.status === "failed",
24
+ isRunning: (state) => state.status === "running",
25
+ isSucceeded: (state) => state.status === "succeeded",
26
+ });
27
+ /**
28
+ * Returns a poller factory.
29
+ */
30
+ export function buildCreatePoller(inputs) {
31
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, getPollingInterval, } = inputs;
32
+ return async ({ init, poll }, options) => {
33
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
34
+ const stateProxy = createStateProxy();
35
+ const withOperationLocation = withOperationLocationCallback
36
+ ? (() => {
37
+ let called = false;
38
+ return (operationLocation, isUpdated) => {
39
+ if (isUpdated)
40
+ withOperationLocationCallback(operationLocation);
41
+ else if (!called)
42
+ withOperationLocationCallback(operationLocation);
43
+ called = true;
44
+ };
45
+ })()
46
+ : undefined;
47
+ const state = restoreFrom
48
+ ? deserializeState(restoreFrom)
49
+ : await initOperation({
50
+ init,
51
+ stateProxy,
52
+ processResult,
53
+ getOperationStatus: getStatusFromInitialResponse,
54
+ withOperationLocation,
55
+ });
56
+ let resultPromise;
57
+ let cancelJob;
58
+ const abortController = new AbortController();
59
+ const handlers = new Map();
60
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
61
+ let currentPollIntervalInMs = intervalInMs;
62
+ const poller = {
63
+ getOperationState: () => state,
64
+ getResult: () => state.result,
65
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
66
+ isStopped: () => resultPromise === undefined,
67
+ stopPolling: () => {
68
+ abortController.abort();
69
+ cancelJob === null || cancelJob === void 0 ? void 0 : cancelJob();
70
+ },
71
+ toString: () => JSON.stringify({
72
+ state,
73
+ }),
74
+ onProgress: (callback) => {
75
+ const s = Symbol();
76
+ handlers.set(s, callback);
77
+ return () => handlers.delete(s);
78
+ },
79
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
80
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
81
+ const { signal: abortSignal } = inputAbortSignal
82
+ ? new AbortController([inputAbortSignal, abortController.signal])
83
+ : abortController;
84
+ if (!poller.isDone()) {
85
+ await poller.poll({ abortSignal });
86
+ while (!poller.isDone()) {
87
+ const delay = delayMs(currentPollIntervalInMs);
88
+ cancelJob = delay.cancel;
89
+ await delay;
90
+ await poller.poll({ abortSignal });
91
+ }
92
+ }
93
+ switch (state.status) {
94
+ case "succeeded": {
95
+ return poller.getResult();
96
+ }
97
+ case "canceled": {
98
+ throw new Error("Operation was canceled");
99
+ }
100
+ case "failed": {
101
+ throw state.error;
102
+ }
103
+ case "notStarted":
104
+ case "running": {
105
+ // Unreachable
106
+ throw new Error(`polling completed without succeeding or failing`);
107
+ }
108
+ }
109
+ })().finally(() => {
110
+ resultPromise = undefined;
111
+ }))),
112
+ async poll(pollOptions) {
113
+ await pollOperation({
114
+ poll,
115
+ state,
116
+ stateProxy,
117
+ getOperationLocation,
118
+ withOperationLocation,
119
+ getPollingInterval,
120
+ getOperationStatus: getStatusFromPollResponse,
121
+ processResult,
122
+ updateState,
123
+ options: pollOptions,
124
+ setDelay: (pollIntervalInMs) => {
125
+ currentPollIntervalInMs = pollIntervalInMs;
126
+ },
127
+ });
128
+ await handleProgressEvents();
129
+ if (state.status === "canceled") {
130
+ throw new Error("Operation was canceled");
131
+ }
132
+ if (state.status === "failed") {
133
+ throw state.error;
134
+ }
135
+ },
136
+ };
137
+ return poller;
138
+ };
139
+ }
140
+ //# sourceMappingURL=poller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"poller.js","sourceRoot":"","sources":["../../../src/poller/poller.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,eAAe,EAAmB,MAAM,yBAAyB,CAAC;AAU3E,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAEzC,MAAM,gBAAgB,GAGlB,GAAG,EAAE,CAAC,CAAC;IACT;;;;OAIG;I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AM,KAAK,UAAU,EAAE;oBAC/B,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;iBAC3C;gBACD,IAAI,KAAK,CAAC,MAAM,KAAK,QAAQ,EAAE;oBAC7B,MAAM,KAAK,CAAC,KAAK,CAAC;iBACnB;YACH,CAAC;SACF,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortController, AbortSignalLike } from \"@azure/abort-controller\";\nimport {\n BuildCreatePollerOptions,\n CreatePollerOptions,\n Operation,\n OperationState,\n RestorableOperationState,\n SimplePollerLike,\n StateProxy,\n} from \"./models\";\nimport { deserializeState, initOperation, pollOperation } from \"./operation\";\nimport { POLL_INTERVAL_IN_MS } from \"./constants\";\nimport { delayMs } from \"./util/delayMs\";\n\nconst createStateProxy: <TResult, TState extends OperationState<TResult>>() => StateProxy<\n TState,\n TResult\n> = () => ({\n /**\n * The state at this point is created to be of type OperationState<TResult>.\n * It will be updated later to be of type TState when the\n * customer-provided callback, `updateState`, is called during polling.\n */\n initState: (config) => ({ status: \"running\", config } as any),\n setCanceled: (state) => (state.status = \"canceled\"),\n setError: (state, error) => (state.error = error),\n setResult: (state, result) => (state.result = result),\n setRunning: (state) => (state.status = \"running\"),\n setSucceeded: (state) => (state.status = \"succeeded\"),\n setFailed: (state) => (state.status = \"failed\"),\n\n getError: (state) => state.error,\n getResult: (state) => state.result,\n isCanceled: (state) => state.status === \"canceled\",\n isFailed: (state) => state.status === \"failed\",\n isRunning: (state) => state.status === \"running\",\n isSucceeded: (state) => state.status === \"succeeded\",\n});\n\n/**\n * Returns a poller factory.\n */\nexport function buildCreatePoller<TResponse, TResult, TState extends OperationState<TResult>>(\n inputs: BuildCreatePollerOptions<TResponse, TState>\n): (\n lro: Operation<TResponse, { abortSignal?: AbortSignalLike }>,\n options?: CreatePollerOptions<TResponse, TResult, TState>\n) => Promise<SimplePollerLike<TState, TResult>> {\n const {\n getOperationLocation,\n getStatusFromInitialResponse,\n getStatusFromPollResponse,\n getPollingInterval,\n } = inputs;\n return async (\n { init, poll }: Operation<TResponse, { abortSignal?: AbortSignalLike }>,\n options?: CreatePollerOptions<TResponse, TResult, TState>\n ) => {\n const {\n processResult,\n updateState,\n withOperationLocation: withOperationLocationCallback,\n intervalInMs = POLL_INTERVAL_IN_MS,\n restoreFrom,\n } = options || {};\n const stateProxy = createStateProxy<TResult, TState>();\n const withOperationLocation = withOperationLocationCallback\n ? (() => {\n let called = false;\n return (operationLocation: string, isUpdated: boolean) => {\n if (isUpdated) withOperationLocationCallback(operationLocation);\n else if (!called) withOperationLocationCallback(operationLocation);\n called = true;\n };\n })()\n : undefined;\n const state: RestorableOperationState<TState> = restoreFrom\n ? deserializeState(restoreFrom)\n : await initOperation({\n init,\n stateProxy,\n processResult,\n getOperationStatus: getStatusFromInitialResponse,\n withOperationLocation,\n });\n let resultPromise: Promise<TResult> | undefined;\n let cancelJob: (() => void) | undefined;\n const abortController = new AbortController();\n // Progress handlers\n type Handler = (state: TState) => void;\n const handlers = new Map<symbol, Handler>();\n const handleProgressEvents = async (): Promise<void> => handlers.forEach((h) => h(state));\n\n let currentPollIntervalInMs = intervalInMs;\n\n const poller: SimplePollerLike<TState, TResult> = {\n getOperationState: () => state,\n getResult: () => state.result,\n isDone: () => [\"succeeded\", \"failed\", \"canceled\"].includes(state.status),\n isStopped: () => resultPromise === undefined,\n stopPolling: () => {\n abortController.abort();\n cancelJob?.();\n },\n toString: () =>\n JSON.stringify({\n state,\n }),\n onProgress: (callback: (state: TState) => void) => {\n const s = Symbol();\n handlers.set(s, callback);\n return () => handlers.delete(s);\n },\n pollUntilDone: (pollOptions?: { abortSignal?: AbortSignalLike }) =>\n (resultPromise ??= (async () => {\n const { abortSignal: inputAbortSignal } = pollOptions || {};\n const { signal: abortSignal } = inputAbortSignal\n ? new AbortController([inputAbortSignal, abortController.signal])\n : abortController;\n if (!poller.isDone()) {\n await poller.poll({ abortSignal });\n while (!poller.isDone()) {\n const delay = delayMs(currentPollIntervalInMs);\n cancelJob = delay.cancel;\n await delay;\n await poller.poll({ abortSignal });\n }\n }\n switch (state.status) {\n case \"succeeded\": {\n return poller.getResult() as TResult;\n }\n case \"canceled\": {\n throw new Error(\"Operation was canceled\");\n }\n case \"failed\": {\n throw state.error;\n }\n case \"notStarted\":\n case \"running\": {\n // Unreachable\n throw new Error(`polling completed without succeeding or failing`);\n }\n }\n })().finally(() => {\n resultPromise = undefined;\n })),\n async poll(pollOptions?: { abortSignal?: AbortSignalLike }): Promise<void> {\n await pollOperation({\n poll,\n state,\n stateProxy,\n getOperationLocation,\n withOperationLocation,\n getPollingInterval,\n getOperationStatus: getStatusFromPollResponse,\n processResult,\n updateState,\n options: pollOptions,\n setDelay: (pollIntervalInMs) => {\n currentPollIntervalInMs = pollIntervalInMs;\n },\n });\n await handleProgressEvents();\n if (state.status === \"canceled\") {\n throw new Error(\"Operation was canceled\");\n }\n if (state.status === \"failed\") {\n throw state.error;\n }\n },\n };\n return poller;\n };\n}\n"]}
@@ -0,0 +1,52 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ /**
4
+ * Map an optional value through a function
5
+ * @internal
6
+ */
7
+ const maybemap = (value, f) => value === undefined ? undefined : f(value);
8
+ const INTERRUPTED = new Error("The poller is already stopped");
9
+ /**
10
+ * A promise that delays resolution until a certain amount of time (in milliseconds) has passed, with facilities for
11
+ * robust cancellation.
12
+ *
13
+ * ### Example:
14
+ *
15
+ * ```javascript
16
+ * let toCancel;
17
+ *
18
+ * // Wait 20 seconds, and optionally allow the function to be cancelled.
19
+ * await delayMs(20000, (cancel) => { toCancel = cancel });
20
+ *
21
+ * // ... if `toCancel` is called before the 20 second timer expires, then the delayMs promise will reject.
22
+ * ```
23
+ *
24
+ * @internal
25
+ * @param ms - the number of milliseconds to wait before resolving
26
+ * @param cb - a callback that can provide the caller with a cancellation function
27
+ */
28
+ export function delayMs(ms) {
29
+ let aborted = false;
30
+ let toReject;
31
+ return Object.assign(new Promise((resolve, reject) => {
32
+ let token;
33
+ toReject = () => {
34
+ maybemap(token, clearTimeout);
35
+ reject(INTERRUPTED);
36
+ };
37
+ // In the rare case that the operation is _already_ aborted, we will reject instantly. This could happen, for
38
+ // example, if the user calls the cancellation function immediately without yielding execution.
39
+ if (aborted) {
40
+ toReject();
41
+ }
42
+ else {
43
+ token = setTimeout(resolve, ms);
44
+ }
45
+ }), {
46
+ cancel: () => {
47
+ aborted = true;
48
+ toReject === null || toReject === void 0 ? void 0 : toReject();
49
+ },
50
+ });
51
+ }
52
+ //# sourceMappingURL=delayMs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delayMs.js","sourceRoot":"","sources":["../../../../src/poller/util/delayMs.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;;GAGG;AACH,MAAM,QAAQ,GAAG,CAAS,KAAqB,EAAE,CAAgB,EAAkB,EAAE,CACnF,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AAI7C,MAAM,WAAW,GAAG,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AAa/D;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,OAAO,CAAC,EAAU;IAChC,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,QAAkC,CAAC;IAEvC,OAAO,MAAM,CAAC,MAAM,CAClB,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpC,IAAI,KAAoC,CAAC;QACzC,QAAQ,GAAG,GAAG,EAAE;YACd,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;YAC9B,MAAM,CAAC,WAAW,CAAC,CAAC;QACtB,CAAC,CAAC;QAEF,6GAA6G;QAC7G,+FAA+F;QAC/F,IAAI,OAAO,EAAE;YACX,QAAQ,EAAE,CAAC;SACZ;aAAM;YACL,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;SACjC;IACH,CAAC,CAAC,EACF;QACE,MAAM,EAAE,GAAG,EAAE;YACX,OAAO,GAAG,IAAI,CAAC;YACf,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,EAAI,CAAC;QACf,CAAC;KACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Map an optional value through a function\n * @internal\n */\nconst maybemap = <T1, T2>(value: T1 | undefined, f: (v: T1) => T2): T2 | undefined =>\n value === undefined ? undefined : f(value);\n\ntype CancellationToken = Parameters<typeof clearTimeout>[0];\n\nconst INTERRUPTED = new Error(\"The poller is already stopped\");\n\n/**\n * A PromiseLike object that supports cancellation.\n * @internal\n */\ninterface CancelablePromiseLike<T> extends PromiseLike<T> {\n /**\n * Cancel the promise (cause it to reject).\n */\n cancel(): void;\n}\n\n/**\n * A promise that delays resolution until a certain amount of time (in milliseconds) has passed, with facilities for\n * robust cancellation.\n *\n * ### Example:\n *\n * ```javascript\n * let toCancel;\n *\n * // Wait 20 seconds, and optionally allow the function to be cancelled.\n * await delayMs(20000, (cancel) => { toCancel = cancel });\n *\n * // ... if `toCancel` is called before the 20 second timer expires, then the delayMs promise will reject.\n * ```\n *\n * @internal\n * @param ms - the number of milliseconds to wait before resolving\n * @param cb - a callback that can provide the caller with a cancellation function\n */\nexport function delayMs(ms: number): CancelablePromiseLike<void> {\n let aborted = false;\n let toReject: (() => void) | undefined;\n\n return Object.assign(\n new Promise<void>((resolve, reject) => {\n let token: CancellationToken | undefined;\n toReject = () => {\n maybemap(token, clearTimeout);\n reject(INTERRUPTED);\n };\n\n // In the rare case that the operation is _already_ aborted, we will reject instantly. This could happen, for\n // example, if the user calls the cancellation function immediately without yielding execution.\n if (aborted) {\n toReject();\n } else {\n token = setTimeout(resolve, ms);\n }\n }),\n {\n cancel: () => {\n aborted = true;\n toReject?.();\n },\n }\n );\n}\n"]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@azure/core-lro",
3
3
  "author": "Microsoft Corporation",
4
4
  "sdk-type": "client",
5
- "version": "2.3.0-beta.1",
5
+ "version": "2.3.0",
6
6
  "description": "Isomorphic client library for supporting long-running operations in node.js and browser.",
7
7
  "tags": [
8
8
  "isomorphic",
@@ -96,18 +96,15 @@
96
96
  "tslib": "^2.2.0"
97
97
  },
98
98
  "devDependencies": {
99
- "@azure/core-http": "^2.0.0",
100
99
  "@azure/core-rest-pipeline": "^1.1.0",
101
100
  "@azure/eslint-plugin-azure-sdk": "^3.0.0",
102
101
  "@azure/dev-tool": "^1.0.0",
103
102
  "@azure/test-utils": "^1.0.0",
104
103
  "@microsoft/api-extractor": "7.18.11",
105
- "@types/chai": "^4.1.6",
106
104
  "@types/mocha": "^7.0.2",
107
105
  "@types/node": "^12.0.0",
108
- "chai": "^4.2.0",
109
106
  "cross-env": "^7.0.2",
110
- "eslint": "^7.15.0",
107
+ "eslint": "^8.0.0",
111
108
  "karma": "^6.2.0",
112
109
  "karma-chrome-launcher": "^3.0.0",
113
110
  "karma-coverage": "^2.0.0",
@@ -121,12 +118,10 @@
121
118
  "karma-sourcemap-loader": "^0.3.8",
122
119
  "mocha": "^7.1.1",
123
120
  "mocha-junit-reporter": "^2.0.0",
124
- "npm-run-all": "^4.1.5",
125
121
  "nyc": "^15.0.0",
126
122
  "prettier": "^2.5.1",
127
123
  "rimraf": "^3.0.0",
128
124
  "ts-node": "^10.0.0",
129
- "typescript": "~4.6.0",
130
- "uglify-js": "^3.4.9"
125
+ "typescript": "~4.6.0"
131
126
  }
132
127
  }