From 14fe6aa75878394244644ebe716f501642e9f849 Mon Sep 17 00:00:00 2001 From: chradek <51000525+chradek@users.noreply.github.com> Date: Fri, 6 Nov 2020 09:56:33 -0800 Subject: [PATCH 01/35] [event-hubs] prepare 5.3.1 release (#12336) * [event-hubs] fix samples compilation * [event-hubs] update changelog release date for 5.3.1 --- sdk/eventhub/event-hubs/CHANGELOG.md | 2 +- sdk/eventhub/event-hubs/package.json | 1 + .../event-hubs/samples/javascript/iothubConnectionString.js | 2 +- sdk/eventhub/event-hubs/samples/javascript/receiveEvents.js | 2 +- .../samples/typescript/src/iothubConnectionString.ts | 4 ++-- .../event-hubs/samples/typescript/src/receiveEvents.ts | 2 +- 6 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sdk/eventhub/event-hubs/CHANGELOG.md b/sdk/eventhub/event-hubs/CHANGELOG.md index 08b581fccea6..59b256066315 100644 --- a/sdk/eventhub/event-hubs/CHANGELOG.md +++ b/sdk/eventhub/event-hubs/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 5.3.1 (Unreleased) +## 5.3.1 (2020-11-09) - Fixes issue [#12278](https://github.com/Azure/azure-sdk-for-js/issues/12278) where the `processEvents` handler could ignore the `maxWaitTimeInSeconds` diff --git a/sdk/eventhub/event-hubs/package.json b/sdk/eventhub/event-hubs/package.json index 46afc25947a6..1eb6219098c5 100644 --- a/sdk/eventhub/event-hubs/package.json +++ b/sdk/eventhub/event-hubs/package.json @@ -134,6 +134,7 @@ "downlevel-dts": "~0.4.0", "eslint": "^6.1.0", "esm": "^3.2.18", + "https-proxy-agent": "^5.0.0", "karma": "^5.1.0", "karma-chrome-launcher": "^3.0.0", "karma-coverage": "^2.0.0", diff --git a/sdk/eventhub/event-hubs/samples/javascript/iothubConnectionString.js b/sdk/eventhub/event-hubs/samples/javascript/iothubConnectionString.js index 1efca4870bf7..75b98d8aec01 100644 --- a/sdk/eventhub/event-hubs/samples/javascript/iothubConnectionString.js +++ b/sdk/eventhub/event-hubs/samples/javascript/iothubConnectionString.js @@ -131,7 +131,7 @@ async function main() { } }, processError: async (err, context) => { - console.log(`Error : ${err}`); + console.log(`Error on partition "${context.partitionId}" : ${err}`); } }, { startPosition: earliestEventPosition } diff --git a/sdk/eventhub/event-hubs/samples/javascript/receiveEvents.js b/sdk/eventhub/event-hubs/samples/javascript/receiveEvents.js index 07a6b0790c45..d6304d70b2f5 100644 --- a/sdk/eventhub/event-hubs/samples/javascript/receiveEvents.js +++ b/sdk/eventhub/event-hubs/samples/javascript/receiveEvents.js @@ -48,7 +48,7 @@ async function main() { } }, processError: async (err, context) => { - console.log(`Error : ${err}`); + console.log(`Error on partition "${context.partitionId}": ${err}`); } }, { startPosition: earliestEventPosition } diff --git a/sdk/eventhub/event-hubs/samples/typescript/src/iothubConnectionString.ts b/sdk/eventhub/event-hubs/samples/typescript/src/iothubConnectionString.ts index edcee16a502c..7bdb0f9d3596 100644 --- a/sdk/eventhub/event-hubs/samples/typescript/src/iothubConnectionString.ts +++ b/sdk/eventhub/event-hubs/samples/typescript/src/iothubConnectionString.ts @@ -131,7 +131,7 @@ async function convertIotHubToEventHubsConnectionString(connectionString: string }); } -async function main() { +export async function main() { console.log(`Running iothubConnectionString sample`); const eventHubsConnectionString = await convertIotHubToEventHubsConnectionString( @@ -151,7 +151,7 @@ async function main() { } }, processError: async (err, context) => { - console.log(`Error : ${err}`); + console.log(`Error on partition "${context.partitionId}" : ${err}`); } }, { startPosition: earliestEventPosition } diff --git a/sdk/eventhub/event-hubs/samples/typescript/src/receiveEvents.ts b/sdk/eventhub/event-hubs/samples/typescript/src/receiveEvents.ts index ee4bfbdd30c4..7359c2013dc9 100644 --- a/sdk/eventhub/event-hubs/samples/typescript/src/receiveEvents.ts +++ b/sdk/eventhub/event-hubs/samples/typescript/src/receiveEvents.ts @@ -49,7 +49,7 @@ export async function main() { } }, processError: async (err, context) => { - console.log(`Error : ${err}`); + console.log(`Error on partition "${context.partitionId}": ${err}`); } }, { startPosition: earliestEventPosition } From b92c535421b2c58c7c3f1b1b91510e79c674dd2d Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Fri, 6 Nov 2020 10:03:17 -0800 Subject: [PATCH 02/35] Make sure we always log in as app or provisioner (#12325) This also adds previously-required parameters back into @PSBoundParameters to pass down to pre- and post-scripts. Co-authored-by: Heath Stewart --- .../TestResources/New-TestResources.ps1 | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/eng/common/TestResources/New-TestResources.ps1 b/eng/common/TestResources/New-TestResources.ps1 index 1fbb27309559..8de70b50dce7 100644 --- a/eng/common/TestResources/New-TestResources.ps1 +++ b/eng/common/TestResources/New-TestResources.ps1 @@ -141,6 +141,9 @@ $UserName = if ($env:USER) { $env:USER } else { "${env:USERNAME}" } if (!$BaseName) { $BaseName = "$UserName$ServiceDirectory" + # Make sure pre- and post-scripts are passed formerly required arguments. + $PSBoundParameters['BaseName'] = $BaseName + Log "BaseName was not set. Using default base name: '$BaseName'" } @@ -167,8 +170,7 @@ if (!$Location) { Write-Verbose "Location was not set. Using default location for environment: '$Location'" } -# If no test application ID is specified during an interactive session, create a new service principal. -if (!$CI -and !$TestApplicationId) { +if (!$CI) { # Make sure the user is logged in to create a service principal. $context = Get-AzContext; @@ -177,13 +179,20 @@ if (!$CI -and !$TestApplicationId) { $context = (Connect-AzAccount -Subscription $defaultSubscription).Context } - Log "TestApplicationId was not specified; creating a new service principal" - $servicePrincipal = New-AzADServicePrincipal -Role Owner + # If no test application ID is specified during an interactive session, create a new service principal. + if (!$TestApplicationId) { + Log "TestApplicationId was not specified; creating a new service principal" + $servicePrincipal = New-AzADServicePrincipal -Role Owner + + $TestApplicationId = $servicePrincipal.ApplicationId + $TestApplicationSecret = (ConvertFrom-SecureString $servicePrincipal.Secret -AsPlainText); - $TestApplicationId = $servicePrincipal.ApplicationId - $TestApplicationSecret = (ConvertFrom-SecureString $servicePrincipal.Secret -AsPlainText); + # Make sure pre- and post-scripts are passed formerly required arguments. + $PSBoundParameters['TestApplicationId'] = $TestApplicationId + $PSBoundParameters['TestApplicationSecret'] = $TestApplicationSecret - Log "Created service principal '$TestApplicationId'" + Log "Created service principal '$TestApplicationId'" + } if (!$ProvisionerApplicationId) { $ProvisionerApplicationId = $TestApplicationId From 9413fb68e1041aaa243be7ae02ca4a3741125b64 Mon Sep 17 00:00:00 2001 From: KarishmaGhiya Date: Fri, 6 Nov 2020 11:27:48 -0800 Subject: [PATCH 03/35] Handle listing of new data feed source types (#12316) Co-authored-by: Jeremy Meng --- .../ai-metrics-advisor/CHANGELOG.md | 1 + .../recording_creates_unknown_data_feed.json | 20 ++++++++ ...d_to_have_an_unknown_data_source_type.json | 20 ++++++++ ...lerts_for_alert_configuration_by_page.json | 38 +++++++-------- .../recording_creates_unknown_data_feed.js | 5 ++ ...ed_to_have_a_different_data_source_type.js | 2 +- ...eed_to_have_an_unknown_data_source_type.js | 5 ++ ..._alerts_for_alert_configuration_by_page.js | 34 ++++++------- .../review/ai-metrics-advisor.api.md | 8 +++- .../samples/javascript/incidentsAndAlerts.js | 12 ++--- .../typescript/src/incidentsAndAlerts.ts | 12 ++--- .../src/metricsAdvisorAdministrationClient.ts | 8 +++- .../ai-metrics-advisor/src/models.ts | 11 ++++- .../ai-metrics-advisor/src/transforms.ts | 8 +++- .../test/advisorclient.spec.ts | 10 ++-- .../ai-metrics-advisor/test/datafeed.spec.ts | 48 ++++++++++++++++++- .../test/transforms.spec.ts | 16 +++++++ 17 files changed, 196 insertions(+), 62 deletions(-) create mode 100644 sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.json create mode 100644 sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.json create mode 100644 sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.js create mode 100644 sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.js diff --git a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md index b75f971d221e..de4806f976ba 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md @@ -46,6 +46,7 @@ - `IngestionStatus.timestamp` - `latestSuccessTimestamp` and `latestActiveTimestamp` in the return type of `getDataFeedIngestionProgress()`. - Parameters of `Date` type now also accept strings. No validation is done for the strings. The SDK calls `new Date()` to convert them to `Date`. +- Handle potential new data feed source types gracefully ## 1.0.0-beta.1 (2020-10-07) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.json b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.json new file mode 100644 index 000000000000..563e3dd8d374 --- /dev/null +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.json @@ -0,0 +1,20 @@ +{ + "recordings": [], + "uniqueTestInfo": { + "uniqueName": { + "js-test-datafeed-": "js-test-datafeed-160462060783902573", + "js-test-appInsightsFeed-": "js-test-appInsightsFeed-160462060783902417", + "js-test-sqlServerFeed-": "js-test-sqlServerFeed-160462060783904133", + "js-test-cosmosFeed-": "js-test-cosmosFeed-160462060783905477", + "js-test-dataExplorerFeed-": "js-test-dataExplorerFeed-160462060783906596", + "js-test-tableFeed-": "js-test-tableFeed-160462060783901974", + "js-test-httpRequestFeed-": "js-test-httpRequestFeed-160462060783906040", + "js-test-influxdbFeed-": "js-test-influxdbFeed-160462060783907937", + "js-test-mongoDbFeed-": "js-test-mongoDbFeed-160462060783904167", + "js-test-mySqlFeed-": "js-test-mySqlFeed-160462060783905821", + "js-test-postgreSqlFeed-": "js-test-postgreSqlFeed-160462060783905792" + }, + "newDate": {} + }, + "hash": "a1d32b3cb29addc69ddee69533b1d9c3" +} \ No newline at end of file diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.json b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.json new file mode 100644 index 000000000000..1f2d94a777a8 --- /dev/null +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.json @@ -0,0 +1,20 @@ +{ + "recordings": [], + "uniqueTestInfo": { + "uniqueName": { + "js-test-datafeed-": "js-test-datafeed-160462633023508955", + "js-test-appInsightsFeed-": "js-test-appInsightsFeed-160462633023506053", + "js-test-sqlServerFeed-": "js-test-sqlServerFeed-160462633023501659", + "js-test-cosmosFeed-": "js-test-cosmosFeed-160462633023507940", + "js-test-dataExplorerFeed-": "js-test-dataExplorerFeed-160462633023505691", + "js-test-tableFeed-": "js-test-tableFeed-160462633023501610", + "js-test-httpRequestFeed-": "js-test-httpRequestFeed-160462633023500719", + "js-test-influxdbFeed-": "js-test-influxdbFeed-160462633023509804", + "js-test-mongoDbFeed-": "js-test-mongoDbFeed-160462633023501586", + "js-test-mySqlFeed-": "js-test-mySqlFeed-160462633023504987", + "js-test-postgreSqlFeed-": "js-test-postgreSqlFeed-160462633023508181" + }, + "newDate": {} + }, + "hash": "2a2fb7f260a4a275c35cd9a7ef9ea88d" +} \ No newline at end of file diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.json b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.json index f3305e7c77c3..4c4f11958bf4 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.json +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/browsers/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.json @@ -4,41 +4,41 @@ "method": "POST", "url": "https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query", "query": { - "$top": "2" + "$top": "1" }, - "requestBody": "{\"startTime\":\"2020-01-01T00:00:00.000Z\",\"endTime\":\"2020-09-12T00:00:00.000Z\",\"timeMode\":\"AnomalyTime\"}", + "requestBody": "{\"startTime\":\"2020-11-01T00:00:00.000Z\",\"endTime\":\"2020-11-05T00:00:00.000Z\",\"timeMode\":\"AnomalyTime\"}", "status": 200, - "response": "{\"value\":[{\"alertId\":\"1747a763000\",\"timestamp\":\"2020-09-11T00:00:00Z\",\"createdTime\":\"2020-09-14T12:31:04.148Z\",\"modifiedTime\":\"2020-09-17T17:26:31.464Z\"},{\"alertId\":\"174754fd400\",\"timestamp\":\"2020-09-10T00:00:00Z\",\"createdTime\":\"2020-09-14T12:31:04.002Z\",\"modifiedTime\":\"2020-09-16T21:08:42.991Z\"}],\"@nextLink\":\"https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=2&$skip=2\"}", + "response": "{\"value\":[{\"alertId\":\"175908d9800\",\"timestamp\":\"2020-11-04T00:00:00Z\",\"createdTime\":\"2020-11-05T00:56:55.458Z\",\"modifiedTime\":\"2020-11-06T00:07:25.627Z\"}],\"@nextLink\":\"https://endpoint:443/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=1&$skip=1\"}", "responseHeaders": { - "apim-request-id": "72de8aa5-a002-4ca5-b896-6fa938112c3e", - "content-length": "489", + "apim-request-id": "51c5f0f5-796d-4b62-8b26-579f31e7f2ea", + "content-length": "342", "content-type": "application/json; charset=utf-8", - "date": "Mon, 21 Sep 2020 19:33:06 GMT", + "date": "Fri, 06 Nov 2020 18:57:39 GMT", "strict-transport-security": "max-age=31536000; includeSubDomains; preload", "x-content-type-options": "nosniff", - "x-envoy-upstream-service-time": "179", - "x-request-id": "72de8aa5-a002-4ca5-b896-6fa938112c3e" + "x-envoy-upstream-service-time": "222", + "x-request-id": "51c5f0f5-796d-4b62-8b26-579f31e7f2ea" } }, { "method": "POST", - "url": "https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query", + "url": "https://endpoint:443/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query", "query": { - "$top": "2", - "$skip": "2" + "$top": "1", + "$skip": "1" }, - "requestBody": "{\"startTime\":\"2020-01-01T00:00:00.000Z\",\"endTime\":\"2020-09-12T00:00:00.000Z\",\"timeMode\":\"AnomalyTime\"}", + "requestBody": "{\"startTime\":\"2020-11-01T00:00:00.000Z\",\"endTime\":\"2020-11-05T00:00:00.000Z\",\"timeMode\":\"AnomalyTime\"}", "status": 200, - "response": "{\"value\":[{\"alertId\":\"17470297800\",\"timestamp\":\"2020-09-09T00:00:00Z\",\"createdTime\":\"2020-09-12T01:15:16.575Z\",\"modifiedTime\":\"2020-09-14T20:43:36.527Z\"},{\"alertId\":\"1746b031c00\",\"timestamp\":\"2020-09-08T00:00:00Z\",\"createdTime\":\"2020-09-12T01:15:16.406Z\",\"modifiedTime\":\"2020-09-14T20:42:57.048Z\"}],\"@nextLink\":\"https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=2&$skip=4\"}", + "response": "{\"value\":[{\"alertId\":\"1758b673c00\",\"timestamp\":\"2020-11-03T00:00:00Z\",\"createdTime\":\"2020-11-04T00:06:13.262Z\",\"modifiedTime\":\"2020-11-06T00:07:25.348Z\"}],\"@nextLink\":\"https://endpoint:443/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=1&$skip=2\"}", "responseHeaders": { - "apim-request-id": "aa464793-a62c-4c8f-9fcb-a9669e5896e9", - "content-length": "489", + "apim-request-id": "c26219d8-beaa-45fc-9455-7539db925673", + "content-length": "342", "content-type": "application/json; charset=utf-8", - "date": "Mon, 21 Sep 2020 19:33:06 GMT", + "date": "Fri, 06 Nov 2020 18:57:39 GMT", "strict-transport-security": "max-age=31536000; includeSubDomains; preload", "x-content-type-options": "nosniff", - "x-envoy-upstream-service-time": "138", - "x-request-id": "aa464793-a62c-4c8f-9fcb-a9669e5896e9" + "x-envoy-upstream-service-time": "132", + "x-request-id": "c26219d8-beaa-45fc-9455-7539db925673" } } ], @@ -46,5 +46,5 @@ "uniqueName": {}, "newDate": {} }, - "hash": "87dd6ecc9229da03e7c2d77e9d03e3ec" + "hash": "64689509eeb6ad817ac4406e74ff5544" } \ No newline at end of file diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.js b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.js new file mode 100644 index 000000000000..80167563725a --- /dev/null +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_creates_unknown_data_feed.js @@ -0,0 +1,5 @@ +let nock = require('nock'); + +module.exports.hash = "b2f0887c6a85310b4e414e246d1600ca"; + +module.exports.testInfo = {"uniqueName":{"js-test-datafeed-":"js-test-datafeed-160461303045407429","js-test-appInsightsFeed-":"js-test-appInsightsFeed-160461303045408090","js-test-sqlServerFeed-":"js-test-sqlServerFeed-160461303045406730","js-test-cosmosFeed-":"js-test-cosmosFeed-160461303045404287","js-test-dataExplorerFeed-":"js-test-dataExplorerFeed-160461303045409902","js-test-tableFeed-":"js-test-tableFeed-160461303045404859","js-test-httpRequestFeed-":"js-test-httpRequestFeed-160461303045405666","js-test-influxdbFeed-":"js-test-influxdbFeed-160461303045409935","js-test-mongoDbFeed-":"js-test-mongoDbFeed-160461303045405356","js-test-mySqlFeed-":"js-test-mySqlFeed-160461303045400432","js-test-postgreSqlFeed-":"js-test-postgreSqlFeed-160461303045403296"},"newDate":{}} diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_a_different_data_source_type.js b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_a_different_data_source_type.js index 518791ac1fed..a90986cdc66c 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_a_different_data_source_type.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_a_different_data_source_type.js @@ -46,4 +46,4 @@ nock('https://endpoint:443', {"encodedQueryParams":true}) 'Tue, 20 Oct 2020 22:50:52 GMT', 'Connection', 'close' -]); +]); \ No newline at end of file diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.js b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.js new file mode 100644 index 000000000000..421368a99e45 --- /dev/null +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisoradministrationclient_datafeed_datafeed/recording_updates_data_feed_to_have_an_unknown_data_source_type.js @@ -0,0 +1,5 @@ +let nock = require('nock'); + +module.exports.hash = "ab0a998856c118deb560aa4e36c8a9d9"; + +module.exports.testInfo = {"uniqueName":{"js-test-datafeed-":"js-test-datafeed-160462632131002247","js-test-appInsightsFeed-":"js-test-appInsightsFeed-160462632131009886","js-test-sqlServerFeed-":"js-test-sqlServerFeed-160462632131000186","js-test-cosmosFeed-":"js-test-cosmosFeed-160462632131000621","js-test-dataExplorerFeed-":"js-test-dataExplorerFeed-160462632131001168","js-test-tableFeed-":"js-test-tableFeed-160462632131001883","js-test-httpRequestFeed-":"js-test-httpRequestFeed-160462632131006381","js-test-influxdbFeed-":"js-test-influxdbFeed-160462632131000853","js-test-mongoDbFeed-":"js-test-mongoDbFeed-160462632131004079","js-test-mySqlFeed-":"js-test-mySqlFeed-160462632131008480","js-test-postgreSqlFeed-":"js-test-postgreSqlFeed-160462632131002478"},"newDate":{}} diff --git a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.js b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.js index f22a821a3361..3a5a4634773b 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/recordings/node/metricsadvisorclient/recording_lists_alerts_for_alert_configuration_by_page.js @@ -1,53 +1,49 @@ let nock = require('nock'); -module.exports.hash = "4070e9dac179e413d525f140069a4db5"; +module.exports.hash = "0474e9571ef05dc822a7d4755dcc73bf"; module.exports.testInfo = {"uniqueName":{},"newDate":{}} nock('https://endpoint:443', {"encodedQueryParams":true}) - .post('/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query', {"startTime":"2020-01-01T00:00:00.000Z","endTime":"2020-09-12T00:00:00.000Z","timeMode":"AnomalyTime"}) + .post('/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query', {"startTime":"2020-11-01T00:00:00.000Z","endTime":"2020-11-05T00:00:00.000Z","timeMode":"AnomalyTime"}) .query(true) - .reply(200, {"value":[{"alertId":"1747a763000","timestamp":"2020-09-11T00:00:00Z","createdTime":"2020-09-14T12:31:04.148Z","modifiedTime":"2020-09-17T17:26:31.464Z"},{"alertId":"174754fd400","timestamp":"2020-09-10T00:00:00Z","createdTime":"2020-09-14T12:31:04.002Z","modifiedTime":"2020-09-16T21:08:42.991Z"}],"@nextLink":"https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=2&$skip=2"}, [ + .reply(200, {"value":[{"alertId":"175908d9800","timestamp":"2020-11-04T00:00:00Z","createdTime":"2020-11-05T00:56:55.458Z","modifiedTime":"2020-11-06T00:07:25.627Z"}],"@nextLink":"https://endpoint:443/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=1&$skip=1"}, [ 'Content-Length', - '489', + '342', 'Content-Type', 'application/json; charset=utf-8', 'x-request-id', - '183384d4-ec75-447a-86bb-15a93ad9dedc', + 'be3800c5-1928-4ac7-bc5f-8fef030a2d9e', 'x-envoy-upstream-service-time', - '301', + '5232', 'apim-request-id', - '183384d4-ec75-447a-86bb-15a93ad9dedc', + 'be3800c5-1928-4ac7-bc5f-8fef030a2d9e', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload', 'x-content-type-options', 'nosniff', 'Date', - 'Mon, 21 Sep 2020 19:31:44 GMT', - 'Connection', - 'close' + 'Fri, 06 Nov 2020 18:57:29 GMT' ]); nock('https://endpoint:443', {"encodedQueryParams":true}) - .post('/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query', {"startTime":"2020-01-01T00:00:00.000Z","endTime":"2020-09-12T00:00:00.000Z","timeMode":"AnomalyTime"}) + .post('/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query', {"startTime":"2020-11-01T00:00:00.000Z","endTime":"2020-11-05T00:00:00.000Z","timeMode":"AnomalyTime"}) .query(true) - .reply(200, {"value":[{"alertId":"17470297800","timestamp":"2020-09-09T00:00:00Z","createdTime":"2020-09-12T01:15:16.575Z","modifiedTime":"2020-09-14T20:43:36.527Z"},{"alertId":"1746b031c00","timestamp":"2020-09-08T00:00:00Z","createdTime":"2020-09-12T01:15:16.406Z","modifiedTime":"2020-09-14T20:42:57.048Z"}],"@nextLink":"https://endpoint/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=2&$skip=4"}, [ + .reply(200, {"value":[{"alertId":"1758b673c00","timestamp":"2020-11-03T00:00:00Z","createdTime":"2020-11-04T00:06:13.262Z","modifiedTime":"2020-11-06T00:07:25.348Z"}],"@nextLink":"https://endpoint:443/metricsadvisor/v1.0/alert/anomaly/configurations/7edf304f-6487-4e3d-a137-cc4f679bcbc0/alerts/query?$top=1&$skip=2"}, [ 'Content-Length', - '489', + '342', 'Content-Type', 'application/json; charset=utf-8', 'x-request-id', - 'b2a75b5f-a3bf-44de-ba02-427f23fb5fdf', + '3f1e7c12-600f-454d-b294-f411852b579b', 'x-envoy-upstream-service-time', - '148', + '1089', 'apim-request-id', - 'b2a75b5f-a3bf-44de-ba02-427f23fb5fdf', + '3f1e7c12-600f-454d-b294-f411852b579b', 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload', 'x-content-type-options', 'nosniff', 'Date', - 'Mon, 21 Sep 2020 19:31:52 GMT', - 'Connection', - 'close' + 'Fri, 06 Nov 2020 18:57:30 GMT' ]); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md index e3b31016f665..3d510c5568ab 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md @@ -310,7 +310,7 @@ export interface DataFeedSchema { } // @public -export type DataFeedSource = AzureApplicationInsightsDataFeedSource | AzureBlobDataFeedSource | AzureCosmosDBDataFeedSource | AzureDataExplorerDataFeedSource | AzureDataLakeStorageGen2DataFeedSource | AzureTableDataFeedSource | ElasticsearchDataFeedSource | HttpRequestDataFeedSource | InfluxDBDataFeedSource | MySqlDataFeedSource | PostgreSqlDataFeedSource | SQLServerDataFeedSource | MongoDBDataFeedSource; +export type DataFeedSource = AzureApplicationInsightsDataFeedSource | AzureBlobDataFeedSource | AzureCosmosDBDataFeedSource | AzureDataExplorerDataFeedSource | AzureDataLakeStorageGen2DataFeedSource | AzureTableDataFeedSource | ElasticsearchDataFeedSource | HttpRequestDataFeedSource | InfluxDBDataFeedSource | MySqlDataFeedSource | PostgreSqlDataFeedSource | SQLServerDataFeedSource | MongoDBDataFeedSource | UnknownDataFeedSource; // @public export type DataFeedSourcePatch = Omit & { @@ -994,6 +994,12 @@ export interface TopNGroupScope { top: number; } +// @public +export type UnknownDataFeedSource = { + dataSourceType: "Unknown"; + dataSourceParameter: unknown; +}; + // @public (undocumented) export interface WebhookHookParameter { certificateKey?: string; diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js index 79bbd3c40519..12da204b8f09 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js @@ -124,10 +124,10 @@ async function getRootCauses(client, detectionConfigId, incidentId) { async function listAlerts(client, alertConfigId) { console.log(`Listing alerts for alert configuration '${alertConfigId}'`); console.log(" using for-await-of syntax"); - for await (const alert of client.listAlertsForAlertConfiguration( + for await (const alert of client.listAlerts( alertConfigId, - new Date("10/22/2020"), - new Date("10/24/2020"), + new Date("11/01/2020"), + new Date("11/05/2020"), "AnomalyTime" )) { console.log(" Alert"); @@ -138,10 +138,10 @@ async function listAlerts(client, alertConfigId) { console.log(` by pages`); const iterator = client - .listAlertsForAlertConfiguration( + .listAlerts( alertConfigId, - new Date("10/22/2020"), - new Date("10/24/2020"), + new Date("11/01/2020"), + new Date("11/05/2020"), "AnomalyTime" ) .byPage({ maxPageSize: 20 }); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts index 3f40799c9a45..ef08817c3d55 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts @@ -136,10 +136,10 @@ async function getRootCauses( async function listAlerts(client: MetricsAdvisorClient, alertConfigId: string) { console.log(`Listing alerts for alert configuration '${alertConfigId}'`); console.log(" using for-await-of syntax"); - for await (const alert of client.listAlertsForAlertConfiguration( + for await (const alert of client.listAlerts( alertConfigId, - new Date("10/22/2020"), - new Date("10/24/2020"), + new Date("11/01/2020"), + new Date("11/05/2020"), "AnomalyTime" )) { console.log(" Alert"); @@ -150,10 +150,10 @@ async function listAlerts(client: MetricsAdvisorClient, alertConfigId: string) { console.log(` by pages`); const iterator = client - .listAlertsForAlertConfiguration( + .listAlerts( alertConfigId, - new Date("10/22/2020"), - new Date("10/24/2020"), + new Date("11/01/2020"), + new Date("11/05/2020"), "AnomalyTime" ) .byPage({ maxPageSize: 20 }); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts index db901bbdfcda..02b7be316281 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts @@ -188,7 +188,9 @@ export class MetricsAdvisorAdministrationClient { operationOptions ); const { name, granularity, source, schema, ingestionSettings, options } = feed; - + if (source.dataSourceType === "Unknown") { + throw new Error("Cannot create a data feed with the Unknown source type."); + } const needRollup: NeedRollupEnum | undefined = options?.rollupSettings?.rollupType === "AutoRollup" ? "NeedRollup" @@ -454,7 +456,9 @@ export class MetricsAdvisorAdministrationClient { "MetricsAdvisorAdministrationClient-updateDataFeed", options ); - + if (patch.source.dataSourceType === "Unknown") { + throw new Error("Cannot update a data feed to have the Unknown source type."); + } try { const requestOptions = operationOptionsToRequestOptionsBase(finalOptions); const patchBody = { diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts index 8a2ee5879e32..eeb8e4987e37 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts @@ -401,6 +401,14 @@ export type MongoDBDataFeedSource = { dataSourceParameter: MongoDBParameter; }; +/** + * Represents an Unknown data source. + */ +export type UnknownDataFeedSource = { + dataSourceType: "Unknown"; + dataSourceParameter: unknown; +}; + /** * Represents a SQL Server data source. */ @@ -425,7 +433,8 @@ export type DataFeedSource = | MySqlDataFeedSource | PostgreSqlDataFeedSource | SQLServerDataFeedSource - | MongoDBDataFeedSource; + | MongoDBDataFeedSource + | UnknownDataFeedSource; /** * Represents the input type to the Update Data Feed operation. diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts index 8ad7a990e1da..5c909d7cf523 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts @@ -517,7 +517,13 @@ export function fromServiceDataFeedDetailUnion(original: ServiceDataFeedDetailUn return result13; } default: - throw new Error(`Unrecognized datasource type ${original.dataSourceType}`); + return { + ...common, + source: { + dataSourceType: "Unknown", + dataSourceParameter: (original as any).dataSourceParameter + } + }; } } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/advisorclient.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/advisorclient.spec.ts index b75f22006f60..9e9ad1062429 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/advisorclient.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/advisorclient.spec.ts @@ -211,15 +211,15 @@ describe("MetricsAdvisorClient", () => { const iterator = client .listAlerts( testEnv.METRICS_ADVISOR_ALERT_CONFIG_ID, - new Date(Date.UTC(2020, 0, 1)), - new Date(Date.UTC(2020, 8, 12)), + new Date(Date.UTC(2020, 10, 1)), + new Date(Date.UTC(2020, 10, 5)), "AnomalyTime" ) - .byPage({ maxPageSize: 2 }); + .byPage({ maxPageSize: 1 }); let result = await iterator.next(); - assert.equal(result.value.length, 2, "Expecting two alerts in first page"); + assert.equal(result.value.length, 1, "Expecting one alert in first page"); result = await iterator.next(); - assert.equal(result.value.length, 2, "Expecting two alerts in second page"); + assert.equal(result.value.length, 1, "Expecting one alert in second page"); }); it("lists anomalies for alert", async function() { diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts index 5cea3156872d..3723a4cd5156 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts @@ -16,7 +16,8 @@ import { DataFeedDimension, DataFeedMetric, MetricsAdvisorAdministrationClient, - MetricsAdvisorKeyCredential + MetricsAdvisorKeyCredential, + UnknownDataFeedSource } from "../src"; import { createRecordedAdminClient, testEnv } from "./util/recordedClients"; import { Recorder } from "@azure/test-utils-recorder"; @@ -761,6 +762,51 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { it("deletes PostgreSQL data feed", async function() { await verifyDataFeedDeletion(client, createdPostGreSqlId); }); + + it("creates Unknown data feed", async () => { + const expectedSource : UnknownDataFeedSource = { + dataSourceType: "Unknown", + dataSourceParameter: { + connectionString: "https://connect-to-postgresql", + query: "{ find: postgresql,filter: { Time: @StartTime },batch: 200 }" + } + }; + try{ + await client.createDataFeed({ + name: postgreSqlFeedName, + source: expectedSource, + granularity, + schema: dataFeedSchema, + ingestionSettings: dataFeedIngestion, + options + }); + assert.fail("Test should throw error"); + } + catch(error){ + assert.equal((error as any).message, "Cannot create a data feed with the Unknown source type."); + } + }); + + it("updates data feed to have an unknown data source type", async function() { + const patch: DataFeedPatch = { + source: { + dataSourceType: "Unknown", + dataSourceParameter: { + connectionString: "https://connect-to-mongodb-patch", + database: "data-feed-mongodb-patch", + command: "{ find: mongodb,filter: { Time: @StartTime },batch: 200 }" + } + } + }; + try{ + await client.updateDataFeed(createdPostGreSqlId, patch); + assert.fail("Test should throw error"); + } + catch(error){ + assert.equal((error as any).message, "Cannot update a data feed to have the Unknown source type."); + } + }); + }); }).timeout(60000); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts index 2aba752d0a00..395c78a0999e 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts @@ -183,6 +183,22 @@ describe("Transforms", () => { assert.strictEqual(actual.source.dataSourceType, serviceDataFeed.dataSourceType); }); + it("fromServiceDataFeedDetailUnion() for future data source types", () => { + const serviceDataFeed: ServiceDataFeedDetailUnion = { + dataSourceType: "Future Source" as any, + dataSourceParameter: {futureConnectionString: "xyz", futureQuery: "someQuery"} as any, + dataFeedName: "name", + metrics: [{ name: "m1", id: "m-id1", displayName: "m1 display" }], + dimension: [{ name: "d1", displayName: "d1 display" }], + granularityName: "Daily", + dataStartFrom: new Date(Date.UTC(2020, 9, 1)) + }; + + const actual = fromServiceDataFeedDetailUnion(serviceDataFeed); + assert.strictEqual(actual.source.dataSourceType, "Unknown"); + assert.deepStrictEqual(actual.source.dataSourceParameter, serviceDataFeed.dataSourceParameter); + }); + [ { original: "Yearly", expected: "Yearly" }, { original: "Daily", expected: "Daily" }, From cbd04b0a7ff7bbed56c9b50696b68c2c53a5d66e Mon Sep 17 00:00:00 2001 From: KarishmaGhiya Date: Fri, 6 Nov 2020 12:27:58 -0800 Subject: [PATCH 04/35] remove queries out of for-loop to an iterator variable (#12338) --- .../ai-metrics-advisor/README.md | 18 +++++---------- .../samples/javascript/alertingConfig.js | 3 ++- .../samples/javascript/dataFeed.js | 3 ++- .../samples/javascript/detectionConfig.js | 3 ++- .../samples/javascript/incidentsAndAlerts.js | 21 ++++++++++------- .../samples/javascript/ingestionStatus.js | 7 ++---- .../samples/javascript/metricFeedback.js | 5 ++-- .../samples/javascript/metricQueries.js | 14 +++++------ .../samples/javascript/quickstart.js | 13 +++++------ .../samples/typescript/src/alertingConfig.ts | 3 ++- .../samples/typescript/src/dataFeed.ts | 3 ++- .../samples/typescript/src/detectionConfig.ts | 3 ++- .../typescript/src/incidentsAndAlerts.ts | 23 +++++++++++-------- .../samples/typescript/src/ingestionStatus.ts | 7 ++---- .../samples/typescript/src/metricFeedback.ts | 5 ++-- .../samples/typescript/src/metricQueries.ts | 14 +++++------ .../samples/typescript/src/quickstart.ts | 13 +++++------ 17 files changed, 81 insertions(+), 77 deletions(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/README.md b/sdk/metricsadvisor/ai-metrics-advisor/README.md index db5bfd7d4651..d4e62ab9ac7b 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/README.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/README.md @@ -246,11 +246,8 @@ async function main() { async function checkIngestionStatus(adminClient, datafeedId, startTime, endTime) { // This shows how to use for-await-of syntax to list status console.log("Checking ingestion status..."); - for await (const status of adminClient.listDataFeedIngestionStatus( - datafeedId, - startTime, - endTime - )) { + const iterator = adminClient.listDataFeedIngestionStatus(datafeedId, startTime, endTime); + for await (const status of iterator) { console.log(` [${status.timestamp}] ${status.status} - ${status.message}`); } } @@ -429,12 +426,8 @@ async function main() { async function queryAlerts(client, alertConfigId, startTime, endTime) { let alerts = []; - for await (const alert of client.listAlerts( - alertConfigId, - startTime, - endTime, - "AnomalyTime" - )) { + const iterator = client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime"); + for await (const alert of iterator) { alerts.push(alert); } @@ -445,7 +438,8 @@ async function queryAnomaliesByAlert(client, alert) { console.log( `Listing anomalies for alert configuration '${alert.alertConfigId}' and alert '${alert.id}'` ); - for await (const anomaly of client.listAnomalies(alert)) { + const iterator = client.listAnomalies(alert); + for await (const anomaly of iterator) { console.log( ` Anomaly ${anomaly.severity} ${anomaly.status} ${anomaly.seriesKey.dimension} ${anomaly.timestamp}` ); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/alertingConfig.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/alertingConfig.js index b142a8378115..ac982b9902e0 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/alertingConfig.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/alertingConfig.js @@ -108,7 +108,8 @@ async function deleteAlertConfig(adminClient, alertConfigId) { async function listAlertingConfig(adminClient, detectdionConfigId) { console.log(`Listing alerting configurations for detection configuration ${detectdionConfigId}`); let i = 1; - for await (const config of adminClient.listAlertConfigs(detectdionConfigId)) { + const iterator = adminClient.listAlertConfigs(detectdionConfigId); + for await (const config of iterator) { console.log(`Alert configuration ${i++}`); console.log(config); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js index 0764b1fe5342..901721dd4acd 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js @@ -43,7 +43,8 @@ async function listDataFeeds(client) { // second approach console.log(" using for-await-of loop"); - for await (const datatFeed of client.listDataFeeds()) { + const iterator = client.listDataFeeds(); + for await (const datatFeed of iterator) { console.log(`id :${datatFeed.id}, name: ${datatFeed.name}`); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/detectionConfig.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/detectionConfig.js index 5ad6abc58aa8..78fed8367aac 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/detectionConfig.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/detectionConfig.js @@ -173,7 +173,8 @@ async function deleteDetectionConfig(adminClient, detectionConfigId) { async function listDetectionConfig(adminClient, metricId) { console.log(`Listing detection configurations for metric '${metricId}'...`); let i = 1; - for await (const config of adminClient.listDetectionConfigs(metricId)) { + const iterator = adminClient.listDetectionConfigs(metricId); + for await (const config of iterator) { console.log(` detection configuration ${i++}`); console.log(config); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js index 12da204b8f09..fb482a093dbc 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js @@ -35,14 +35,15 @@ async function main() { async function listIncidentsForDetectionConfig(client, detectionConfigId) { console.log(`Listing incidents for detection config '${detectionConfigId}'`); console.log(" using for-await-of syntax"); - for await (const incident of client.listIncidents( + const listIterator = client.listIncidents( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { dimensionFilter: [{ city: "Manila", category: "Shoes Handbags & Sunglasses" }] } - )) { + ); + for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); @@ -77,14 +78,15 @@ async function listIncidentsForDetectionConfig(client, detectionConfigId) { async function listAnomaliesForDetectionConfig(client, detectionConfigId) { console.log(`Listing anomalies for detection config '${detectionConfigId}'`); console.log(" using for-await-of syntax"); - for await (const anomaly of client.listAnomalies( + const listIterator = client.listAnomalies( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { severityFilter: { min: "Medium", max: "High" } } - )) { + ); + for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` metric id: ${anomaly.metricId}`); console.log(` detection config id: ${anomaly.detectionConfigurationId}`); @@ -124,12 +126,13 @@ async function getRootCauses(client, detectionConfigId, incidentId) { async function listAlerts(client, alertConfigId) { console.log(`Listing alerts for alert configuration '${alertConfigId}'`); console.log(" using for-await-of syntax"); - for await (const alert of client.listAlerts( + const listIterator = client.listAlerts( alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime" - )) { + ); + for await (const alert of listIterator) { console.log(" Alert"); console.log(` id: ${alert.id}`); console.log(` timestamp: ${alert.timestamp}`); @@ -159,7 +162,8 @@ async function listIncidentsForAlert(client, alertConfigId, alertId) { `Listing incidents for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); - for await (const incident of client.listIncidents({ alertConfigId, id: alertId })) { + const listIterator = client.listIncidents({ alertConfigId, id: alertId }); + for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); @@ -194,7 +198,8 @@ async function listAnomaliesForAlert(client, alertConfigId, alertId) { `Listing anomalies for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); - for await (const anomaly of client.listAnomalies({ alertConfigId, id: alertId })) { + const listIterator = client.listAnomalies({ alertConfigId, id: alertId }); + for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` metric id: ${anomaly.metricId}`); console.log(` detection config id: ${anomaly.detectionConfigurationId}`); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/ingestionStatus.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/ingestionStatus.js index 0a8377fb59db..474b4da2174f 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/ingestionStatus.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/ingestionStatus.js @@ -36,11 +36,8 @@ async function main() { async function listIngestionStatus(adminClient, dataFeedId, startTime, endTime) { console.log("Listing ingestion status..."); // iterate through all ingestions using for-await-of - for await (const ingestion of adminClient.listDataFeedIngestionStatus( - dataFeedId, - startTime, - endTime - )) { + const listIterator = adminClient.listDataFeedIngestionStatus(dataFeedId, startTime, endTime); + for await (const ingestion of listIterator) { console.log(` ${ingestion.timestamp} ${ingestion.status} ${ingestion.message}`); } // listing by pages diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricFeedback.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricFeedback.js index cfad4a5c2bca..c7dac6c672cb 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricFeedback.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricFeedback.js @@ -85,13 +85,14 @@ async function getFeedback(client, feedbackId) { async function listFeedback(client, metricId, startTime, endTime) { console.log("Listing feedbacks..."); console.log(" using for-await-of syntax"); - for await (const feedback of client.listFeedback(metricId, { + const listIterator = client.listFeedback(metricId, { filter: { startTime: new Date("08/01/2020"), endTime: new Date("08/03/2020"), timeMode: "MetricTimestamp" } - })) { + }); + for await (const feedback of listIterator) { console.log(` ${feedback.feedbackType} feedback ${feedback.id}`); console.log(` created time: ${feedback.createdTime}`); console.log(` metric id: ${feedback.metricId}`); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricQueries.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricQueries.js index 1f320694d9fe..2da040ec5179 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricQueries.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/metricQueries.js @@ -28,10 +28,8 @@ async function main() { async function listMetricSeriesDefinitions(client, metricId) { console.log("Listing metric series definitions..."); console.log(" with for-await-of loop"); - for await (const definition of client.listMetricSeriesDefinitions( - metricId, - new Date("08/05/2020") - )) { + const listIterator = client.listMetricSeriesDefinitions(metricId, new Date("08/05/2020")); + for await (const definition of listIterator) { console.log(definition); } @@ -58,11 +56,12 @@ async function listMetricSeriesDefinitions(client, metricId) { async function listEnrichmentStatus(client, metricId) { console.log("Listing metric enrichment status..."); - for await (const status of client.listMetricEnrichmentStatus( + const listIterator = client.listMetricEnrichmentStatus( metricId, new Date("10/22/2020"), new Date("10/24/2020") - )) { + ); + for await (const status of listIterator) { console.log(" Enrichment status"); console.log(status.timestamp); console.log(status.status); @@ -72,7 +71,8 @@ async function listEnrichmentStatus(client, metricId) { async function listMetricDimensionValues(client, metricId) { console.log("Listing metric dimension values..."); - for await (const dv of client.listMetricDimensionValues(metricId, "city")) { + const listIterator = client.listMetricDimensionValues(metricId, "city"); + for await (const dv of listIterator) { console.log(` ${dv}`); } } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js index 92f9d574ae1d..de0eee9bec19 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js @@ -136,11 +136,8 @@ async function createDataFeed(adminClient, sqlServerConnectionString, sqlServerQ async function checkIngestionStatus(adminClient, datafeedId, startTime, endTime) { // This shows how to use for-await-of syntax to list status console.log("Checking ingestion status..."); - for await (const status of adminClient.listDataFeedIngestionStatus( - datafeedId, - startTime, - endTime - )) { + const listIterator = adminClient.listDataFeedIngestionStatus(datafeedId, startTime, endTime); + for await (const status of listIterator) { console.log(` [${status.timestamp}] ${status.status} - ${status.message}`); } } @@ -218,7 +215,8 @@ async function queryAlerts(client, alertConfigId, startTime, endTime) { // This shows how to use `for-await-of` syntax to list alerts console.log(" using for-await-of syntax"); let alerts = []; - for await (const alert of client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime")) { + const listIterator = client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime"); + for await (const alert of listIterator) { alerts.push(alert); console.log(" Alert"); console.log(` id: ${alert.id}`); @@ -245,7 +243,8 @@ async function queryAnomaliesByAlert(client, alert) { console.log( `Listing anomalies for alert configuration '${alert.alertConfigId}' and alert '${alert.id}'` ); - for await (const anomaly of client.listAnomalies(alert)) { + const listIterator = client.listAnomalies(alert); + for await (const anomaly of listIterator) { console.log( ` Anomaly ${anomaly.severity} ${anomaly.status} ${anomaly.seriesKey.dimension} ${anomaly.timestamp}` ); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/alertingConfig.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/alertingConfig.ts index a18b32d5f4c4..1b101c9ec6b5 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/alertingConfig.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/alertingConfig.ts @@ -126,7 +126,8 @@ async function listAlertConfig( ) { console.log(`Listing alert configurations for detection configuration ${detectdionConfigId}`); let i = 1; - for await (const config of adminClient.listAlertConfigs(detectdionConfigId)) { + const iterator = adminClient.listAlertConfigs(detectdionConfigId); + for await (const config of iterator) { console.log(`Alert configuration ${i++}`); console.log(config); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts index 279c81e10754..580911ea894d 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts @@ -47,7 +47,8 @@ async function listDataFeeds(client: MetricsAdvisorAdministrationClient) { // second approach console.log(" using for-await-of loop"); - for await (const datatFeed of client.listDataFeeds()) { + const iterator = client.listDataFeeds(); + for await (const datatFeed of iterator) { console.log(`id :${datatFeed.id}, name: ${datatFeed.name}`); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/detectionConfig.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/detectionConfig.ts index 217b45261552..11898c8f0adb 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/detectionConfig.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/detectionConfig.ts @@ -193,7 +193,8 @@ async function listDetectionConfig( ) { console.log(`Listing detection configurations for metric '${metricId}'...`); let i = 1; - for await (const config of adminClient.listDetectionConfigs(metricId)) { + const iterator = adminClient.listDetectionConfigs(metricId); + for await (const config of iterator) { console.log(` detection configuration ${i++}`); console.log(config); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts index ef08817c3d55..54c14b680aea 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts @@ -39,14 +39,15 @@ async function listIncidentsForDetectionConfig( ) { console.log(`Listing incidents for detection config '${detectionConfigId}'`); console.log(" using for-await-of syntax"); - for await (const incident of client.listIncidents( + const listIterator = client.listIncidents( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { dimensionFilter: [{ city: "Manila", category: "Shoes Handbags & Sunglasses" }] } - )) { + ); + for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); @@ -83,15 +84,16 @@ async function listAnomaliesForDetectionConfig( detectionConfigId: string ) { console.log(`Listing anomalies for detection config '${detectionConfigId}'`); - console.log(" using for-await-of syntax"); - for await (const anomaly of client.listAnomalies( + const listIterator = client.listAnomalies( detectionConfigId, new Date("10/22/2020"), new Date("10/24/2020"), { severityFilter: { min: "Medium", max: "High" } } - )) { + ); + console.log(" using for-await-of syntax"); + for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` metric id: ${anomaly.metricId}`); console.log(` detection config id: ${anomaly.detectionConfigurationId}`); @@ -136,12 +138,13 @@ async function getRootCauses( async function listAlerts(client: MetricsAdvisorClient, alertConfigId: string) { console.log(`Listing alerts for alert configuration '${alertConfigId}'`); console.log(" using for-await-of syntax"); - for await (const alert of client.listAlerts( + const listIterator = client.listAlerts( alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime" - )) { + ); + for await (const alert of listIterator) { console.log(" Alert"); console.log(` id: ${alert.id}`); console.log(` timestamp: ${alert.timestamp}`); @@ -175,7 +178,8 @@ async function listIncidentsForAlert( `Listing incidents for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); - for await (const incident of client.listIncidents({ alertConfigId, id: alertId })) { + const listIterator = client.listIncidents({ alertConfigId, id: alertId }); + for await (const incident of listIterator) { console.log(" Incident"); console.log(` id: ${incident.id}`); console.log(` severity: ${incident.severity}`); @@ -214,7 +218,8 @@ async function listAnomaliesForAlert( `Listing anomalies for alert configuration '${alertConfigId}' and alert '${alertId}'` ); console.log(" using for-await-of syntax"); - for await (const anomaly of client.listAnomalies({ alertConfigId, id: alertId })) { + const listIterator = client.listAnomalies({ alertConfigId, id: alertId }); + for await (const anomaly of listIterator) { console.log(" Anomaly"); console.log(` timestamp: ${anomaly.timestamp}`); console.log(` dimension: ${anomaly.seriesKey}`); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/ingestionStatus.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/ingestionStatus.ts index f058ed63e36a..865725e093f8 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/ingestionStatus.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/ingestionStatus.ts @@ -42,11 +42,8 @@ async function listIngestionStatus( ) { console.log("Listing ingestion status..."); // iterate through all ingestions using for-await-of - for await (const ingestion of adminClient.listDataFeedIngestionStatus( - dataFeedId, - startTime, - endTime - )) { + const listIterator = adminClient.listDataFeedIngestionStatus(dataFeedId, startTime, endTime); + for await (const ingestion of listIterator) { console.log(` ${ingestion.timestamp} ${ingestion.status} ${ingestion.message}`); } // listing by pages diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricFeedback.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricFeedback.ts index 088a75461c53..5fafc77ddb67 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricFeedback.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricFeedback.ts @@ -93,13 +93,14 @@ async function getFeedback(client: MetricsAdvisorClient, feedbackId: string) { async function listFeedback(client: MetricsAdvisorClient, metricId: string) { console.log("Listing feedbacks..."); console.log(" using for-await-of syntax"); - for await (const feedback of client.listFeedback(metricId, { + const listIterator = client.listFeedback(metricId, { filter: { startTime: new Date("08/01/2020"), endTime: new Date("08/03/2020"), timeMode: "MetricTimestamp" } - })) { + }); + for await (const feedback of listIterator) { console.log(` ${feedback.feedbackType} feedback ${feedback.id}`); console.log(` created time: ${feedback.createdTime}`); console.log(` metric id: ${feedback.metricId}`); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricQueries.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricQueries.ts index d5add6c2435e..2b29c4f37abc 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricQueries.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/metricQueries.ts @@ -29,10 +29,8 @@ export async function main() { async function listMetricSeriesDefinitions(client: MetricsAdvisorClient, metricId: string) { console.log("Listing metric series definitions..."); console.log(" with for-await-of loop"); - for await (const definition of client.listMetricSeriesDefinitions( - metricId, - new Date("08/05/2020") - )) { + const listIterator = client.listMetricSeriesDefinitions(metricId, new Date("08/05/2020")); + for await (const definition of listIterator) { console.log(definition); } console.log(" first two pages using byPage()"); @@ -58,11 +56,12 @@ async function listMetricSeriesDefinitions(client: MetricsAdvisorClient, metricI async function listEnrichmentStatus(client: MetricsAdvisorClient, metricId: string) { console.log("Listing metric enrichment status..."); - for await (const status of client.listMetricEnrichmentStatus( + const listIterator = client.listMetricEnrichmentStatus( metricId, new Date("10/22/2020"), new Date("10/24/2020") - )) { + ); + for await (const status of listIterator) { console.log(" Enrichment status"); console.log(status.timestamp); console.log(status.status); @@ -72,7 +71,8 @@ async function listEnrichmentStatus(client: MetricsAdvisorClient, metricId: stri async function listMetricDimensionValues(client: MetricsAdvisorClient, metricId: string) { console.log("Listing metric dimension values..."); - for await (const dv of client.listMetricDimensionValues(metricId, "city")) { + const listIterator = client.listMetricDimensionValues(metricId, "city"); + for await (const dv of listIterator) { console.log(` ${dv}`); } } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts index cb5ce836d011..67c44c8fe850 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts @@ -154,11 +154,8 @@ async function checkIngestionStatus( ) { // This shows how to use for-await-of syntax to list status console.log("Checking ingestion status..."); - for await (const status of adminClient.listDataFeedIngestionStatus( - datafeedId, - startTime, - endTime - )) { + const listIterator = adminClient.listDataFeedIngestionStatus(datafeedId, startTime, endTime); + for await (const status of listIterator) { console.log(` [${status.timestamp}] ${status.status} - ${status.message}`); } } @@ -248,7 +245,8 @@ async function queryAlerts( // This shows how to use `for-await-of` syntax to list alerts console.log(" using for-await-of syntax"); let alerts: AnomalyAlert[] = []; - for await (const alert of client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime")) { + const listIterator = client.listAlerts(alertConfigId, startTime, endTime, "AnomalyTime"); + for await (const alert of listIterator) { alerts.push(alert); console.log(" Alert"); console.log(` id: ${alert.id}`); @@ -275,7 +273,8 @@ async function queryAnomaliesByAlert(client: MetricsAdvisorClient, alert: Anomal console.log( `Listing anomalies for alert configuration '${alert.alertConfigId}' and alert '${alert.id}'` ); - for await (const anomaly of client.listAnomalies(alert)) { + const listIterator = client.listAnomalies(alert); + for await (const anomaly of listIterator) { console.log( ` Anomaly ${anomaly.severity} ${anomaly.status} ${anomaly.seriesKey.dimension} ${anomaly.timestamp}` ); From 9190ef5439f9fb36c058c381bd24ffccba0c9dc8 Mon Sep 17 00:00:00 2001 From: Jeremy Meng Date: Fri, 6 Nov 2020 13:45:51 -0800 Subject: [PATCH 05/35] [MetricsAdvisor] Fix typos in doc comments/messages (#12340) --- .../ai-metrics-advisor/src/metricsAdvisorClient.ts | 4 ++-- sdk/metricsadvisor/ai-metrics-advisor/src/models.ts | 8 ++++---- .../ai-metrics-advisor/test/adminclient.spec.ts | 4 ++-- .../ai-metrics-advisor/test/datafeed.spec.ts | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorClient.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorClient.ts index 2c357d97abc7..88e499c3b55a 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorClient.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorClient.ts @@ -133,7 +133,7 @@ export type ListFeedbackOptions = { export type ListMetricSeriesDefinitionsOptions = { skip?: number; /** - * filter specfic dimension name and values + * filter specific dimension name and values */ dimensionFilter?: Record; } & OperationOptions; @@ -1805,7 +1805,7 @@ export class MetricsAdvisorClient { * @param startTime The start of the time range to retrieve series data * @param endTime The end of the time range to retrieve series data * @param seriesToFilter A list of time series to retrieve their data - * @param options The optiosn parameter + * @param options The options parameter */ public async getMetricSeriesData( metricId: string, diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts index eeb8e4987e37..ab18ac176918 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts @@ -209,7 +209,7 @@ export interface DataFeedOptions { rollupSettings?: DataFeedRollupSettings; /** - * settings to control how missing data apoints are filled + * settings to control how missing data points are filled */ missingDataPointFillSettings?: DataFeedMissingDataPointFillSettings; @@ -276,7 +276,7 @@ export interface DataFeed { */ status: DataFeedStatus; /** - * Indicates whether the current user is an aministrator of the data feed. + * Indicates whether the current user is an administrator of the data feed. */ isAdmin: boolean; /** @@ -539,7 +539,7 @@ export type MetricSeriesGroupDetectionCondition = DetectionConditionsCommon & { }; /** - * Detection condidtion for a specific time series. + * Detection condition for a specific time series. */ export type MetricSingleSeriesDetectionCondition = DetectionConditionsCommon & { /** @@ -583,7 +583,7 @@ export type HardThresholdConditionUnion = */ anomalyDetectorDirection: "Both"; /** - * supress condition + * suppress condition */ suppressCondition: SuppressCondition; }; diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts index ae101c9fdb71..5197c234de6b 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts @@ -145,7 +145,7 @@ describe("MetricsAdvisorAdministrationClient", () => { const actual = await client.createDetectionConfig(expected); - assert.ok(actual.id, "Expecting valid detecion config"); + assert.ok(actual.id, "Expecting valid detection config"); createdDetectionConfigId = actual.id!; assert.equal(actual.name, expected.name); @@ -207,7 +207,7 @@ describe("MetricsAdvisorAdministrationClient", () => { const actual = await client.updateDetectionConfig(createdDetectionConfigId, expected); - assert.ok(actual.id, "Expecting valid detecion config"); + assert.ok(actual.id, "Expecting valid detection config"); createdDetectionConfigId = actual.id!; assert.equal(actual.name, expected.name); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts index 3723a4cd5156..254f34b38762 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts @@ -169,7 +169,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { assert.equal(actual.schema.dimensions?.length, 2, "Expecting two dimensions"); assert.equal(actual.name, feedName); assert.deepStrictEqual(actual.source, expectedSource, "Source mismatch!"); - assert.deepStrictEqual(actual.granularity, granularity, "Granualarity mismatch!"); + assert.deepStrictEqual(actual.granularity, granularity, "Granularity mismatch!"); assert.equal( actual.schema.metrics[0].name, dataFeedSchema.metrics[0].name, @@ -260,7 +260,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { assert.equal(actual.schema.dimensions?.length, 2, "Expecting two dimensions"); assert.equal(actual.name, feedName); assert.deepStrictEqual(actual.source, expectedSource, "Source mismatch!"); - assert.deepStrictEqual(actual.granularity, granularity, "Granualarity mismatch!"); + assert.deepStrictEqual(actual.granularity, granularity, "Granularity mismatch!"); assert.equal( actual.schema.metrics[0].name, dataFeedSchema.metrics[0].name, From 61d3b59e5605480b933b7f0be13d70b260cd820d Mon Sep 17 00:00:00 2001 From: Sarangan Rajamanickam Date: Fri, 6 Nov 2020 21:58:08 +0000 Subject: [PATCH 06/35] Open up Buffered Sender Configurations (#12297) * Open up Buffered Sender Configurations * Response to PR Comments * Update API File * Added Jitter value * PR Comments II * Add jitterValue to the correct place * Format * Sync Retry Logic with core-https * Changed Name to initialBatchActionCount * Update API --- .../review/search-documents.api.md | 5 ++ .../search-documents/src/indexModels.ts | 26 +++++++++ .../src/searchIndexingBufferedSenderImpl.ts | 55 ++++++++++++++++--- .../search-documents/src/serviceUtils.ts | 11 ++++ 4 files changed, 88 insertions(+), 9 deletions(-) diff --git a/sdk/search/search-documents/review/search-documents.api.md b/sdk/search/search-documents/review/search-documents.api.md index f79b00290db5..6845e7db8544 100644 --- a/sdk/search/search-documents/review/search-documents.api.md +++ b/sdk/search/search-documents/review/search-documents.api.md @@ -1275,6 +1275,11 @@ export type SearchIndexingBufferedSenderMergeOrUploadDocumentsOptions = Operatio // @public export interface SearchIndexingBufferedSenderOptions { autoFlush?: boolean; + flushWindowInMs?: number; + initialBatchActionCount?: number; + maxRetries?: number; + maxRetryDelayInMs?: number; + retryDelayInMs?: number; } // @public diff --git a/sdk/search/search-documents/src/indexModels.ts b/sdk/search/search-documents/src/indexModels.ts index 4d32ffd10cce..2b269eabbb92 100644 --- a/sdk/search/search-documents/src/indexModels.ts +++ b/sdk/search/search-documents/src/indexModels.ts @@ -37,6 +37,32 @@ export interface SearchIndexingBufferedSenderOptions { * Indicates if autoFlush is enabled. */ autoFlush?: boolean; + /** + * Initial Batch Action Count. + * + * A batch request will be sent once the documents + * reach the initialBatchActionCount. + */ + initialBatchActionCount?: number; + /** + * Flush Window. + * + * A batch request will be sent after flushWindowInMs is + * reached. + */ + flushWindowInMs?: number; + /** + * Maximum number of Retries + */ + maxRetries?: number; + /** + * Delay between retries + */ + retryDelayInMs?: number; + /** + * Max Delay between retries + */ + maxRetryDelayInMs?: number; } /** diff --git a/sdk/search/search-documents/src/searchIndexingBufferedSenderImpl.ts b/sdk/search/search-documents/src/searchIndexingBufferedSenderImpl.ts index 49d47182c445..69ab39be91fb 100644 --- a/sdk/search/search-documents/src/searchIndexingBufferedSenderImpl.ts +++ b/sdk/search/search-documents/src/searchIndexingBufferedSenderImpl.ts @@ -18,19 +18,29 @@ import EventEmitter from "events"; import { createSpan } from "./tracing"; import { CanonicalCode } from "@opentelemetry/api"; import { SearchIndexingBufferedSender } from "./searchIndexingBufferedSender"; +import { delay } from "@azure/core-http"; +import { getRandomIntegerInclusive } from "./serviceUtils"; /** * Default Batch Size */ -export const DEFAULT_BATCH_SIZE: number = 1000; +export const DEFAULT_BATCH_SIZE: number = 512; /** * Default window flush interval */ export const DEFAULT_FLUSH_WINDOW: number = 60000; /** - * Default number of times to retry + * Default number of times to retry. */ export const DEFAULT_RETRY_COUNT: number = 3; +/** + * Default retry delay. + */ +export const DEFAULT_RETRY_DELAY: number = 800; +/** + * Default Max Delay between retries. + */ +export const DEFAULT_MAX_RETRY_DELAY: number = 60000; /** * Class used to perform buffered operations against a search index, @@ -49,10 +59,22 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende * Interval between flushes (in milliseconds). */ private flushWindowInMs: number; + /** + * Delay between retries + */ + private retryDelayInMs: number; + /** + * Maximum number of Retries + */ + private maxRetries: number; + /** + * Max Delay between retries + */ + private maxRetryDelayInMs: number; /** * Size of the batch. */ - private batchSize: number; + private initialBatchActionCount: number; /** * Batch object used to complete the service call. */ @@ -75,9 +97,15 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende */ constructor(client: SearchClient, options: SearchIndexingBufferedSenderOptions = {}) { this.client = client; + // General Configuration properties this.autoFlush = options.autoFlush ?? false; - this.flushWindowInMs = DEFAULT_FLUSH_WINDOW; - this.batchSize = DEFAULT_BATCH_SIZE; + this.initialBatchActionCount = options.initialBatchActionCount ?? DEFAULT_BATCH_SIZE; + this.flushWindowInMs = options.flushWindowInMs ?? DEFAULT_FLUSH_WINDOW; + // Retry specific configuration properties + this.retryDelayInMs = options.retryDelayInMs ?? DEFAULT_FLUSH_WINDOW; + this.maxRetries = options.maxRetries ?? DEFAULT_RETRY_COUNT; + this.maxRetryDelayInMs = options.maxRetryDelayInMs ?? DEFAULT_MAX_RETRY_DELAY; + this.batchObject = new IndexDocumentsBatch(); if (this.autoFlush) { const interval = setInterval(() => this.flush(), this.flushWindowInMs); @@ -323,7 +351,7 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende } private isBatchReady(): boolean { - return this.batchObject.actions.length >= this.batchSize; + return this.batchObject.actions.length >= this.initialBatchActionCount; } private async internalFlush(force: boolean, options: OperationOptions = {}): Promise { @@ -332,7 +360,7 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende const actions: IndexDocumentsAction[] = this.batchObject.actions; this.batchObject = new IndexDocumentsBatch(); while (actions.length > 0) { - const actionsToSend = actions.splice(0, this.batchSize); + const actionsToSend = actions.splice(0, this.initialBatchActionCount); await this.submitDocuments(actionsToSend, options); } } @@ -341,7 +369,7 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende private async submitDocuments( actionsToSend: IndexDocumentsAction[], options: OperationOptions, - retryAttempt: number = 0 + retryAttempt: number = 1 ): Promise { try { for (const action of actionsToSend) { @@ -354,7 +382,16 @@ class SearchIndexingBufferedSenderImpl implements SearchIndexingBufferedSende // raise success event this.emitter.emit("batchSucceeded", result); } catch (e) { - if (this.isRetryAbleError(e) && retryAttempt < DEFAULT_RETRY_COUNT) { + if (this.isRetryAbleError(e) && retryAttempt <= this.maxRetries) { + // Exponentially increase the delay each time + const exponentialDelay = this.retryDelayInMs * Math.pow(2, retryAttempt); + // Don't let the delay exceed the maximum + const clampedExponentialDelay = Math.min(this.maxRetryDelayInMs, exponentialDelay); + // Allow the final value to have some "jitter" (within 50% of the delay size) so + // that retries across multiple clients don't occur simultaneously. + const delayWithJitter = + clampedExponentialDelay / 2 + getRandomIntegerInclusive(0, clampedExponentialDelay / 2); + await delay(delayWithJitter); this.submitDocuments(actionsToSend, options, retryAttempt + 1); } else { this.emitter.emit("batchFailed", e); diff --git a/sdk/search/search-documents/src/serviceUtils.ts b/sdk/search/search-documents/src/serviceUtils.ts index fe360f066ea5..dd1c61962b94 100644 --- a/sdk/search/search-documents/src/serviceUtils.ts +++ b/sdk/search/search-documents/src/serviceUtils.ts @@ -574,3 +574,14 @@ export function convertDataDeletionDetectionPolicyToPublic( return dataDeletionDetectionPolicy as SoftDeleteColumnDeletionDetectionPolicy; } + +export function getRandomIntegerInclusive(min: number, max: number): number { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} From 6f4e75b15046393318ee381d2a697a26431212d1 Mon Sep 17 00:00:00 2001 From: Jeremy Meng Date: Fri, 6 Nov 2020 14:51:28 -0800 Subject: [PATCH 07/35] [MetricsAdvisor] rename createTime property to createdOn (#12259) to be consistent with JS libraries' convention. --- .../ai-metrics-advisor/CHANGELOG.md | 1 + .../review/ai-metrics-advisor.api.md | 6 ++--- .../samples/javascript/metricFeedback.js | 2 +- .../samples/typescript/src/metricFeedback.ts | 2 +- .../src/metricsAdvisorAdministrationClient.ts | 2 +- .../ai-metrics-advisor/src/models.ts | 4 +-- .../ai-metrics-advisor/src/transforms.ts | 4 +-- .../test/adminclient.spec.ts | 4 +-- .../ai-metrics-advisor/test/datafeed.spec.ts | 25 +++++++++++-------- .../test/transforms.spec.ts | 4 +-- 10 files changed, 28 insertions(+), 26 deletions(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md index de4806f976ba..4009bdf68bc8 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md @@ -45,6 +45,7 @@ - `EnrichmentStatus.timestamp` - `IngestionStatus.timestamp` - `latestSuccessTimestamp` and `latestActiveTimestamp` in the return type of `getDataFeedIngestionProgress()`. +- [Breaking] property `createdTime` on `DataFeed` and `MetricFeedbackCommon` to `createdOn`. - Parameters of `Date` type now also accept strings. No validation is done for the strings. The SDK calls `new Date()` to convert them to `Date`. - Handle potential new data feed source types gracefully diff --git a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md index 3d510c5568ab..9fed889be5df 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md @@ -195,7 +195,7 @@ export type CreateDataFeedOptions = DataFeedOptions & OperationOptions; // @public export interface DataFeed { - createdTime: Date; + createdOn: Date; creator: string; granularity: DataFeedGranularity; id: string; @@ -212,7 +212,7 @@ export interface DataFeed { export type DataFeedAccessMode = "Private" | "Public"; // @public -export type DataFeedDescriptor = Omit; +export type DataFeedDescriptor = Omit; // @public export type DataFeedDetailStatus = "Active" | "Paused"; @@ -776,7 +776,7 @@ export interface MetricEnrichmentStatusPageResponse extends Array; /** diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts index ab18ac176918..6546d78d6a4b 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts @@ -270,7 +270,7 @@ export interface DataFeed { /** * Time when the data feed is created */ - createdTime: Date; + createdOn: Date; /** * Status of the data feed. */ @@ -644,7 +644,7 @@ export interface MetricFeedbackCommon { /** * feedback created time */ - readonly createdTime?: Date; + readonly createdOn?: Date; /** * user who gives this feedback */ diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts index 5c909d7cf523..929ef1ee6990 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts @@ -188,7 +188,7 @@ export function fromServiceMetricFeedbackUnion( ): MetricFeedbackUnion { const common: MetricFeedbackCommon = { id: original.feedbackId, - createdTime: original.createdTime, + createdOn: original.createdTime, userPrincipal: original.userPrincipal, metricId: original.metricId, dimensionKey: original.dimensionFilter.dimension @@ -337,7 +337,7 @@ export function fromServiceDataFeedDetailUnion(original: ServiceDataFeedDetailUn id: original.dataFeedId!, name: original.dataFeedName, metricIds: original.metrics.map((c) => c.id!), - createdTime: original.createdTime!, + createdOn: original.createdTime!, status: original.status!, isAdmin: original.isAdmin!, creator: original.creator!, diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts index 5197c234de6b..7a9d90a3b9df 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/adminclient.spec.ts @@ -248,9 +248,7 @@ describe("MetricsAdvisorAdministrationClient", () => { }); it("lists detection configurations", async function() { - const iterator = client.listDetectionConfigs( - testEnv.METRICS_ADVISOR_AZURE_BLOB_METRIC_ID_1 - ); + const iterator = client.listDetectionConfigs(testEnv.METRICS_ADVISOR_AZURE_BLOB_METRIC_ID_1); let result = await iterator.next(); assert.ok(result.value.id, "Expecting first detection config"); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts index 254f34b38762..5a55ab3cadb6 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts @@ -764,15 +764,15 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { }); it("creates Unknown data feed", async () => { - const expectedSource : UnknownDataFeedSource = { + const expectedSource: UnknownDataFeedSource = { dataSourceType: "Unknown", dataSourceParameter: { connectionString: "https://connect-to-postgresql", query: "{ find: postgresql,filter: { Time: @StartTime },batch: 200 }" } }; - try{ - await client.createDataFeed({ + try { + await client.createDataFeed({ name: postgreSqlFeedName, source: expectedSource, granularity, @@ -781,9 +781,11 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { options }); assert.fail("Test should throw error"); - } - catch(error){ - assert.equal((error as any).message, "Cannot create a data feed with the Unknown source type."); + } catch (error) { + assert.equal( + (error as any).message, + "Cannot create a data feed with the Unknown source type." + ); } }); @@ -798,15 +800,16 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { } } }; - try{ + try { await client.updateDataFeed(createdPostGreSqlId, patch); assert.fail("Test should throw error"); - } - catch(error){ - assert.equal((error as any).message, "Cannot update a data feed to have the Unknown source type."); + } catch (error) { + assert.equal( + (error as any).message, + "Cannot update a data feed to have the Unknown source type." + ); } }); - }); }).timeout(60000); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts index 395c78a0999e..74674579f35d 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/transforms.spec.ts @@ -92,7 +92,7 @@ describe("Transforms", () => { const actual = fromServiceMetricFeedbackUnion(anomalyFeedback); assert.equal(actual.id, feedbackCommon.feedbackId); - assert.equal(actual.createdTime, feedbackCommon.createdTime); + assert.equal(actual.createdOn, feedbackCommon.createdTime); assert.equal(actual.userPrincipal, feedbackCommon.userPrincipal); assert.equal(actual.dimensionKey, feedbackCommon.dimensionFilter.dimension); assert.equal(actual.feedbackType, "Anomaly"); @@ -186,7 +186,7 @@ describe("Transforms", () => { it("fromServiceDataFeedDetailUnion() for future data source types", () => { const serviceDataFeed: ServiceDataFeedDetailUnion = { dataSourceType: "Future Source" as any, - dataSourceParameter: {futureConnectionString: "xyz", futureQuery: "someQuery"} as any, + dataSourceParameter: { futureConnectionString: "xyz", futureQuery: "someQuery" } as any, dataFeedName: "name", metrics: [{ name: "m1", id: "m-id1", displayName: "m1 display" }], dimension: [{ name: "d1", displayName: "d1 display" }], From 25464c79df2c74bbb646c942dc840a669879ba4e Mon Sep 17 00:00:00 2001 From: Sarangan Rajamanickam Date: Fri, 6 Nov 2020 23:05:03 +0000 Subject: [PATCH 08/35] November release changes (#12342) * November Release Changes * Format --- sdk/search/search-documents/CHANGELOG.md | 5 ++++- .../src/bufferedSender/uploadDocuments/autoFlushSizeBased.ts | 2 ++ .../bufferedSender/uploadDocuments/autoFlushTimerBased.ts | 2 ++ .../src/bufferedSender/uploadDocuments/manualFlush.ts | 2 ++ 4 files changed, 10 insertions(+), 1 deletion(-) diff --git a/sdk/search/search-documents/CHANGELOG.md b/sdk/search/search-documents/CHANGELOG.md index 5c79ab848bd3..4c1680b1352d 100644 --- a/sdk/search/search-documents/CHANGELOG.md +++ b/sdk/search/search-documents/CHANGELOG.md @@ -1,7 +1,10 @@ # Release History -## 11.1.0-beta.2 (Unreleased) +## 11.1.0-beta.2 (2020-11-10) +- [Breaking] Hidden the constructor of `SearchIndexingBufferedSender` and made it to an interface. Please refer [#11785](https://github.com/Azure/azure-sdk-for-js/pull/11785) for further details. +- Added `encryptionKey` property to `SearchIndexerDataSource`, `SearchIndexer` and `SearchIndexerSkillSet` objects. Please refer [#12275](https://github.com/Azure/azure-sdk-for-js/pull/12275) for further details. +- Added user configurable properties such as `flushWindowInMs`, `initialBatchActionCount`, `maxRetries`, etc to the `SearchIndexingBufferedSenderOptions` object. Please refer [#12297](https://github.com/Azure/azure-sdk-for-js/pull/12297) for further details. ## 11.1.0-beta.1 (2020-10-05) diff --git a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushSizeBased.ts b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushSizeBased.ts index 0fcd01436f92..55166c474553 100644 --- a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushSizeBased.ts +++ b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushSizeBased.ts @@ -8,6 +8,8 @@ import { import { createIndex, WAIT_TIME } from "../../utils/setup"; import { Hotel } from "../../utils/interfaces"; import { delay } from "@azure/core-http"; +import * as dotenv from "dotenv"; +dotenv.config(); /** * This sample is to demonstrate the use of SearchIndexingBufferedSender. diff --git a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushTimerBased.ts b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushTimerBased.ts index 397f44dd3f90..19ff310d7d76 100644 --- a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushTimerBased.ts +++ b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/autoFlushTimerBased.ts @@ -9,6 +9,8 @@ import { import { createIndex, WAIT_TIME } from "../../utils/setup"; import { Hotel } from "../../utils/interfaces"; import { delay } from "@azure/core-http"; +import * as dotenv from "dotenv"; +dotenv.config(); /** * This sample is to demonstrate the use of SearchIndexingBufferedSender. diff --git a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/manualFlush.ts b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/manualFlush.ts index 1bec7c045b9b..bd5f2321bd37 100644 --- a/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/manualFlush.ts +++ b/sdk/search/search-documents/samples/typescript/src/bufferedSender/uploadDocuments/manualFlush.ts @@ -8,6 +8,8 @@ import { import { createIndex, WAIT_TIME } from "../../utils/setup"; import { Hotel } from "../../utils/interfaces"; import { delay } from "@azure/core-http"; +import * as dotenv from "dotenv"; +dotenv.config(); /** * This sample is to demonstrate the use of SearchIndexingBufferedSender. From e918a3ea9fc3dddafaa9fe4b48c689eabd84b34c Mon Sep 17 00:00:00 2001 From: Jeremy Meng Date: Fri, 6 Nov 2020 15:21:13 -0800 Subject: [PATCH 09/35] [MetricsAdvisor] Flatten DataFeedOptions in data feed (#12263) and remove the wrapping `options`. We were putting into it all the rest of optional settings that don't fit into any of groupings but it's not necessary. --- .../ai-metrics-advisor/CHANGELOG.md | 1 + .../ai-metrics-advisor/README.md | 22 ++--- .../review/ai-metrics-advisor.api.md | 30 +++--- .../samples/javascript/dataFeed.js | 34 +++---- .../samples/javascript/quickstart.js | 22 ++--- .../samples/typescript/src/dataFeed.ts | 34 +++---- .../samples/typescript/src/quickstart.ts | 22 ++--- .../src/metricsAdvisorAdministrationClient.ts | 69 +++++++------ .../ai-metrics-advisor/src/models.ts | 16 +-- .../ai-metrics-advisor/src/transforms.ts | 32 +++--- .../ai-metrics-advisor/test/datafeed.spec.ts | 99 +++++++++---------- 11 files changed, 179 insertions(+), 202 deletions(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md index 4009bdf68bc8..0cc977b3fbae 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md @@ -46,6 +46,7 @@ - `IngestionStatus.timestamp` - `latestSuccessTimestamp` and `latestActiveTimestamp` in the return type of `getDataFeedIngestionProgress()`. - [Breaking] property `createdTime` on `DataFeed` and `MetricFeedbackCommon` to `createdOn`. +- [Breaking] Remove the wrapping data feed `options` property from `DataFeed` and `DataFeedPatch` and flatten its child properties. - Parameters of `Date` type now also accept strings. No validation is done for the strings. The SDK calls `new Date()` to convert them to `Date`. - Handle potential new data feed source types gracefully diff --git a/sdk/metricsadvisor/ai-metrics-advisor/README.md b/sdk/metricsadvisor/ai-metrics-advisor/README.md index d4e62ab9ac7b..e90323516630 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/README.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/README.md @@ -197,18 +197,16 @@ async function createDataFeed(adminClient, sqlServerConnectionString, sqlServerQ ingestionRetryDelayInSeconds: -1, stopRetryAfterInSeconds: -1 }, - options: { - rollupSettings: { - rollupType: "AutoRollup", - rollupMethod: "Sum", - rollupIdentificationValue: "__CUSTOM_SUM__" - }, - missingDataPointFillSettings: { - fillType: "SmartFilling" - }, - accessMode: "Private", - adminEmails: ["xyz@example.com"] - } + rollupSettings: { + rollupType: "AutoRollup", + rollupMethod: "Sum", + rollupIdentificationValue: "__CUSTOM_SUM__" + }, + missingDataPointFillSettings: { + fillType: "SmartFilling" + }, + accessMode: "Private", + adminEmails: ["xyz@example.com"] }; const result = await adminClient.createDataFeed(dataFeed); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md index 9fed889be5df..1deee119949a 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/review/ai-metrics-advisor.api.md @@ -194,19 +194,18 @@ export type ChangeThresholdConditionUnion = { export type CreateDataFeedOptions = DataFeedOptions & OperationOptions; // @public -export interface DataFeed { +export type DataFeed = { + id: string; + name: string; createdOn: Date; + status: DataFeedStatus; + isAdmin: boolean; creator: string; + source: DataFeedSource; + schema: DataFeedSchema; granularity: DataFeedGranularity; - id: string; ingestionSettings: DataFeedIngestionSettings; - isAdmin: boolean; - name: string; - options?: DataFeedOptions; - schema: DataFeedSchema; - source: DataFeedSource; - status: DataFeedStatus; -} +} & DataFeedOptions; // @public export type DataFeedAccessMode = "Private" | "Public"; @@ -274,17 +273,16 @@ export interface DataFeedOptions { } // @public -export interface DataFeedPatch { - ingestionSettings?: DataFeedIngestionSettings; +export type DataFeedPatch = { name?: string; - options?: DataFeedOptions & { - status?: DataFeedDetailStatus; - }; + source: DataFeedSourcePatch; schema?: { timestampColumn?: string; }; - source: DataFeedSourcePatch; -} + ingestionSettings?: DataFeedIngestionSettings; +} & DataFeedOptions & { + status?: DataFeedDetailStatus; +}; // @public export type DataFeedRollupMethod = "None" | "Sum" | "Max" | "Min" | "Avg" | "Count"; diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js index 901721dd4acd..cefca08049a6 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js @@ -109,18 +109,16 @@ async function createDataFeed(client) { ingestionRetryDelayInSeconds: -1, stopRetryAfterInSeconds: -1 }, - options: { - rollupSettings: { - rollupType: "AutoRollup", - rollupMethod: "Sum", - rollupIdentificationValue: "__SUM__" - }, - missingDataPointFillSettings: { - fillType: "CustomValue", - customFillValue: 567 - }, - accessMode: "Private" - } + rollupSettings: { + rollupType: "AutoRollup", + rollupMethod: "Sum", + rollupIdentificationValue: "__SUM__" + }, + missingDataPointFillSettings: { + fillType: "CustomValue", + customFillValue: 567 + }, + accessMode: "Private" }; const result = await client.createDataFeed(feed); @@ -149,13 +147,11 @@ async function updateDataFeed(client, dataFeedId) { stopRetryAfterInSeconds: 667777, ingestionStartOffsetInSeconds: 4444 }, - options: { - description: "New datafeed description", - missingDataPointFillSettings: { - fillType: "SmartFilling" - }, - status: "Paused" - } + description: "New datafeed description", + missingDataPointFillSettings: { + fillType: "SmartFilling" + }, + status: "Paused" }; try { diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js index de0eee9bec19..b14d154e4f31 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/quickstart.js @@ -116,18 +116,16 @@ async function createDataFeed(adminClient, sqlServerConnectionString, sqlServerQ ingestionRetryDelayInSeconds: -1, stopRetryAfterInSeconds: -1 }, - options: { - rollupSettings: { - rollupType: "AutoRollup", - rollupMethod: "Sum", - rollupIdentificationValue: "__SUM__" - }, - missingDataPointFillSettings: { - fillType: "SmartFilling" - }, - accessMode: "Private", - adminEmails: ["xyz@microsoft.com"] - } + rollupSettings: { + rollupType: "AutoRollup", + rollupMethod: "Sum", + rollupIdentificationValue: "__SUM__" + }, + missingDataPointFillSettings: { + fillType: "SmartFilling" + }, + accessMode: "Private", + adminEmails: ["xyz@microsoft.com"] }; const result = await adminClient.createDataFeed(dataFeed); return result; diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts index 580911ea894d..bbef1ea3f7a2 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts @@ -115,18 +115,16 @@ async function createDataFeed( ingestionRetryDelayInSeconds: -1, stopRetryAfterInSeconds: -1 }, - options: { - rollupSettings: { - rollupType: "AutoRollup", - rollupMethod: "Sum", - rollupIdentificationValue: "__CUSTOM_SUM__" - }, - missingDataPointFillSettings: { - fillType: "CustomValue", - customFillValue: 567 - }, - accessMode: "Private" - } + rollupSettings: { + rollupType: "AutoRollup", + rollupMethod: "Sum", + rollupIdentificationValue: "__CUSTOM_SUM__" + }, + missingDataPointFillSettings: { + fillType: "CustomValue", + customFillValue: 567 + }, + accessMode: "Private" }; const result = await client.createDataFeed(feed); @@ -155,13 +153,11 @@ async function updateDataFeed(client: MetricsAdvisorAdministrationClient, dataFe stopRetryAfterInSeconds: 667777, ingestionStartOffsetInSeconds: 4444 }, - options: { - description: "New datafeed description", - missingDataPointFillSettings: { - fillType: "SmartFilling" - }, - status: "Paused" - } + description: "New datafeed description", + missingDataPointFillSettings: { + fillType: "SmartFilling" + }, + status: "Paused" }; try { diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts index 67c44c8fe850..6c06a025908d 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts @@ -128,18 +128,16 @@ async function createDataFeed( ingestionRetryDelayInSeconds: -1, stopRetryAfterInSeconds: -1 }, - options: { - rollupSettings: { - rollupType: "AutoRollup", - rollupMethod: "Sum", - rollupIdentificationValue: "__SUM__" - }, - missingDataPointFillSettings: { - fillType: "SmartFilling" - }, - accessMode: "Private", - adminEmails: ["xyz@microsoft.com"] - } + rollupSettings: { + rollupType: "AutoRollup", + rollupMethod: "Sum", + rollupIdentificationValue: "__SUM__" + }, + missingDataPointFillSettings: { + fillType: "SmartFilling" + }, + accessMode: "Private", + adminEmails: ["xyz@microsoft.com"] }; const result = await adminClient.createDataFeed(dataFeed); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts index 085cb19e4637..7c0a3df6da15 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/metricsAdvisorAdministrationClient.ts @@ -187,35 +187,46 @@ export class MetricsAdvisorAdministrationClient { "MetricsAdvisorAdministrationClient-createDataFeed", operationOptions ); - const { name, granularity, source, schema, ingestionSettings, options } = feed; + const { + name, + granularity, + source, + schema, + ingestionSettings, + rollupSettings, + missingDataPointFillSettings, + accessMode, + adminEmails, + viewerEmails, + description + } = feed; + if (source.dataSourceType === "Unknown") { throw new Error("Cannot create a data feed with the Unknown source type."); } + const needRollup: NeedRollupEnum | undefined = - options?.rollupSettings?.rollupType === "AutoRollup" + rollupSettings?.rollupType === "AutoRollup" ? "NeedRollup" - : options?.rollupSettings?.rollupType === "AlreadyRollup" + : rollupSettings?.rollupType === "AlreadyRollup" ? "AlreadyRollup" - : options?.rollupSettings?.rollupType === "NoRollup" + : rollupSettings?.rollupType === "NoRollup" ? "NoRollup" : undefined; const rollUpColumns: string[] | undefined = - options?.rollupSettings?.rollupType === "AutoRollup" - ? options?.rollupSettings.autoRollupGroupByColumnNames + rollupSettings?.rollupType === "AutoRollup" + ? rollupSettings.autoRollupGroupByColumnNames : undefined; const allUpIdentification: string | undefined = - options?.rollupSettings?.rollupType === "AutoRollup" || - options?.rollupSettings?.rollupType === "AlreadyRollup" - ? options?.rollupSettings.rollupIdentificationValue + rollupSettings?.rollupType === "AutoRollup" || rollupSettings?.rollupType === "AlreadyRollup" + ? rollupSettings.rollupIdentificationValue : undefined; const rollUpMethod: DataFeedRollupMethod | undefined = - options?.rollupSettings?.rollupType === "AutoRollup" - ? options?.rollupSettings.rollupMethod - : undefined; - const fillMissingPointType = options?.missingDataPointFillSettings?.fillType; + rollupSettings?.rollupType === "AutoRollup" ? rollupSettings.rollupMethod : undefined; + const fillMissingPointType = missingDataPointFillSettings?.fillType; const fillMissingPointValue = - options?.missingDataPointFillSettings?.fillType === "CustomValue" - ? options?.missingDataPointFillSettings.customFillValue + missingDataPointFillSettings?.fillType === "CustomValue" + ? missingDataPointFillSettings.customFillValue : undefined; try { const requestOptions = operationOptionsToRequestOptionsBase(finalOptions); @@ -237,10 +248,10 @@ export class MetricsAdvisorAdministrationClient { rollUpMethod, fillMissingPointType, fillMissingPointValue, - viewMode: options?.accessMode, - admins: options?.adminEmails, - viewers: options?.viewerEmails, - dataFeedDescription: options?.description, + viewMode: accessMode, + admins: adminEmails, + viewers: viewerEmails, + dataFeedDescription: description, ...finalOptions }; const result = await this.client.createDataFeed(body, requestOptions); @@ -467,7 +478,7 @@ export class MetricsAdvisorAdministrationClient { dataSourceParameter: patch.source.dataSourceParameter, // name and description dataFeedName: patch.name, - dataFeedDescription: patch.options?.description, + dataFeedDescription: patch.description, // schema timestampColumn: patch.schema?.timestampColumn, // ingestion settings @@ -477,19 +488,19 @@ export class MetricsAdvisorAdministrationClient { minRetryIntervalInSeconds: patch.ingestionSettings?.ingestionRetryDelayInSeconds, stopRetryAfterInSeconds: patch.ingestionSettings?.stopRetryAfterInSeconds, // rollup settings - ...toServiceRollupSettings(patch.options?.rollupSettings), + ...toServiceRollupSettings(patch.rollupSettings), // missing point filling settings - fillMissingPointType: patch.options?.missingDataPointFillSettings?.fillType, + fillMissingPointType: patch.missingDataPointFillSettings?.fillType, fillMissingPointValue: - patch.options?.missingDataPointFillSettings?.fillType === "CustomValue" - ? patch.options.missingDataPointFillSettings.customFillValue + patch.missingDataPointFillSettings?.fillType === "CustomValue" + ? patch.missingDataPointFillSettings.customFillValue : undefined, // other options - viewMode: patch.options?.accessMode, - admins: patch.options?.adminEmails, - viewers: patch.options?.viewerEmails, - status: patch.options?.status, - actionLinkTemplate: patch.options?.actionLinkTemplate + viewMode: patch.accessMode, + admins: patch.adminEmails, + viewers: patch.viewerEmails, + status: patch.status, + actionLinkTemplate: patch.actionLinkTemplate }; await this.client.updateDataFeed(dataFeedId, patchBody, requestOptions); return this.getDataFeed(dataFeedId); diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts index 6546d78d6a4b..d0477fe0ec47 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/models.ts @@ -258,7 +258,7 @@ export type DataFeedStatus = "Paused" | "Active"; /** * Represents a Metrics Advisor data feed. */ -export interface DataFeed { +export type DataFeed = { /** * Unique id of the data feed. */ @@ -299,11 +299,7 @@ export interface DataFeed { * Ingestion settings for the data feed. */ ingestionSettings: DataFeedIngestionSettings; - /** - * Optional configurations for the data feed. - */ - options?: DataFeedOptions; -} +} & DataFeedOptions; /** * Represents an Azure Application Insights data source. @@ -439,7 +435,7 @@ export type DataFeedSource = /** * Represents the input type to the Update Data Feed operation. */ -export interface DataFeedPatch { +export type DataFeedPatch = { /** * Name of the data feed */ @@ -461,16 +457,12 @@ export interface DataFeedPatch { * Ingestion settings for the data feed. */ ingestionSettings?: DataFeedIngestionSettings; - /** - * Optional configurations for the data feed. - */ - options?: DataFeedOptions & { +} & DataFeedOptions & { /** * Status of the data feed. */ status?: DataFeedDetailStatus; }; -} /** * A alias type of supported data sources to pass to Update Data Feed operation. diff --git a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts index 929ef1ee6990..fa98d743efb7 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/src/transforms.ts @@ -354,23 +354,21 @@ export function fromServiceDataFeedDetailUnion(original: ServiceDataFeedDetailUn ingestionRetryDelayInSeconds: original.minRetryIntervalInSeconds, stopRetryAfterInSeconds: original.stopRetryAfterInSeconds }, - options: { - description: original.dataFeedDescription, - actionLinkTemplate: original.actionLinkTemplate, - rollupSettings: toRollupSettings(original), - missingDataPointFillSettings: - original.fillMissingPointType === "CustomValue" - ? { - fillType: original.fillMissingPointType!, - customFillValue: original.fillMissingPointValue! - } - : { - fillType: original.fillMissingPointType! - }, - accessMode: original.viewMode, - adminEmails: original.admins, - viewerEmails: original.viewers - } + description: original.dataFeedDescription, + actionLinkTemplate: original.actionLinkTemplate, + rollupSettings: toRollupSettings(original), + missingDataPointFillSettings: + original.fillMissingPointType === "CustomValue" + ? { + fillType: original.fillMissingPointType!, + customFillValue: original.fillMissingPointValue! + } + : { + fillType: original.fillMissingPointType! + }, + accessMode: original.viewMode, + adminEmails: original.admins, + viewerEmails: original.viewers }; switch (original.dataSourceType) { case "AzureApplicationInsights": { diff --git a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts index 5a55ab3cadb6..97f3bf0359ca 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/test/datafeed.spec.ts @@ -159,7 +159,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -191,48 +191,44 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { dataFeedIngestion, "Ingesting settings mismatch!" ); - assert.ok(actual.options, "Expecting valid datafeed options"); - assert.equal( - actual.options!.description, - options.description, - "options.description mismatch" - ); - assert.equal(actual.options!.accessMode, options.accessMode, "options.accessMode mismatch"); + + assert.equal(actual.description, options.description, "options.description mismatch"); + assert.equal(actual.accessMode, options.accessMode, "options.accessMode mismatch"); assert.ok( - actual.options!.missingDataPointFillSettings, + actual.missingDataPointFillSettings, "Expecting valid options.missingDataPointFillSettings" ); assert.equal( - actual.options!.missingDataPointFillSettings!.fillType, + actual.missingDataPointFillSettings!.fillType, options.missingDataPointFillSettings!.fillType, "options.missingDataPointFillSettings.fillType mismatch" ); assert.ok( - actual.options!.missingDataPointFillSettings!.fillType, + actual.missingDataPointFillSettings!.fillType, "Expecting valid options.missingDataPointFillSettings.fillType" ); - if (actual.options!.missingDataPointFillSettings!.fillType! === "CustomValue") { + if (actual.missingDataPointFillSettings!.fillType! === "CustomValue") { // not sure why TS didn't narrow down the union type for us...so casting to any assert.equal( - (actual.options!.missingDataPointFillSettings! as any).customFillValue, + (actual.missingDataPointFillSettings! as any).customFillValue, (options.missingDataPointFillSettings! as any).customFillValue, "options.missingDataPointFillSettings.customFillValue mismatch" ); } - assert.ok(actual.options!.rollupSettings, "Expecting valid options.rollupSettings"); + assert.ok(actual.rollupSettings, "Expecting valid options.rollupSettings"); assert.equal( - actual.options!.rollupSettings!.rollupType, + actual.rollupSettings!.rollupType, options.rollupSettings!.rollupType, "options.missingDataPointFillSettings.rollupType mismatch" ); assert.ok( - actual.options!.rollupSettings!.rollupType, + actual.rollupSettings!.rollupType, "Expecting valid options.missingDataPointFillSettings.fillType" ); - if (actual.options!.rollupSettings!.rollupType! === "AutoRollup") { + if (actual.rollupSettings!.rollupType! === "AutoRollup") { // not sure why TS didn't narrow down the union type for us...so casting to any assert.equal( - (actual.options!.rollupSettings! as any).rollupIdentificationValue, + (actual.rollupSettings! as any).rollupIdentificationValue, (options.rollupSettings! as any).rollupIdentificationValue, "options.missingDataPointFillSettings.fillType mismatch" ); @@ -306,19 +302,17 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { timestampColumn: "UpdatedTimestampeColumn" }, ingestionSettings: expectedIngestionSettings, - options: { - description: "Updated Azure Blob description", - rollupSettings: { - rollupType: "AlreadyRollup", - rollupIdentificationValue: "__Existing__" - }, - missingDataPointFillSettings: { - fillType: "PreviousValue" - }, - accessMode: "Public", - viewerEmails: ["viewer1@example.com"], - actionLinkTemplate: "Updated Azure Blob action link template" - } + description: "Updated Azure Blob description", + rollupSettings: { + rollupType: "AlreadyRollup", + rollupIdentificationValue: "__Existing__" + }, + missingDataPointFillSettings: { + fillType: "PreviousValue" + }, + accessMode: "Public", + viewerEmails: ["viewer1@example.com"], + actionLinkTemplate: "Updated Azure Blob action link template" }; const updated = await client.updateDataFeed(createdAzureBlobDataFeedId, patch); @@ -326,18 +320,15 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { assert.equal(updated.source.dataSourceType, "AzureBlob"); assert.deepStrictEqual(updated.source.dataSourceParameter, expectedSourceParameter); assert.deepStrictEqual(updated.ingestionSettings, expectedIngestionSettings); - assert.ok(updated.options, "Expecting valid updated.options"); - assert.equal(updated.options!.description, "Updated Azure Blob description"); - assert.ok(updated.options!.rollupSettings, "Expecting valid updated.options.rollupSettings"); - assert.equal(updated.options!.rollupSettings!.rollupType, "AlreadyRollup"); - assert.equal( - (updated.options!.rollupSettings! as any).rollupIdentificationValue, - "__Existing__" - ); - assert.equal(updated.options!.missingDataPointFillSettings?.fillType, "PreviousValue"); - assert.equal(updated.options!.accessMode, "Public"); - assert.deepStrictEqual(updated.options!.viewerEmails, ["viewer1@example.com"]); - assert.equal(updated.options?.actionLinkTemplate, "Updated Azure Blob action link template"); + + assert.equal(updated.description, "Updated Azure Blob description"); + assert.ok(updated.rollupSettings, "Expecting valid updated.options.rollupSettings"); + assert.equal(updated.rollupSettings!.rollupType, "AlreadyRollup"); + assert.equal((updated.rollupSettings! as any).rollupIdentificationValue, "__Existing__"); + assert.equal(updated.missingDataPointFillSettings?.fillType, "PreviousValue"); + assert.equal(updated.accessMode, "Public"); + assert.deepStrictEqual(updated.viewerEmails, ["viewer1@example.com"]); + assert.equal(updated.actionLinkTemplate, "Updated Azure Blob action link template"); }); it("creates an Azure Application Insights feed", async () => { @@ -357,7 +348,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -394,7 +385,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -466,7 +457,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -504,7 +495,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -541,7 +532,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -577,7 +568,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -612,7 +603,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -649,7 +640,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -686,7 +677,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -722,7 +713,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.ok(actual.id, "Expecting valid data feed id"); @@ -778,7 +769,7 @@ describe("MetricsAdvisorAdministrationClient datafeed", () => { granularity, schema: dataFeedSchema, ingestionSettings: dataFeedIngestion, - options + ...options }); assert.fail("Test should throw error"); } catch (error) { From ae679b539e4bf2107231b96e02f5ef6408491d89 Mon Sep 17 00:00:00 2001 From: Jeremy Meng Date: Fri, 6 Nov 2020 16:47:40 -0800 Subject: [PATCH 10/35] [MetricsAdvisor] Fix missed rename updates and typo (#12351) --- .../ai-metrics-advisor/samples/javascript/dataFeed.js | 2 +- .../samples/javascript/incidentsAndAlerts.js | 11 +++-------- .../samples/typescript/src/dataFeed.ts | 2 +- .../samples/typescript/src/incidentsAndAlerts.ts | 11 +++-------- .../samples/typescript/src/quickstart.ts | 4 ++-- 5 files changed, 10 insertions(+), 20 deletions(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js index cefca08049a6..3405bd28d069 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/dataFeed.js @@ -159,7 +159,7 @@ async function updateDataFeed(client, dataFeedId) { const updated = await client.updateDataFeed(dataFeedId, patch); console.dir(updated); } catch (err) { - console.log("Error occured when updating data feed"); + console.log("Error occurred when updating data feed"); console.log(err); } } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js index fb482a093dbc..edeb5ff4a67d 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/javascript/incidentsAndAlerts.js @@ -50,7 +50,7 @@ async function listIncidentsForDetectionConfig(client, detectionConfigId) { console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); - console.log(` last occured: ${incident.lastOccurredTime}`); + console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } @@ -141,12 +141,7 @@ async function listAlerts(client, alertConfigId) { console.log(` by pages`); const iterator = client - .listAlerts( - alertConfigId, - new Date("11/01/2020"), - new Date("11/05/2020"), - "AnomalyTime" - ) + .listAlerts(alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime") .byPage({ maxPageSize: 20 }); let result = await iterator.next(); @@ -170,7 +165,7 @@ async function listIncidentsForAlert(client, alertConfigId, alertId) { console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); - console.log(` last occured: ${incident.lastOccurredTime}`); + console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts index bbef1ea3f7a2..b320a63f42a3 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/dataFeed.ts @@ -165,7 +165,7 @@ async function updateDataFeed(client: MetricsAdvisorAdministrationClient, dataFe const updated = await client.updateDataFeed(dataFeedId, patch); console.dir(updated); } catch (err) { - console.log("Error occured when updating data feed"); + console.log("Error occurred when updating data feed"); console.log(err); } } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts index 54c14b680aea..6c0d094d7a06 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/incidentsAndAlerts.ts @@ -54,7 +54,7 @@ async function listIncidentsForDetectionConfig( console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); - console.log(` last occured: ${incident.lastOccurredTime}`); + console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } @@ -153,12 +153,7 @@ async function listAlerts(client: MetricsAdvisorClient, alertConfigId: string) { console.log(` by pages`); const iterator = client - .listAlerts( - alertConfigId, - new Date("11/01/2020"), - new Date("11/05/2020"), - "AnomalyTime" - ) + .listAlerts(alertConfigId, new Date("11/01/2020"), new Date("11/05/2020"), "AnomalyTime") .byPage({ maxPageSize: 20 }); let result = await iterator.next(); @@ -186,7 +181,7 @@ async function listIncidentsForAlert( console.log(` status: ${incident.status}`); console.log(` root dimension key: ${incident.rootDimensionKey}`); console.log(` startTime: ${incident.startTime}`); - console.log(` last occured: ${incident.lastOccurredTime}`); + console.log(` last occurred: ${incident.lastOccurredTime}`); console.log(` detection config id: ${incident.detectionConfigurationId}`); } diff --git a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts index 6c06a025908d..09f710d97b5f 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts +++ b/sdk/metricsadvisor/ai-metrics-advisor/samples/typescript/src/quickstart.ts @@ -178,7 +178,7 @@ async function configureAnomalyDetectionConfiguration( }, description: "Detection configuration description" }; - return await adminClient.createMetricAnomalyDetectionConfiguration(anomalyConfig); + return await adminClient.createDetectionConfig(anomalyConfig); } async function createWebhookHook(adminClient: MetricsAdvisorAdministrationClient) { @@ -230,7 +230,7 @@ async function configureAlertConfiguration( hookIds, description: "Alerting config description" }; - return await adminClient.createAnomalyAlertConfiguration(anomalyAlert); + return await adminClient.createAlertConfig(anomalyAlert); } async function queryAlerts( From 7e9fcae3430a679cf8f0cfdcc08fe43d7576928b Mon Sep 17 00:00:00 2001 From: Ramya Rao Date: Fri, 6 Nov 2020 21:51:50 -0800 Subject: [PATCH 11/35] Update Service Bus migration guide with more pointers, and use similar general text in Event Hubs (#12350) --- sdk/eventhub/event-hubs/migrationguide.md | 10 ++ sdk/servicebus/service-bus/migrationguide.md | 102 +++++++++++++++---- 2 files changed, 90 insertions(+), 22 deletions(-) diff --git a/sdk/eventhub/event-hubs/migrationguide.md b/sdk/eventhub/event-hubs/migrationguide.md index c0d0b8592f88..9a963edefa6c 100644 --- a/sdk/eventhub/event-hubs/migrationguide.md +++ b/sdk/eventhub/event-hubs/migrationguide.md @@ -5,6 +5,16 @@ to migrate their application to V5 of the same library. For users new to the JavaScript SDK for Event Hubs, please see the [readme file for the @azure/event-hubs package](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/eventhub/event-hubs/README.md). +## Migration benefits + +A natural question to ask when considering whether or not to adopt a new version or library is what the benefits of doing so would be. As Azure has matured and been embraced by a more diverse group of developers, we have been focused on learning the patterns and practices to best support developer productivity and to understand the gaps that the JavaScript client libraries have. + +There were several areas of consistent feedback expressed across the Azure client library ecosystem. One of the most important is that the client libraries for different Azure services have not had a consistent approach to organization, naming, and API structure. Additionally, many developers have felt that the learning curve was difficult, and the APIs did not offer a good, approachable, and consistent onboarding story for those learning Azure or exploring a specific Azure service. + +To try and improve the development experience across Azure services, including Event Hubs, a set of uniform [design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) was created for all languages to drive a consistent experience with established API patterns for all services. A set of [TypeScript & JavaScript specific guidelines](https://azure.github.io/azure-sdk/typescript_introduction.html) was also introduced to ensure that these libraries have a natural and idiomatic feel. Further details are available in the guidelines for those interested. + +The new version 5 of the Event Hubs library provides the ability to share in some of the cross-service improvements made to the Azure development experience, such as using the new `@azure/identity` library to share a single authentication between clients and a unified diagnostics pipeline offering a common view of the activities across each of the client libraries. + ## General changes Version 5 of the `@azure/event-hubs` package is a result of our efforts to diff --git a/sdk/servicebus/service-bus/migrationguide.md b/sdk/servicebus/service-bus/migrationguide.md index b9a91db83704..c30e9353ae61 100644 --- a/sdk/servicebus/service-bus/migrationguide.md +++ b/sdk/servicebus/service-bus/migrationguide.md @@ -1,33 +1,84 @@ # Guide to migrate from @azure/service-bus v1 to v7 -This document is intended for users that would like to try out preview 8 -for @azure/service-bus. As the package is in preview, these details might -change as the package is developed before its final release. +This guide is intended to assist in the migration from version 1 of the Service Bus client library `@azure/service-bus` to version 7 of the same library. It will focus on side-by-side comparisons for similar operations between the two packages. -## General changes +Familiarity with the version 1 of the `@azure/service-bus` library is assumed. For those new to the Service Bus client library for JavaScript, please refer to the [README](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/servicebus/service-bus/README.md) and [Service Bus samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/servicebus/service-bus/samples) for the `@azure/service-bus` library rather than this guide. -Version 7 of `@azure/service-bus` provides some "under-the-hood" changes -by standardizing on common infrastructure with `@azure/event-hubs`. This change -brings this package in line with the [Azure SDK Design Guidelines for Typescript](https://azure.github.io/azure-sdk/typescript_introduction.html#design-principles). +## Migration benefits -## API changes from V1 to V7 +A natural question to ask when considering whether or not to adopt a new version or library is what the benefits of doing so would be. As Azure has matured and been embraced by a more diverse group of developers, we have been focused on learning the patterns and practices to best support developer productivity and to understand the gaps that the JavaScript client libraries have. -### Creating ServiceBusClient +There were several areas of consistent feedback expressed across the Azure client library ecosystem. One of the most important is that the client libraries for different Azure services have not had a consistent approach to organization, naming, and API structure. Additionally, many developers have felt that the learning curve was difficult, and the APIs did not offer a good, approachable, and consistent onboarding story for those learning Azure or exploring a specific Azure service. -- `ServiceBusClient` can now be constructed using new(). The static methods to - construct it have been removed. +To try and improve the development experience across Azure services, including Service Bus, a set of uniform [design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) was created for all languages to drive a consistent experience with established API patterns for all services. A set of [TypeScript & JavaScript specific guidelines](https://azure.github.io/azure-sdk/typescript_introduction.html) was also introduced to ensure that these libraries have a natural and idiomatic feel. Further details are available in the guidelines for those interested. - In V1: +The new version 7 of the Service Bus library provides the ability to share in some of the cross-service improvements made to the Azure development experience, such as using the new `@azure/identity` library to share a single authentication between clients and a unified diagnostics pipeline offering a common view of the activities across each of the client libraries. - ```typescript - const serviceBusClient = ServiceBusClient.fromConnectionString("connection string"); - ``` +## Changes in version 7 of the Service Bus library - In V7: +### Client hierarchy - ```typescript - const serviceBusClient = new ServiceBusClient("connection string"); - ``` +In the interest of simplifying the API surface we've made a single top level client called `ServiceBusClient`, rather than one for each of queue, topic, and subscription. This acts as the single entry point in contrast with multiple entry points from before. You can create senders and receivers from this client to the queue/topic/subscription/session of your choice and start sending/receiving messages. + +#### Approachability + +By having a single entry point, the `ServiceBusClient` helps with the discoverability of the API as you can explore all available features through methods from a single client, as opposed to searching through documentation or exploring namespace for the types that you can instantiate. Whether sending or receiving, using sessions or not, you will start your applications by constructing the same client. + +#### Consistency + +We now have methods with similar names, signature and location to create senders and receivers. This provides consistency and predictability on the various features of the library. + +### New features + +We have a variety of new features in the version 7 of the Service Bus library. + +- A new `ServiceBusAdministrationClient` to perform operations like create/get/list/update/delete on queues/topics/subscriptions/rules. These were already available as part of a separate package `@azure/arm-servicebus` that uses Azure Resouce Manager APIs but had the drawback of not supporting connection strings. +- Ability to configure the retry policy used by the operations on the client, sender and receivers. +- Ability to cancel async operations on the client, sender and receivers using the abort signal from `@azure/abort-controller` + +### Client constructors + +While previously, you would use the static method `createFromConnectionString` on the client to create it using connection string, now you can use the client constructor directly. + +In V1: + +```javascript +const serviceBusClient = ServiceBusClient.createFromConnectionString("connection string"); +``` + +In V7: + +```javascript +const serviceBusClient = new ServiceBusClient("connection string"); +``` + +While previously, you would use the static method `createFromAadTokenCredentials` on the client to create it using Azure Active Directory, now you can use the new [@azure/identity](https://www.npmjs.com/package/@azure/identity) library to share a single authentication solution between clients of different Azure services. + +In V1: + +```javascript +const { ServiceBusClient } = require("@azure/service-bus"); +const { interactiveLogin } = require("@azure/ms-rest-nodeauth"); + +const credential = await interactiveLogin({ + tokenAudience: "https://servicebus.azure.net/" +}); + +const serviceBusClient = ServiceBusClient.createFromAadTokenCredentials( + "my-namespace.servicebus.windows.net", + credential +); +``` + +In V7: + +```javascript +const { ServiceBusClient } = require("@azure/service-bus"); +const { DefaultAzureCredential } = require("@azure/identity"); + +const credential = new DefaultAzureCredential(); +const serviceBusClient = new ServiceBusClient("my-namespace.servicebus.windows.net", credential); +``` ### Creating senders and receivers @@ -37,7 +88,7 @@ brings this package in line with the [Azure SDK Design Guidelines for Typescript In V1: ```typescript - const serviceBusClient = ServiceBusClient.fromConnectionString("connection string"); + const serviceBusClient = ServiceBusClient.createFromConnectionString("connection string"); // for queues const queueClient = serviceBusClient.createQueueClient("queue"); @@ -73,9 +124,9 @@ brings this package in line with the [Azure SDK Design Guidelines for Typescript const subscriptionReceiver = serviceBusClient.createReceiver("topic", "subscription"); ``` -- `createSessionReceiver()` method is now split into two async methods `acceptSession()` and `acceptNextSession()` +- The `createReceiver()` overload that took session options is replaced by two async methods `acceptSession()` and `acceptNextSession()` - The promise returned by these methods is resolved when a receiver link has been initialized with a session in the service. - - Prior to v7 `createSessionReceiver()` worked using lazy-initialization, where the + - Prior to v7, `createReceiver()` worked using lazy-initialization, where the receiver link to the session was only initialized when the async methods on the `ServiceBusSessionReceiver` were first called. @@ -108,6 +159,13 @@ brings this package in line with the [Azure SDK Design Guidelines for Typescript }); ``` +### Settling messages + +Previously, the methods to settle messages (`complete()`, `abandon()`, `defer()` and `deadLetter()`) were on the messages themselves. +These have been moved to the receiver in the new version, take the message as input and have the `Message` suffix in their name. +The idea is to have the message represents just the data and not have the responsibility of any operation on the service side. +Additionally, since a message cannot be settled if the receiver that was used to receive it is not alive, tying these operations to the receiver drives the message home better. + ### Rule management - The add/get/remove rule operations on the older `SubscriptionClient` have moved to the new `ServiceBusAdministrationClient` class which will be supporting From 4839eeb669d2657b81a7fe5bf5b8eeb8842f14ee Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Mon, 9 Nov 2020 10:03:48 -0800 Subject: [PATCH 12/35] Increment package version after release of azure-core-http (#12323) --- sdk/core/core-http/CHANGELOG.md | 3 +++ sdk/core/core-http/package.json | 2 +- sdk/core/core-http/src/util/constants.ts | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/sdk/core/core-http/CHANGELOG.md b/sdk/core/core-http/CHANGELOG.md index 38b15e3f4fbe..51a160dee791 100644 --- a/sdk/core/core-http/CHANGELOG.md +++ b/sdk/core/core-http/CHANGELOG.md @@ -1,5 +1,8 @@ # Release History +## 1.2.1 (Unreleased) + + ## 1.2.0 (2020-11-05) - Explicitly set `manual` redirect handling for node fetch. And fixing redirectPipeline [PR 11863](https://github.com/Azure/azure-sdk-for-js/pull/11863) diff --git a/sdk/core/core-http/package.json b/sdk/core/core-http/package.json index 5ba74eb73a2b..9f4bf694f657 100644 --- a/sdk/core/core-http/package.json +++ b/sdk/core/core-http/package.json @@ -2,7 +2,7 @@ "name": "@azure/core-http", "sdk-type": "client", "author": "Microsoft Corporation", - "version": "1.2.0", + "version": "1.2.1", "description": "Isomorphic client Runtime for Typescript/node.js/browser javascript client libraries generated using AutoRest", "tags": [ "isomorphic", diff --git a/sdk/core/core-http/src/util/constants.ts b/sdk/core/core-http/src/util/constants.ts index 316a312ff738..294e1ec7312a 100644 --- a/sdk/core/core-http/src/util/constants.ts +++ b/sdk/core/core-http/src/util/constants.ts @@ -7,7 +7,7 @@ export const Constants = { * @const * @type {string} */ - coreHttpVersion: "1.2.0", + coreHttpVersion: "1.2.1", /** * Specifies HTTP. From c22ad7d3186ce7aad0b07b8db1af3eb9e9509921 Mon Sep 17 00:00:00 2001 From: Ramya Rao Date: Mon, 9 Nov 2020 10:05:10 -0800 Subject: [PATCH 13/35] [Service Bus] Remove Connection Context from ServiceBusMessage (#12398) In #12216, we moved the code to settle a message and renew its lock from the ServiceBusMessageImpl to the ServiceBusReceiver. After this move, the only dependency left on the ConnectionContext in the ServiceBusMessageImpl is for the DataTransformer. This PR updates the ServiceBusMessage constructor to take the DataTransformer instead of the ConnectionContext and thus remove this dependency altogether. This closes #9944 as we no longer need to track the context or the receiver on the message. This closes #10620 as well. Since the context is not being tracked on the message anymore, it does not matter that the data transformer is tracked on the context. --- .../service-bus/src/core/batchingReceiver.ts | 2 +- .../service-bus/src/core/managementClient.ts | 2 +- .../service-bus/src/core/streamingReceiver.ts | 2 +- .../service-bus/src/serviceBusMessage.ts | 7 +++---- .../service-bus/src/session/messageSession.ts | 2 +- .../test/internal/serviceBusMessage.spec.ts | 19 ++++++++----------- 6 files changed, 15 insertions(+), 19 deletions(-) diff --git a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts index cfb5753ee968..0b65e9778789 100644 --- a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts @@ -253,7 +253,7 @@ export class BatchingReceiverLite { this._createServiceBusMessage = (context: MessageAndDelivery) => { return new ServiceBusMessageImpl( - _connectionContext, + _connectionContext.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/src/core/managementClient.ts b/sdk/servicebus/service-bus/src/core/managementClient.ts index a16bda0a0438..b1cc4e0dd928 100644 --- a/sdk/servicebus/service-bus/src/core/managementClient.ts +++ b/sdk/servicebus/service-bus/src/core/managementClient.ts @@ -802,7 +802,7 @@ export class ManagementClient extends LinkEntity { for (const msg of messages) { const decodedMessage = RheaMessageUtil.decode(msg.message); const message = new ServiceBusMessageImpl( - this._context, + this._context.dataTransformer, decodedMessage as any, { tag: msg["lock-token"] } as any, false, diff --git a/sdk/servicebus/service-bus/src/core/streamingReceiver.ts b/sdk/servicebus/service-bus/src/core/streamingReceiver.ts index 5b71c73ea993..f49e4790dcf5 100644 --- a/sdk/servicebus/service-bus/src/core/streamingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/streamingReceiver.ts @@ -222,7 +222,7 @@ export class StreamingReceiver extends MessageReceiver { } const bMessage: ServiceBusMessageImpl = new ServiceBusMessageImpl( - this._context, + this._context.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/src/serviceBusMessage.ts b/sdk/servicebus/service-bus/src/serviceBusMessage.ts index 6f067e93d181..91a7eb44650f 100644 --- a/sdk/servicebus/service-bus/src/serviceBusMessage.ts +++ b/sdk/servicebus/service-bus/src/serviceBusMessage.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { AmqpAnnotatedMessage, Constants } from "@azure/core-amqp"; +import { AmqpAnnotatedMessage, Constants, DataTransformer } from "@azure/core-amqp"; import { Buffer } from "buffer"; import Long from "long"; import { @@ -11,7 +11,6 @@ import { uuid_to_string, Message as RheaMessage } from "rhea-promise"; -import { ConnectionContext } from "./connectionContext"; import { messageLogger as logger } from "./log"; import { ReceiveMode } from "./models"; import { reorderLockToken } from "./util/utils"; @@ -770,7 +769,7 @@ export class ServiceBusMessageImpl implements ServiceBusReceivedMessage { * @internal */ constructor( - private readonly _context: ConnectionContext, + private readonly _dataTransformer: DataTransformer, msg: RheaMessage, delivery: Delivery, shouldReorderLockToken: boolean, @@ -783,7 +782,7 @@ export class ServiceBusMessageImpl implements ServiceBusReceivedMessage { this.lockToken = undefined; } if (msg.body) { - this.body = this._context.dataTransformer.decode(msg.body); + this.body = this._dataTransformer.decode(msg.body); } // TODO: _amqpAnnotatedMessage is already being populated in fromRheaMessage(), no need to do it twice this._amqpAnnotatedMessage = AmqpAnnotatedMessage.fromRheaMessage(msg); diff --git a/sdk/servicebus/service-bus/src/session/messageSession.ts b/sdk/servicebus/service-bus/src/session/messageSession.ts index 2c0e5ec83aef..4b18c09d03a5 100644 --- a/sdk/servicebus/service-bus/src/session/messageSession.ts +++ b/sdk/servicebus/service-bus/src/session/messageSession.ts @@ -621,7 +621,7 @@ export class MessageSession extends LinkEntity { } const bMessage = new ServiceBusMessageImpl( - this._context, + this._context.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts b/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts index 366d8af34576..f6afb3c727e3 100644 --- a/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts +++ b/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts @@ -2,7 +2,6 @@ // Licensed under the MIT license. import { ServiceBusMessageImpl } from "../../src/serviceBusMessage"; -import { ConnectionContext } from "../../src/connectionContext"; import { Delivery, uuid_to_string, @@ -11,15 +10,13 @@ import { Message as RheaMessage } from "rhea-promise"; import chai from "chai"; -import { Constants } from "@azure/core-amqp"; +import { Constants, DataTransformer } from "@azure/core-amqp"; const assert = chai.assert; -const fakeContext = { - dataTransformer: { - encode: (data) => data, - decode: (data) => data - } -} as ConnectionContext; +const fakeDataTransformer = { + encode: (data) => data, + decode: (data) => data +} as DataTransformer; const fakeDelivery = {} as Delivery; describe("ServiceBusMessageImpl LockToken unit tests", () => { @@ -38,7 +35,7 @@ describe("ServiceBusMessageImpl LockToken unit tests", () => { it("Lock token in peekLock mode", () => { const sbMessage = new ServiceBusMessageImpl( - fakeContext, + fakeDataTransformer, amqpMessage, { tag: fakeDeliveryTag } as Delivery, false, @@ -50,7 +47,7 @@ describe("ServiceBusMessageImpl LockToken unit tests", () => { it("Lock token in receiveAndDelete mode", () => { const sbMessage = new ServiceBusMessageImpl( - fakeContext, + fakeDataTransformer, amqpMessage, { tag: fakeDeliveryTag } as Delivery, false, @@ -99,7 +96,7 @@ describe("ServiceBusMessageImpl AmqpAnnotations unit tests", () => { }; const sbMessage = new ServiceBusMessageImpl( - fakeContext, + fakeDataTransformer, amqpMessage, fakeDelivery, false, From 490e97a53399b1d61c5443c7f1b3bee7710bc8c8 Mon Sep 17 00:00:00 2001 From: Sarangan Rajamanickam Date: Mon, 9 Nov 2020 18:45:28 +0000 Subject: [PATCH 14/35] QnAMaker SDK Release (#12311) * Revert "[data-plane] JS: 'Release for QnA Maker 2020-11-02' (#12261)" This reverts commit 65e6460fd54f60a8d879d0def40e15663c201d2f. * Regenerated SDK for the preview 5.0 version --- .../cognitiveservices-qnamaker/package.json | 2 +- .../cognitiveservices-qnamaker/rollup.config.js | 4 ++-- .../src/models/alterationsMappers.ts | 4 ++-- .../src/models/endpointKeysMappers.ts | 4 ++-- .../src/models/endpointSettingsMappers.ts | 4 ++-- .../cognitiveservices-qnamaker/src/models/index.ts | 4 ++-- .../src/models/knowledgebaseMappers.ts | 4 ++-- .../cognitiveservices-qnamaker/src/models/mappers.ts | 4 ++-- .../src/models/operationsMappers.ts | 4 ++-- .../cognitiveservices-qnamaker/src/models/parameters.ts | 5 ++--- .../src/operations/alterations.ts | 5 ++--- .../src/operations/endpointKeys.ts | 5 ++--- .../src/operations/endpointSettings.ts | 5 ++--- .../cognitiveservices-qnamaker/src/operations/index.ts | 5 ++--- .../src/operations/knowledgebase.ts | 8 ++++---- .../src/operations/operations.ts | 8 ++++---- .../cognitiveservices-qnamaker/src/qnAMakerClient.ts | 5 ++--- .../src/qnAMakerClientContext.ts | 7 +++---- .../cognitiveservices-qnamaker/swagger/readme.md | 4 +++- 19 files changed, 43 insertions(+), 48 deletions(-) diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/package.json b/sdk/cognitiveservices/cognitiveservices-qnamaker/package.json index 5c61d45ba5b8..488f10f02e93 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/package.json +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/package.json @@ -2,7 +2,7 @@ "name": "@azure/cognitiveservices-qnamaker", "author": "Microsoft Corporation", "description": "QnAMakerClient Library with typescript type definitions for node.js and browser.", - "version": "4.0.0", + "version": "3.2.0", "dependencies": { "@azure/ms-rest-js": "^2.0.4", "tslib": "^1.10.0" diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/rollup.config.js b/sdk/cognitiveservices/cognitiveservices-qnamaker/rollup.config.js index aa740262d6cc..72c998843834 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/rollup.config.js +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/rollup.config.js @@ -21,8 +21,8 @@ const config = { "@azure/ms-rest-azure-js": "msRestAzure" }, banner: `/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/alterationsMappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/alterationsMappers.ts index bb61c2cf1a47..5222a6daad5a 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/alterationsMappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/alterationsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointKeysMappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointKeysMappers.ts index b236c184044f..40cfa78ae4bc 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointKeysMappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointKeysMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointSettingsMappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointSettingsMappers.ts index 41a5e8575e4f..094d973ef5ef 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointSettingsMappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/endpointSettingsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/index.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/index.ts index fb8ebf4aafaa..4812cbc54ea3 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/index.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/index.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/knowledgebaseMappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/knowledgebaseMappers.ts index 720fade307f8..a034bb7cce6a 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/knowledgebaseMappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/knowledgebaseMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/mappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/mappers.ts index 00ded8ef31cd..9924b290f994 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/mappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/mappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/operationsMappers.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/operationsMappers.ts index 7887207338c4..5034f2601aee 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/operationsMappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/operationsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/parameters.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/parameters.ts index 6030e4432a1e..9702306b51f2 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/parameters.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/models/parameters.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/alterations.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/alterations.ts index 19f9d2691467..2460696a7eea 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/alterations.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/alterations.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointKeys.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointKeys.ts index 99dcc6869859..b64d18803ddc 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointKeys.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointKeys.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointSettings.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointSettings.ts index bd092c5dd289..dc3a35dda12f 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointSettings.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/endpointSettings.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/index.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/index.ts index e67a8e209eb3..aaa6bf49d884 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/index.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/index.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/knowledgebase.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/knowledgebase.ts index 7d9c688930d2..28416e55e0c1 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/knowledgebase.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/knowledgebase.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -438,7 +437,8 @@ const updateOperationSpec: msRest.OperationSpec = { headersMapper: Mappers.KnowledgebaseUpdateHeaders }, default: { - bodyMapper: Mappers.ErrorResponse + bodyMapper: Mappers.ErrorResponse, + headersMapper: Mappers.KnowledgebaseUpdateHeaders } }, serializer diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/operations.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/operations.ts index 09769c778f8e..0623c1cd6650 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/operations.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/operations/operations.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -70,7 +69,8 @@ const getDetailsOperationSpec: msRest.OperationSpec = { headersMapper: Mappers.OperationsGetDetailsHeaders }, default: { - bodyMapper: Mappers.ErrorResponse + bodyMapper: Mappers.ErrorResponse, + headersMapper: Mappers.OperationsGetDetailsHeaders } }, serializer diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClient.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClient.ts index 841765040e39..5690ed0a3612 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClient.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClient.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClientContext.ts b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClientContext.ts index 06f756bdace0..00597b9a5f08 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClientContext.ts +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/src/qnAMakerClientContext.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -11,7 +10,7 @@ import * as msRest from "@azure/ms-rest-js"; const packageName = "@azure/cognitiveservices-qnamaker"; -const packageVersion = "4.0.0"; +const packageVersion = "3.2.0"; export class QnAMakerClientContext extends msRest.ServiceClient { endpoint: string; diff --git a/sdk/cognitiveservices/cognitiveservices-qnamaker/swagger/readme.md b/sdk/cognitiveservices/cognitiveservices-qnamaker/swagger/readme.md index bfc9011e99ab..362708b6d1d0 100644 --- a/sdk/cognitiveservices/cognitiveservices-qnamaker/swagger/readme.md +++ b/sdk/cognitiveservices/cognitiveservices-qnamaker/swagger/readme.md @@ -9,6 +9,8 @@ add-credentials: true openapi-type: data-plane license-header: MICROSOFT_MIT_NO_VERSION input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cognitiveservices/data-plane/QnAMaker/preview/v5.0-preview.1/QnAMaker.json +use-extension: + "@microsoft.azure/autorest.typescript": "4.4.4" ``` ## TypeScript @@ -17,7 +19,7 @@ These settings apply only when `--typescript` is specified on the command line. ```yaml $(typescript) typescript: - package-version: 4.0.0 + package-version: 3.2.0 package-name: "@azure/cognitiveservices-qnamaker" output-folder: .. azure-arm: false From 3e56254dc85df46eff57ef021a35141f1a54a7fc Mon Sep 17 00:00:00 2001 From: Steve Faulkner Date: Mon, 9 Nov 2020 13:21:06 -0600 Subject: [PATCH 15/35] Fix for atob not loading in React Native (#12412) For some reason React native always tries to load .browser for `atob` so as workaround we can put the polyfill in the browser file. --- sdk/cosmosdb/cosmos/src/utils/atob.browser.ts | 46 ++++++++++++++++++- sdk/cosmosdb/cosmos/src/utils/atob.native.ts | 43 ----------------- 2 files changed, 44 insertions(+), 45 deletions(-) delete mode 100644 sdk/cosmosdb/cosmos/src/utils/atob.native.ts diff --git a/sdk/cosmosdb/cosmos/src/utils/atob.browser.ts b/sdk/cosmosdb/cosmos/src/utils/atob.browser.ts index 766fc839b4ae..286f50149d60 100644 --- a/sdk/cosmosdb/cosmos/src/utils/atob.browser.ts +++ b/sdk/cosmosdb/cosmos/src/utils/atob.browser.ts @@ -1,8 +1,50 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +let safeatob: any; + +// base64 character set, plus padding character (=) +const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +// Regular expression to check formal correctness of base64 encoded strings +const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; + if ("function" !== typeof atob) { - throw new Error("Your browser environment is missing the global `atob` function"); + // atob implementation for React Native + safeatob = (str: string) => { + // atob can work with strings with whitespaces, even inside the encoded part, + // but only \t, \n, \f, \r and ' ', which can be stripped. + str = String(str).replace(/[\t\n\f\r ]+/g, ""); + if (!b64re.test(str)) { + throw new TypeError( + "Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded." + ); + } + + // Adding the padding if missing, for simplicity + str += "==".slice(2 - (str.length & 3)); + let bitmap; + let result = ""; + let r1; + let r2; + let i = 0; + for (; i < str.length; ) { + bitmap = + (b64.indexOf(str.charAt(i++)) << 18) | + (b64.indexOf(str.charAt(i++)) << 12) | + ((r1 = b64.indexOf(str.charAt(i++))) << 6) | + (r2 = b64.indexOf(str.charAt(i++))); + + result += + r1 === 64 + ? String.fromCharCode((bitmap >> 16) & 255) + : r2 === 64 + ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255) + : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255); + } + return result; + }; +} else { + safeatob = atob; } -export default atob; +export default safeatob; diff --git a/sdk/cosmosdb/cosmos/src/utils/atob.native.ts b/sdk/cosmosdb/cosmos/src/utils/atob.native.ts deleted file mode 100644 index 966af92ce53f..000000000000 --- a/sdk/cosmosdb/cosmos/src/utils/atob.native.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -// atob implementation for React Native - -// base64 character set, plus padding character (=) -const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -// Regular expression to check formal correctness of base64 encoded strings -const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; - -export function atob(str: string) { - // atob can work with strings with whitespaces, even inside the encoded part, - // but only \t, \n, \f, \r and ' ', which can be stripped. - str = String(str).replace(/[\t\n\f\r ]+/g, ""); - if (!b64re.test(str)) { - throw new TypeError( - "Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded." - ); - } - - // Adding the padding if missing, for simplicity - str += "==".slice(2 - (str.length & 3)); - let bitmap; - let result = ""; - let r1; - let r2; - let i = 0; - for (; i < str.length; ) { - bitmap = - (b64.indexOf(str.charAt(i++)) << 18) | - (b64.indexOf(str.charAt(i++)) << 12) | - ((r1 = b64.indexOf(str.charAt(i++))) << 6) | - (r2 = b64.indexOf(str.charAt(i++))); - - result += - r1 === 64 - ? String.fromCharCode((bitmap >> 16) & 255) - : r2 === 64 - ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255) - : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255); - } - return result; -} From 1e8ad241670c74a2a5f054060441644c31959fb0 Mon Sep 17 00:00:00 2001 From: Harsha Nalluru Date: Mon, 9 Nov 2020 11:43:04 -0800 Subject: [PATCH 16/35] [Core AMQP] Do not stringify entityPath for `undefined` (#12321) Fixes https://github.com/Azure/azure-sdk-for-js/issues/8105 and https://github.com/Azure/azure-sdk-for-js/issues/11155 --- sdk/core/core-amqp/CHANGELOG.md | 5 +++ sdk/core/core-amqp/package.json | 6 +-- .../src/connectionConfig/connectionConfig.ts | 4 +- sdk/core/core-amqp/test/config.spec.ts | 40 +++++++++++++++++++ .../service-bus/src/constructorHelpers.ts | 16 -------- .../test/internal/serviceBusClient.spec.ts | 36 ++++------------- 6 files changed, 59 insertions(+), 48 deletions(-) diff --git a/sdk/core/core-amqp/CHANGELOG.md b/sdk/core/core-amqp/CHANGELOG.md index cd01d485a28e..56f53b4b837c 100644 --- a/sdk/core/core-amqp/CHANGELOG.md +++ b/sdk/core/core-amqp/CHANGELOG.md @@ -2,6 +2,11 @@ ## 2.0.0 (Unreleased) +### Breaking Changes + +- Previously, `ConnectionConfig.validate()` overridden entityPath if `undefined` with `String(undefined) = "undefined"`. This has been updated to retain `undefined` in the validation. + [PR 12321](https://github.com/Azure/azure-sdk-for-js/pull/12321) + ## 2.0.0-beta.1 (2020-11-03) - `AmqpAnnotatedMessage` interface that closely represents the AMQP annotated message from the [AMQP spec](https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-messaging-v1.0-os.html#section-message-format) has been added. New `AmqpMessageHeaders` and `AmqpMessageProperties` interfaces(properties with camelCasing) have been added in the place of re-exports from "rhea" library(properties with snake_casing). diff --git a/sdk/core/core-amqp/package.json b/sdk/core/core-amqp/package.json index c9251fc6af79..1238ee543b11 100644 --- a/sdk/core/core-amqp/package.json +++ b/sdk/core/core-amqp/package.json @@ -51,9 +51,9 @@ "lint": "eslint package.json api-extractor.json src test --ext .ts -f html -o core-amqp-lintReport.html || exit 0", "pack": "npm pack 2>&1", "prebuild": "npm run clean", - "test:browser": "npm run build:test && npm run unit-test:browser && npm run integration-test:browser", - "test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node", - "test": "npm run build:test && npm run unit-test && npm run integration-test", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser", + "test:node": "npm run clean && npm run build:test && npm run unit-test:node", + "test": "npm run test:node && npm run test:browser", "unit-test:browser": "karma start --single-run", "unit-test:node": "cross-env TS_NODE_FILES=true TS_NODE_COMPILER_OPTIONS=\"{\\\"module\\\":\\\"commonjs\\\"}\" nyc --reporter=lcov --reporter=text-lcov mocha -r ts-node/register -t 50000 --reporter ../../../common/tools/mocha-multi-reporter.js ./test/**/*.spec.ts", "unit-test": "npm run unit-test:node && npm run unit-test:browser" diff --git a/sdk/core/core-amqp/src/connectionConfig/connectionConfig.ts b/sdk/core/core-amqp/src/connectionConfig/connectionConfig.ts index 057fca85a080..0911f8c1c331 100644 --- a/sdk/core/core-amqp/src/connectionConfig/connectionConfig.ts +++ b/sdk/core/core-amqp/src/connectionConfig/connectionConfig.ts @@ -134,7 +134,9 @@ export const ConnectionConfig = { if (options.isEntityPathRequired && !config.entityPath) { throw new TypeError("Missing 'entityPath' in configuration"); } - config.entityPath = String(config.entityPath); + if (config.entityPath != undefined) { + config.entityPath = String(config.entityPath); + } if (!isSharedAccessSignature(config.connectionString)) { if (!config.sharedAccessKeyName) { diff --git a/sdk/core/core-amqp/test/config.spec.ts b/sdk/core/core-amqp/test/config.spec.ts index a87030602e38..0eb733ec9e2c 100644 --- a/sdk/core/core-amqp/test/config.spec.ts +++ b/sdk/core/core-amqp/test/config.spec.ts @@ -194,6 +194,46 @@ describe("ConnectionConfig", function() { done(); }); }); + + describe("EntityPath Validation", function() { + const connectionString = ` + Endpoint=sb://hostname.servicebus.windows.net/; + SharedAccessKeyName=sakName; + SharedAccessKey=sakName; + EntityPath=ep; + `; + const config: ConnectionConfig = { + connectionString: connectionString, + endpoint: "sb://hostname.servicebus.windows.net/", + host: "hostname.servicebus.windows.net/", + sharedAccessKeyName: "sakName", + sharedAccessKey: "abcd" + }; + + it("undefined is not stringified", () => { + config.entityPath = undefined; + ConnectionConfig.validate(config); + should.equal(config.entityPath, undefined, `EntityPath is not undefined`); + }); + + it("null is not stringified", () => { + config.entityPath = null as any; + ConnectionConfig.validate(config); + should.equal(config.entityPath, null, `EntityPath is not null`); + }); + + it("number is stringified", () => { + config.entityPath = 3 as any; + ConnectionConfig.validate(config); + should.equal(config.entityPath, "3", `EntityPath is not stringified`); + }); + + it("string is unchanged", () => { + config.entityPath = "entityPath"; + ConnectionConfig.validate(config); + should.equal(config.entityPath, "entityPath", `EntityPath is not a string`); + }); + }); }); describe("SharedAccessSignature", () => { diff --git a/sdk/servicebus/service-bus/src/constructorHelpers.ts b/sdk/servicebus/service-bus/src/constructorHelpers.ts index 99c7d1186e8b..c4fbb5fd16e8 100644 --- a/sdk/servicebus/service-bus/src/constructorHelpers.ts +++ b/sdk/servicebus/service-bus/src/constructorHelpers.ts @@ -26,21 +26,6 @@ export interface ServiceBusClientOptions { userAgentOptions?: UserAgentOptions; } -/** - * @internal - * @ignore - * - * @param {ConnectionConfig} config - */ -function validate(config: ConnectionConfig) { - // TODO: workaround - core-amqp's validate string-izes "undefined" - // the timing of this particular call happens in a spot where we might not have an - // entity path so it's perfectly legitimate for it to be empty. - config.entityPath = config.entityPath ?? ""; - - ConnectionConfig.validate(config); -} - /** * @internal * @ignore @@ -60,7 +45,6 @@ export function createConnectionContext( config.webSocketEndpointPath = "$servicebus/websocket"; config.webSocketConstructorOptions = options?.webSocketOptions?.webSocketConstructorOptions; - validate(config); return ConnectionContext.create(config, credential, options); } diff --git a/sdk/servicebus/service-bus/test/internal/serviceBusClient.spec.ts b/sdk/servicebus/service-bus/test/internal/serviceBusClient.spec.ts index 4041acfdd8a5..a8cee2d1bb20 100644 --- a/sdk/servicebus/service-bus/test/internal/serviceBusClient.spec.ts +++ b/sdk/servicebus/service-bus/test/internal/serviceBusClient.spec.ts @@ -51,7 +51,10 @@ describe("serviceBusClient unit tests", () => { client["_connectionContext"] = createConnectionContextForTestsWithSessionId( "a session id", - origConnectionContext.config + { + ...origConnectionContext.config, + entityPath: testEntity.topic ? testEntity.topic : testEntity.queue + } ); let sessionReceiver: ServiceBusSessionReceiver; @@ -102,10 +105,10 @@ describe("serviceBusClient unit tests", () => { const origConnectionContext = client["_connectionContext"]; - client["_connectionContext"] = createConnectionContextForTestsWithSessionId( - "session id", - origConnectionContext.config - ); + client["_connectionContext"] = createConnectionContextForTestsWithSessionId("session id", { + ...origConnectionContext.config, + entityPath: testEntity.topic ? testEntity.topic : testEntity.queue + }); let sessionReceiver: ServiceBusSessionReceiver; @@ -317,16 +320,6 @@ describe("serviceBusClient unit tests", () => { }); validateWebsocketInfo(connectionContext, options); }); - - it("undefined entity path is translated to ''", () => { - const connString = "Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c;"; - const connectionContext = createConnectionContextForConnectionString(connString, {}); - assert.equal( - connectionContext.config.entityPath, - "", - "Unexpected entityPath in the connection config" - ); - }); }); describe("createConnectionContextForTokenCredential", () => { @@ -345,19 +338,6 @@ describe("serviceBusClient unit tests", () => { ); validateWebsocketInfo(connectionContext, options); }); - - it("undefined entity path is translated to ''", () => { - const connectionContext = createConnectionContextForTokenCredential( - pseudoTokenCred, - endpoint, - {} - ); - assert.equal( - connectionContext.config.entityPath, - "", - "Unexpected entityPath in the connection config" - ); - }); }); }); }); From b8a7759d34f6efea404b9a56f76a765a4fcfb8d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Rodr=C3=ADguez?= Date: Mon, 9 Nov 2020 17:35:12 -0500 Subject: [PATCH 17/35] [Identity] Success logging (Both in Interactive and in DeviceCode) (#11807) This is a very small issue addressing #11672. When I made #11672 I conflated two different issues related to success logging of Identity credentials (at least definitely in my mind I did conflate these two). Since the fix to these issues is very small, in number of lines changed, I thought it would be ok to make a single pull request to address them both. In this pull request, I have: - Changed the success message of InteractiveBrowserCredential to `Authentication Complete. You can close the browser and return to the application.`. - Changed the success logging message of `DeviceCodeCredential` to be similar to: `DeviceCodeCredential succeeded. Scopes: {1} ExpiresOn: {3}`. - When I did this, I decided to change the other logging messages to make them consistent. **Important:** I decided to re-use the existing logging tools, so the messages are more like `ClientCertificateCredential => getToke() => SUCCESS. Scopes: {1}` If approved, Fixes #11672 Feedback appreciated! --- .../authorizationCodeCredential.browser.ts | 4 ++-- .../authorizationCodeCredential.ts | 2 +- .../credentials/azureCliCredential.browser.ts | 4 ++-- .../src/credentials/azureCliCredential.ts | 10 ++++----- .../src/credentials/chainedTokenCredential.ts | 4 ++-- .../clientCertificateCredential.browser.ts | 4 ++-- .../clientCertificateCredential.ts | 4 ++-- .../src/credentials/clientSecretCredential.ts | 4 ++-- .../deviceCodeCredential.browser.ts | 4 ++-- .../src/credentials/deviceCodeCredential.ts | 18 ++++++++++----- .../environmentCredential.browser.ts | 4 ++-- .../src/credentials/environmentCredential.ts | 4 ++-- .../interactiveBrowserCredential.browser.ts | 9 ++++---- .../interactiveBrowserCredential.ts | 22 +++++++++---------- .../managedIdentityCredential/arcMsi.ts | 2 +- .../managedIdentityCredential/imdsMsi.ts | 6 ++--- .../index.browser.ts | 4 ++-- .../managedIdentityCredential/index.ts | 6 ++--- .../credentials/usernamePasswordCredential.ts | 2 +- .../visualStudioCodeCredential.browser.ts | 4 ++-- .../credentials/visualStudioCodeCredential.ts | 6 ++--- .../identity/src/util/checkTenantId.ts | 2 +- sdk/identity/identity/src/util/logging.ts | 10 ++++++--- .../identity/test/internal/logger.spec.ts | 17 ++++++++------ 24 files changed, 84 insertions(+), 72 deletions(-) diff --git a/sdk/identity/identity/src/credentials/authorizationCodeCredential.browser.ts b/sdk/identity/identity/src/credentials/authorizationCodeCredential.browser.ts index a15d10568e4a..44e9169b30b0 100644 --- a/sdk/identity/identity/src/credentials/authorizationCodeCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/authorizationCodeCredential.browser.ts @@ -27,12 +27,12 @@ export class AuthorizationCodeCredential implements TokenCredential { options?: TokenCredentialOptions ); constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts b/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts index f8a545d0700c..8ea270ac6e75 100644 --- a/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts +++ b/sdk/identity/identity/src/credentials/authorizationCodeCredential.ts @@ -197,7 +197,7 @@ export class AuthorizationCodeCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); throw err; } finally { span.end(); diff --git a/sdk/identity/identity/src/credentials/azureCliCredential.browser.ts b/sdk/identity/identity/src/credentials/azureCliCredential.browser.ts index 0392517e365e..fb9259da24f3 100644 --- a/sdk/identity/identity/src/credentials/azureCliCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/azureCliCredential.browser.ts @@ -9,12 +9,12 @@ const logger = credentialLogger("AzureCliCredential"); export class AzureCliCredential implements TokenCredential { constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/azureCliCredential.ts b/sdk/identity/identity/src/credentials/azureCliCredential.ts index fbd8d8b2d2ed..f740bc1bbb32 100644 --- a/sdk/identity/identity/src/credentials/azureCliCredential.ts +++ b/sdk/identity/identity/src/credentials/azureCliCredential.ts @@ -75,7 +75,7 @@ export class AzureCliCredential implements TokenCredential { // Check to make sure the scope we get back is a valid scope if (!scope.match(/^[0-9a-zA-Z-.:/]+$/)) { const error = new Error("Invalid scope was specified by the user or calling client"); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } @@ -93,17 +93,17 @@ export class AzureCliCredential implements TokenCredential { const error = new CredentialUnavailable( "Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'." ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } else if (isLoginError) { const error = new CredentialUnavailable( "Please run 'az login' from a command prompt to authenticate before using this credential." ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } const error = new CredentialUnavailable(obj.stderr); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } else { responseData = obj.stdout; @@ -126,7 +126,7 @@ export class AzureCliCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); reject(err); }); }); diff --git a/sdk/identity/identity/src/credentials/chainedTokenCredential.ts b/sdk/identity/identity/src/credentials/chainedTokenCredential.ts index d911da9949c9..e606e8d5b505 100644 --- a/sdk/identity/identity/src/credentials/chainedTokenCredential.ts +++ b/sdk/identity/identity/src/credentials/chainedTokenCredential.ts @@ -67,7 +67,7 @@ export class ChainedTokenCredential implements TokenCredential { if (err instanceof CredentialUnavailable) { errors.push(err); } else { - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); throw err; } } @@ -79,7 +79,7 @@ export class ChainedTokenCredential implements TokenCredential { code: CanonicalCode.UNAUTHENTICATED, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); throw err; } diff --git a/sdk/identity/identity/src/credentials/clientCertificateCredential.browser.ts b/sdk/identity/identity/src/credentials/clientCertificateCredential.browser.ts index 1bfaaab5a8be..0f772315c5e9 100644 --- a/sdk/identity/identity/src/credentials/clientCertificateCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/clientCertificateCredential.browser.ts @@ -11,12 +11,12 @@ const logger = credentialLogger("ClientCertificateCredential"); export class ClientCertificateCredential implements TokenCredential { constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/clientCertificateCredential.ts b/sdk/identity/identity/src/credentials/clientCertificateCredential.ts index 99c99c55c6d4..d368cac22751 100644 --- a/sdk/identity/identity/src/credentials/clientCertificateCredential.ts +++ b/sdk/identity/identity/src/credentials/clientCertificateCredential.ts @@ -85,7 +85,7 @@ export class ClientCertificateCredential implements TokenCredential { const error = new Error( "The file at the specified path does not contain a PEM-encoded certificate." ); - logger.info(formatError(error)); + logger.info(formatError("", error)); throw error; } @@ -187,7 +187,7 @@ export class ClientCertificateCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError("", err)); throw err; } finally { span.end(); diff --git a/sdk/identity/identity/src/credentials/clientSecretCredential.ts b/sdk/identity/identity/src/credentials/clientSecretCredential.ts index 635f2ef3d158..0ff52a238d48 100644 --- a/sdk/identity/identity/src/credentials/clientSecretCredential.ts +++ b/sdk/identity/identity/src/credentials/clientSecretCredential.ts @@ -7,7 +7,7 @@ import { TokenCredentialOptions, IdentityClient } from "../client/identityClient import { createSpan } from "../util/tracing"; import { AuthenticationErrorName } from "../client/errors"; import { CanonicalCode } from "@opentelemetry/api"; -import { credentialLogger, formatSuccess } from "../util/logging"; +import { credentialLogger, formatError, formatSuccess } from "../util/logging"; import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint"; const logger = credentialLogger("ClientSecretCredential"); @@ -97,7 +97,7 @@ export class ClientSecretCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(err); + logger.getToken.info(formatError(scopes, err)); throw err; } finally { span.end(); diff --git a/sdk/identity/identity/src/credentials/deviceCodeCredential.browser.ts b/sdk/identity/identity/src/credentials/deviceCodeCredential.browser.ts index 0b7ff7f9b716..2a8b2ac5ef25 100644 --- a/sdk/identity/identity/src/credentials/deviceCodeCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/deviceCodeCredential.browser.ts @@ -9,12 +9,12 @@ const logger = credentialLogger("DeviceCodeCredential"); export class DeviceCodeCredential implements TokenCredential { constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/deviceCodeCredential.ts b/sdk/identity/identity/src/credentials/deviceCodeCredential.ts index 0b080249f969..8d1707190ac5 100644 --- a/sdk/identity/identity/src/credentials/deviceCodeCredential.ts +++ b/sdk/identity/identity/src/credentials/deviceCodeCredential.ts @@ -113,7 +113,10 @@ export class DeviceCodeCredential implements TokenCredential { * @param options The options used to configure any requests this * TokenCredential implementation might make. */ - getToken(scopes: string | string[], options?: GetTokenOptions): Promise { + async getToken( + scopes: string | string[], + options?: GetTokenOptions + ): Promise { const { span } = createSpan("DeviceCodeCredential-getToken", options); const scopeArray = typeof scopes === "object" ? scopes : [scopes]; @@ -123,12 +126,14 @@ export class DeviceCodeCredential implements TokenCredential { scopes: scopeArray }; - logger.info("Sending devicecode request"); + logger.info(`DeviceCodeCredential invoked. Scopes: ${scopeArray.join(", ")}`); - return this.msalClient.acquireTokenFromCache(scopeArray).catch((e) => { + return this.msalClient.acquireTokenFromCache(scopeArray).catch(async (e) => { if (e instanceof AuthenticationRequired) { try { - return this.acquireTokenByDeviceCode(deviceCodeRequest, scopeArray); + const token = await this.acquireTokenByDeviceCode(deviceCodeRequest, scopeArray); + logger.getToken.info(formatSuccess(scopeArray)); + return token; } catch (err) { const code = err.name === AuthenticationErrorName @@ -138,7 +143,7 @@ export class DeviceCodeCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopeArray, err)); throw err; } finally { span.end(); @@ -155,9 +160,10 @@ export class DeviceCodeCredential implements TokenCredential { ): Promise { try { const deviceResponse = await this.msalClient.acquireTokenByDeviceCode(deviceCodeRequest); + const expiresOnTimestamp = deviceResponse.expiresOn.getTime(); logger.getToken.info(formatSuccess(scopes)); return { - expiresOnTimestamp: deviceResponse.expiresOn.getTime(), + expiresOnTimestamp, token: deviceResponse.accessToken }; } catch (error) { diff --git a/sdk/identity/identity/src/credentials/environmentCredential.browser.ts b/sdk/identity/identity/src/credentials/environmentCredential.browser.ts index fef81c8658f1..c01020cd49ed 100644 --- a/sdk/identity/identity/src/credentials/environmentCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/environmentCredential.browser.ts @@ -11,12 +11,12 @@ const logger = credentialLogger("EnvironmentCredential"); export class EnvironmentCredential implements TokenCredential { constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/environmentCredential.ts b/sdk/identity/identity/src/credentials/environmentCredential.ts index 471bf26c745f..0c1dc69068ef 100644 --- a/sdk/identity/identity/src/credentials/environmentCredential.ts +++ b/sdk/identity/identity/src/credentials/environmentCredential.ts @@ -144,7 +144,7 @@ export class EnvironmentCredential implements TokenCredential { .split("More details:") .join("") }); - logger.getToken.info(formatError(authenticationError)); + logger.getToken.info(formatError(scopes, authenticationError)); throw authenticationError; } finally { span.end(); @@ -158,7 +158,7 @@ export class EnvironmentCredential implements TokenCredential { const error = new CredentialUnavailable( "EnvironmentCredential is unavailable. Environment variables are not fully configured." ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } } diff --git a/sdk/identity/identity/src/credentials/interactiveBrowserCredential.browser.ts b/sdk/identity/identity/src/credentials/interactiveBrowserCredential.browser.ts index 9a292af0730f..f850d6cf1336 100644 --- a/sdk/identity/identity/src/credentials/interactiveBrowserCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/interactiveBrowserCredential.browser.ts @@ -48,7 +48,7 @@ export class InteractiveBrowserCredential implements TokenCredential { this.loginStyle = options.loginStyle || "popup"; if (["redirect", "popup"].indexOf(this.loginStyle) === -1) { const error = new Error(`Invalid loginStyle: ${options.loginStyle}`); - logger.info(formatError(error)); + logger.info(formatError("", error)); throw error; } @@ -102,7 +102,7 @@ export class InteractiveBrowserCredential implements TokenCredential { logger.info(`Authentication returned errorCode ${err.errorCode}`); break; default: - logger.info(formatError(`Failed to acquire token: ${err.message}`)); + logger.info(formatError(authParams.scopes, `Failed to acquire token: ${err.message}`)); throw err; } } @@ -156,10 +156,11 @@ export class InteractiveBrowserCredential implements TokenCredential { }); if (authResponse) { + const expiresOnTimestamp = authResponse.expiresOn.getTime(); logger.getToken.info(formatSuccess(scopes)); return { token: authResponse.accessToken, - expiresOnTimestamp: authResponse.expiresOn.getTime() + expiresOnTimestamp }; } else { logger.getToken.info("No response"); @@ -170,7 +171,7 @@ export class InteractiveBrowserCredential implements TokenCredential { code: CanonicalCode.UNKNOWN, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); throw err; } finally { span.end(); diff --git a/sdk/identity/identity/src/credentials/interactiveBrowserCredential.ts b/sdk/identity/identity/src/credentials/interactiveBrowserCredential.ts index e052bf788fb0..88afaaff5448 100644 --- a/sdk/identity/identity/src/credentials/interactiveBrowserCredential.ts +++ b/sdk/identity/identity/src/credentials/interactiveBrowserCredential.ts @@ -92,7 +92,7 @@ export class InteractiveBrowserCredential implements TokenCredential { if (e instanceof AuthenticationRequired) { return this.acquireTokenFromBrowser(scopeArray); } else { - logger.getToken.info(formatError(e)); + logger.getToken.info(formatError(scopes, e)); throw e; } }); @@ -136,23 +136,23 @@ export class InteractiveBrowserCredential implements TokenCredential { try { const authResponse = await this.msalClient.acquireTokenByCode(tokenRequest); - res.sendStatus(200); - + const successMessage = `Authentication Complete. You can close the browser and return to the application.`; + const expiresOnTimestamp = authResponse?.expiresOn.valueOf(); + res.status(200).send(successMessage); logger.getToken.info(formatSuccess(scopeArray)); resolve({ - expiresOnTimestamp: authResponse.expiresOn.valueOf(), + expiresOnTimestamp, token: authResponse.accessToken }); } catch (error) { - res.status(500).send(error); - - logger.getToken.info(formatError(error)); - reject( - new Error( - `Authentication Error "${req.query["error"]}":\n\n${req.query["error_description"]}` - ) + const errorMessage = formatError( + scopeArray, + `${req.query["error"]}. ${req.query["error_description"]}` ); + res.status(500).send(errorMessage); + logger.getToken.info(errorMessage); + reject(new Error(errorMessage)); } finally { cleanup(); } diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts index 75b5ef27d557..e1a4afa9ce01 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts @@ -60,7 +60,7 @@ async function filePathRequest( if (response.status !== 401) { let message = ""; if (response.bodyAsText) { - message = ` Response: ${response.bodyAsText}` + message = ` Response: ${response.bodyAsText}`; } throw new AuthenticationError( response.status, diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/imdsMsi.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/imdsMsi.ts index c4c058899de0..45bfe8261209 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/imdsMsi.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/imdsMsi.ts @@ -4,7 +4,7 @@ import { AccessToken, GetTokenOptions, RequestPrepareOptions, RestError } from "@azure/core-http"; import { CanonicalCode } from "@opentelemetry/api"; import { IdentityClient } from "../../client/identityClient"; -import { credentialLogger, formatError } from "../../util/logging"; +import { credentialLogger } from "../../util/logging"; import { createSpan } from "../../util/tracing"; import { imdsApiVersion, imdsEndpoint } from "./constants"; import { MSI } from "./models"; @@ -108,9 +108,7 @@ export const imdsMsi: MSI = { } catch (err) { // createWebResource failed. // This error should bubble up to the user. - logger.info( - formatError(`Error when creating the WebResource for the IMDS endpoint: ${err.message}`) - ); + logger.info(`Error when creating the WebResource for the IMDS endpoint: ${err.message}`); span.setStatus({ code: CanonicalCode.UNKNOWN, message: err.message diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.browser.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.browser.ts index 67eedf89f53b..dff12380ab78 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.browser.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.browser.ts @@ -14,12 +14,12 @@ export class ManagedIdentityCredential implements TokenCredential { constructor(clientId: string, options?: TokenCredentialOptions); constructor(options?: TokenCredentialOptions); constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public async getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts index e3094452bf78..18b79c8bb060 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts @@ -157,7 +157,7 @@ export class ManagedIdentityCredential implements TokenCredential { const error = new CredentialUnavailable( "The managed identity endpoint was reached, yet no tokens were received." ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } @@ -171,7 +171,7 @@ export class ManagedIdentityCredential implements TokenCredential { const error = new CredentialUnavailable( "The managed identity endpoint is not currently available" ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } @@ -200,7 +200,7 @@ export class ManagedIdentityCredential implements TokenCredential { "ManagedIdentityCredential is unavailable. No managed identity endpoint found." ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } diff --git a/sdk/identity/identity/src/credentials/usernamePasswordCredential.ts b/sdk/identity/identity/src/credentials/usernamePasswordCredential.ts index 953f0cf86509..80aed049920e 100644 --- a/sdk/identity/identity/src/credentials/usernamePasswordCredential.ts +++ b/sdk/identity/identity/src/credentials/usernamePasswordCredential.ts @@ -106,7 +106,7 @@ export class UsernamePasswordCredential implements TokenCredential { code, message: err.message }); - logger.getToken.info(formatError(err)); + logger.getToken.info(formatError(scopes, err)); throw err; } finally { span.end(); diff --git a/sdk/identity/identity/src/credentials/visualStudioCodeCredential.browser.ts b/sdk/identity/identity/src/credentials/visualStudioCodeCredential.browser.ts index 9cb4b1315a21..9a560e0dc623 100644 --- a/sdk/identity/identity/src/credentials/visualStudioCodeCredential.browser.ts +++ b/sdk/identity/identity/src/credentials/visualStudioCodeCredential.browser.ts @@ -11,12 +11,12 @@ const logger = credentialLogger("VisualStudioCodeCredential"); export class VisualStudioCodeCredential implements TokenCredential { constructor() { - logger.info(formatError(BrowserNotSupportedError)); + logger.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } public getToken(): Promise { - logger.getToken.info(formatError(BrowserNotSupportedError)); + logger.getToken.info(formatError("", BrowserNotSupportedError)); throw BrowserNotSupportedError; } } diff --git a/sdk/identity/identity/src/credentials/visualStudioCodeCredential.ts b/sdk/identity/identity/src/credentials/visualStudioCodeCredential.ts index ab33d349e9b6..904a9ddb085f 100644 --- a/sdk/identity/identity/src/credentials/visualStudioCodeCredential.ts +++ b/sdk/identity/identity/src/credentials/visualStudioCodeCredential.ts @@ -181,7 +181,7 @@ export class VisualStudioCodeCredential implements TokenCredential { // Check to make sure the scope we get back is a valid scope if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) { const error = new Error("Invalid scope was specified by the user or calling client"); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } @@ -224,14 +224,14 @@ export class VisualStudioCodeCredential implements TokenCredential { const error = new CredentialUnavailable( "Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently?" ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } } else { const error = new CredentialUnavailable( "Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension?" ); - logger.getToken.info(formatError(error)); + logger.getToken.info(formatError(scopes, error)); throw error; } } diff --git a/sdk/identity/identity/src/util/checkTenantId.ts b/sdk/identity/identity/src/util/checkTenantId.ts index ced3f06b97dd..954deeecf255 100644 --- a/sdk/identity/identity/src/util/checkTenantId.ts +++ b/sdk/identity/identity/src/util/checkTenantId.ts @@ -8,7 +8,7 @@ export function checkTenantId(logger: CredentialLogger, tenantId: string) { const error = new Error( "Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://docs.microsoft.com/partner-center/find-ids-and-domain-names." ); - logger.info(formatError(error)); + logger.info(formatError("", error)); throw error; } } diff --git a/sdk/identity/identity/src/util/logging.ts b/sdk/identity/identity/src/util/logging.ts index 73bfb5e1c8d2..e43f0a00ff7f 100644 --- a/sdk/identity/identity/src/util/logging.ts +++ b/sdk/identity/identity/src/util/logging.ts @@ -48,14 +48,18 @@ export function logEnvVars(credentialName: string, supportedEnvVars: string[]): * Formatting the success event on the credentials */ export function formatSuccess(scope: string | string[]): string { - return `SUCCESS: ${Array.isArray(scope) ? scope.join(", ") : scope}`; + return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; } /** * Formatting the success event on the credentials */ -export function formatError(error: Error | string): string { - return `ERROR: ${typeof error === "string" ? error : error.message}`; +export function formatError(scope: string | string[] | undefined, error: Error | string): string { + let message = "ERROR."; + if (scope?.length) { + message += ` Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; + } + return `${message} Error message: ${typeof error === "string" ? error : error.message}.`; } /** diff --git a/sdk/identity/identity/test/internal/logger.spec.ts b/sdk/identity/identity/test/internal/logger.spec.ts index c0f935b6f149..19351707a162 100644 --- a/sdk/identity/identity/test/internal/logger.spec.ts +++ b/sdk/identity/identity/test/internal/logger.spec.ts @@ -30,7 +30,7 @@ describe("Identity logging utilities", function() { }; const logger = credentialLoggerInstance("title", undefined, fakeLogger as any); logger.info(formatSuccess("scope")); - assert.equal(allParams[0].join(" "), "title => SUCCESS: scope"); + assert.equal(allParams[0].join(" "), "title => SUCCESS. Scopes: scope."); }); it("success with multiple scopes", async function() { @@ -40,7 +40,7 @@ describe("Identity logging utilities", function() { }; const logger = credentialLoggerInstance("title", undefined, fakeLogger as any); logger.info(formatSuccess(["scope 1", "scope 2"])); - assert.equal(allParams[0].join(" "), "title => SUCCESS: scope 1, scope 2"); + assert.equal(allParams[0].join(" "), "title => SUCCESS. Scopes: scope 1, scope 2."); }); it("error (with formatError)", async function() { @@ -49,8 +49,11 @@ describe("Identity logging utilities", function() { info: (...params: any) => allParams.push(params) }; const logger = credentialLoggerInstance("title", undefined, fakeLogger as any); - logger.info(formatError(new Error("message"))); - assert.equal(allParams[0].join(" "), "title => ERROR: message"); + logger.info(formatError("scope", new Error("message"))); + assert.equal( + allParams[0].join(" "), + "title => ERROR. Scopes: scope. Error message: message." + ); }); }); @@ -99,7 +102,7 @@ describe("Identity logging utilities", function() { return null; } const error = new Error("test getToken error"); - this.logger.getToken.info(formatError(error)); + this.logger.getToken.info(formatError(scopes, error)); throw error; } } @@ -110,7 +113,7 @@ describe("Identity logging utilities", function() { await fakeCredential.getToken(["Scope 1", "Scope 2"]); assert.equal( allInfoParams[1].join(" "), - "FakeCredential => getToken() => SUCCESS: Scope 1, Scope 2" + "FakeCredential => getToken() => SUCCESS. Scopes: Scope 1, Scope 2." ); try { @@ -121,7 +124,7 @@ describe("Identity logging utilities", function() { assert.equal( allInfoParams[2].join(" "), - "FakeCredential => getToken() => ERROR: test getToken error" + "FakeCredential => getToken() => ERROR. Error message: test getToken error." ); }); }); From 9f4619006939526f1546a0bc793c13f04bae2a7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Rodr=C3=ADguez?= Date: Mon, 9 Nov 2020 17:40:02 -0500 Subject: [PATCH 18/35] [Identity] Cleanups after end-to-end testing and meetings (#12347) * [Identity] Cleanups after end-to-end testing and meetings * test fixes --- .../managedIdentityCredential/arcMsi.ts | 14 ++++++++------ .../managedIdentityCredential/constants.ts | 3 ++- .../managedIdentityCredential/fabricMsi.ts | 3 ++- .../managedIdentityCredential/index.ts | 5 +++-- .../node/managedIdentityCredential.spec.ts | 19 ++++++++++--------- 5 files changed, 25 insertions(+), 19 deletions(-) diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts index e1a4afa9ce01..c31132f0544a 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/arcMsi.ts @@ -15,16 +15,12 @@ const logger = credentialLogger("ManagedIdentityCredential - ArcMSI"); // Azure Arc MSI doesn't have a special expiresIn parser. const expiresInParser = undefined; -function prepareRequestOptions(resource?: string, clientId?: string): RequestPrepareOptions { +function prepareRequestOptions(resource?: string): RequestPrepareOptions { const queryParameters: any = { resource, "api-version": azureArcAPIVersion }; - if (clientId) { - queryParameters.client_id = clientId; - } - return { // Should be similar to: http://localhost:40342/metadata/identity/oauth2/token url: process.env.IDENTITY_ENDPOINT, @@ -84,12 +80,18 @@ export const arcMsi: MSI = { ): Promise { logger.info(`Using the Azure Arc MSI to authenticate.`); + if (clientId) { + throw new Error( + "User assigned identity is not supported by the Azure Arc Managed Identity Endpoint. To authenticate with the system assigned identity omit the client id when constructing the ManagedIdentityCredential, or if authenticating with the DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set." + ); + } + const requestOptions = { disableJsonStringifyOnBody: true, deserializationMapper: undefined, abortSignal: getTokenOptions.abortSignal, spanOptions: getTokenOptions.tracingOptions && getTokenOptions.tracingOptions.spanOptions, - ...prepareRequestOptions(resource, clientId) + ...prepareRequestOptions(resource) }; const filePath = await filePathRequest(identityClient, requestOptions); diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/constants.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/constants.ts index f712fc950407..52026f204d87 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/constants.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/constants.ts @@ -5,4 +5,5 @@ export const DefaultScopeSuffix = "/.default"; export const imdsEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token"; export const imdsApiVersion = "2018-02-01"; -export const azureArcAPIVersion = "2019-08-15"; +export const azureArcAPIVersion = "2019-11-01"; +export const azureFabricVersion = "2019-07-01-preview"; diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/fabricMsi.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/fabricMsi.ts index 975fea4178ea..1076b1408e37 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/fabricMsi.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/fabricMsi.ts @@ -6,6 +6,7 @@ import { MSI } from "./models"; import { credentialLogger } from "../../util/logging"; import { IdentityClient } from "../../client/identityClient"; import { msiGenericGetToken } from "./utils"; +import { azureFabricVersion } from "./constants"; const logger = credentialLogger("ManagedIdentityCredential - Fabric MSI"); @@ -17,7 +18,7 @@ function expiresInParser(requestBody: any): number { function prepareRequestOptions(resource: string, clientId?: string): RequestPrepareOptions { const queryParameters: any = { resource, - "api-version": "2019-07-01-preview" + "api-version": azureFabricVersion }; if (clientId) { diff --git a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts index 18b79c8bb060..163cfcd0e414 100644 --- a/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts +++ b/sdk/identity/identity/src/credentials/managedIdentityCredential/index.ts @@ -17,7 +17,6 @@ import { imdsMsi } from "./imdsMsi"; import { MSI } from "./models"; import { appServiceMsi2017 } from "./appServiceMsi2017"; import { arcMsi } from "./arcMsi"; -import { fabricMsi } from "./fabricMsi"; const logger = credentialLogger("ManagedIdentityCredential"); @@ -78,7 +77,9 @@ export class ManagedIdentityCredential implements TokenCredential { return this.cachedMSI; } - const MSIs = [fabricMsi, appServiceMsi2017, cloudShellMsi, arcMsi, imdsMsi]; + // "fabricMsi" can't be added yet because our HTTPs pipeline doesn't allow skipping the SSL verification step, + // which is necessary since Service Fabric only provides self-signed certificates on their Identity Endpoint. + const MSIs = [appServiceMsi2017, cloudShellMsi, arcMsi, imdsMsi]; for (const msi of MSIs) { if (await msi.isAvailable(this.identityClient, resource, clientId, getTokenOptions)) { diff --git a/sdk/identity/identity/test/internal/node/managedIdentityCredential.spec.ts b/sdk/identity/identity/test/internal/node/managedIdentityCredential.spec.ts index b41bd339320b..0e1129ae631c 100644 --- a/sdk/identity/identity/test/internal/node/managedIdentityCredential.spec.ts +++ b/sdk/identity/identity/test/internal/node/managedIdentityCredential.spec.ts @@ -17,7 +17,7 @@ interface AuthRequestDetails { token: AccessToken | null; } -describe("ManagedIdentityCredential", function() { +describe("ManagedIdentityCredential", function () { afterEach(() => { delete process.env.IDENTITY_ENDPOINT; delete process.env.IDENTITY_HEADER; @@ -26,7 +26,7 @@ describe("ManagedIdentityCredential", function() { delete process.env.IDENTITY_SERVER_THUMBPRINT; }); - it("sends an authorization request with a modified resource name", async function() { + it("sends an authorization request with a modified resource name", async function () { const authDetails = await getMsiTokenAuthRequest(["https://service/.default"], "client", { authResponse: [ { status: 200 }, // Respond to IMDS isAvailable @@ -83,7 +83,7 @@ describe("ManagedIdentityCredential", function() { } }); - it("returns error when ManagedIdentityCredential authentication failed", async function() { + it("returns error when ManagedIdentityCredential authentication failed", async function () { process.env.AZURE_CLIENT_ID = "errclient"; const errResponse: OAuthErrorResponse = { @@ -211,7 +211,7 @@ describe("ManagedIdentityCredential", function() { [`${filePath}`]: key }); - const authDetails = await getMsiTokenAuthRequest(["https://service/.default"], "client", { + const authDetails = await getMsiTokenAuthRequest(["https://service/.default"], undefined, { authResponse: [ { status: 401, @@ -234,7 +234,6 @@ describe("ManagedIdentityCredential", function() { assert.ok(validationRequest.query, "No query string parameters on request"); assert.equal(validationRequest.method, "GET"); - assert.equal(validationRequest.query!["client_id"], "client"); assert.equal(decodeURIComponent(validationRequest.query!["resource"]), "https://service"); assert.ok( @@ -247,7 +246,6 @@ describe("ManagedIdentityCredential", function() { assert.ok(authRequest.query, "No query string parameters on request"); assert.equal(authRequest.method, "GET"); - assert.equal(authRequest.query!["client_id"], "client"); assert.equal(decodeURIComponent(authRequest.query!["resource"]), "https://service"); assert.ok( @@ -259,15 +257,18 @@ describe("ManagedIdentityCredential", function() { if (authDetails.token) { // We use Date.now underneath. assert.equal( - Math.floor(authDetails.token.expiresOnTimestamp / 100000), - Math.floor(Date.now() / 100000) + Math.floor(authDetails.token.expiresOnTimestamp / 1000000), + Math.floor(Date.now() / 1000000) ); } else { assert.fail("No token was returned!"); } }); - it("sends an authorization request correctly in an Azure Fabric environment", async () => { + // "fabricMsi" isn't part of the ManagedIdentityCredential MSIs yet + // because our HTTPs pipeline doesn't allow skipping the SSL verification step, + // which is necessary since Service Fabric only provides self-signed certificates on their Identity Endpoint. + it.skip("sends an authorization request correctly in an Azure Fabric environment", async () => { // Trigger App Service behavior by setting environment variables process.env.IDENTITY_ENDPOINT = "https://endpoint"; process.env.IDENTITY_HEADER = "secret"; From dc3957934930fa2a3ea2dcf4f3e2473735beba4e Mon Sep 17 00:00:00 2001 From: LuChen-Microsoft <44377201+LuChen-Microsoft@users.noreply.github.com> Date: Mon, 9 Nov 2020 15:15:27 -0800 Subject: [PATCH 19/35] Remove validation from chat list unit tests (#12411) --- .../communication-chat/test/chatClient.spec.ts | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/sdk/communication/communication-chat/test/chatClient.spec.ts b/sdk/communication/communication-chat/test/chatClient.spec.ts index 9ef4021b6e50..ccf6cca402f5 100644 --- a/sdk/communication/communication-chat/test/chatClient.spec.ts +++ b/sdk/communication/communication-chat/test/chatClient.spec.ts @@ -54,7 +54,7 @@ describe("ChatClient", function() { threadId = chatThreadClient.threadId; assert.isNotNull(threadId); - }).timeout(6000); + }).timeout(8000); it("successfully retrieves a thread client", async function() { const chatThreadClient = await chatClient.getChatThreadClient(threadId); @@ -73,8 +73,6 @@ describe("ChatClient", function() { for await (const thread of chatClient.listChatThreads()) { list.push(thread.id!); } - - assert.include(list, threadId); }); it("successfully sends a message", async function() { @@ -107,8 +105,6 @@ describe("ChatClient", function() { for await (const message of chatThreadClient.listMessages()) { list.push(message.id!); } - - assert.include(list, messageId); }); it("successfully deletes a message", async function() { @@ -127,8 +123,6 @@ describe("ChatClient", function() { for await (const member of chatThreadClient.listMembers()) { list.push(member.user.communicationUserId!); } - - assert.include(list, testUser.communicationUserId); }); it("successfully remove a member", async function() { @@ -140,8 +134,6 @@ describe("ChatClient", function() { for await (const receipt of chatThreadClient.listReadReceipts()) { list.push(receipt.chatMessageId!); } - - assert.include(list, messageId); }); it("successfully deletes a thread", async function() { From 3dac5ee4305aea1ae0efa8f72d199adc2101fe32 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Mon, 9 Nov 2020 17:49:50 -0800 Subject: [PATCH 20/35] Sync eng/common directory with azure-sdk-tools for PR 1163 (#12346) * Update subscription configuration schema to include new parameters * Support platform specific arm template parameters and legacy hashtable format * Update arm template parameter comment to include top level key * Restore AdditionalParameters. Merge ArmTemplateParameters from stringified hash literal * Handle duplicate keys more explicitly for arm and env vars * Regenerate New-TestResources.ps1 markdown * revert variable name to environmentVariables to fix post-scripts * Handle empty arm template parameters better * Remove arm template parameter merge logic from deploy template * Add merge hashes function to New-TestResources.ps1 * Add merge hashes function to New-TestResources.ps1 * Add env variable overwrite warning. Use ContainsKey checks * Temporarily manually fix invalid generated markdown links Co-authored-by: Ben Broderick Phillips --- .../TestResources/New-TestResources.ps1 | 52 ++++++++++++++----- .../TestResources/New-TestResources.ps1.md | 43 ++++++++++++--- .../TestResources/Remove-TestResources.ps1 | 2 - .../TestResources/deploy-test-resources.yml | 30 ++++++++--- 4 files changed, 101 insertions(+), 26 deletions(-) diff --git a/eng/common/TestResources/New-TestResources.ps1 b/eng/common/TestResources/New-TestResources.ps1 index 8de70b50dce7..4c03816c1284 100644 --- a/eng/common/TestResources/New-TestResources.ps1 +++ b/eng/common/TestResources/New-TestResources.ps1 @@ -10,7 +10,7 @@ [CmdletBinding(DefaultParameterSetName = 'Default', SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] param ( - # Limit $BaseName to enough characters to be under limit plus prefixes, and https://docs.microsoft.com/azure/architecture/best-practices/resource-naming. + # Limit $BaseName to enough characters to be under limit plus prefixes, and https://docs.microsoft.com/azure/architecture/best-practices/resource-naming [Parameter()] [ValidatePattern('^[-a-zA-Z0-9\.\(\)_]{0,80}(?<=[a-zA-Z0-9\(\)])$')] [string] $BaseName, @@ -58,9 +58,16 @@ param ( [ValidateSet('AzureCloud', 'AzureUSGovernment', 'AzureChinaCloud', 'Dogfood')] [string] $Environment = 'AzureCloud', + [Parameter()] + [hashtable] $ArmTemplateParameters, + [Parameter()] [hashtable] $AdditionalParameters, + [Parameter()] + [ValidateNotNull()] + [hashtable] $EnvironmentVariables = @{}, + [Parameter()] [switch] $CI = ($null -ne $env:SYSTEM_TEAMPROJECTID), @@ -101,6 +108,16 @@ function Retry([scriptblock] $Action, [int] $Attempts = 5) { } } +function MergeHashes([hashtable] $source, [psvariable] $dest) { + foreach ($key in $source.Keys) { + if ($dest.Value.ContainsKey($key) -and $dest.Value[$key] -ne $source[$key]) { + Write-Warning ("Overwriting '$($dest.Name).$($key)' with value '$($dest.Value[$key])' " + + "to new value '$($source[$key])'") + } + $dest.Value[$key] = $source[$key] + } +} + # Support actions to invoke on exit. $exitActions = @({ if ($exitActions.Count -gt 1) { @@ -118,7 +135,6 @@ $repositoryRoot = "$PSScriptRoot/../../.." | Resolve-Path $root = [System.IO.Path]::Combine($repositoryRoot, "sdk", $ServiceDirectory) | Resolve-Path $templateFileName = 'test-resources.json' $templateFiles = @() -$environmentVariables = @{} # Azure SDK Developer Playground $defaultSubscription = "faa080af-c1d8-40ad-9cce-e1a450ca5b57" @@ -252,7 +268,7 @@ $serviceName = if (Split-Path -IsAbsolute $ServiceDirectory) { $ServiceDirectory } -if ($CI) { +if ($CI) { $BaseName = 't' + (New-Guid).ToString('n').Substring(0, 16) Write-Verbose "Generated base name '$BaseName' for CI build" } @@ -289,7 +305,13 @@ if ($CI) { # Set the resource group name variable. Write-Host "Setting variable 'AZURE_RESOURCEGROUP_NAME': $ResourceGroupName" Write-Host "##vso[task.setvariable variable=AZURE_RESOURCEGROUP_NAME;]$ResourceGroupName" - $environmentVariables['AZURE_RESOURCEGROUP_NAME'] = $ResourceGroupName + if ($EnvironmentVariables.ContainsKey('AZURE_RESOURCEGROUP_NAME') -and ` + $EnvironmentVariables['AZURE_RESOURCEGROUP_NAME'] -ne $ResourceGroupName) + { + Write-Warning ("Overwriting 'EnvironmentVariables.AZURE_RESOURCEGROUP_NAME' with value " + + "'$($EnvironmentVariables['AZURE_RESOURCEGROUP_NAME'])' " + "to new value '$($ResourceGroupName)'") + } + $EnvironmentVariables['AZURE_RESOURCEGROUP_NAME'] = $ResourceGroupName } Log "Creating resource group '$ResourceGroupName' in location '$Location'" @@ -322,11 +344,11 @@ if ($TenantId) { if ($TestApplicationSecret) { $templateParameters.Add('testApplicationSecret', $TestApplicationSecret) } -if ($AdditionalParameters) { - $templateParameters += $AdditionalParameters -} -# Include environment-specific parameters only if not already provided as part of the "AdditionalParameters" +MergeHashes $ArmTemplateParameters $(Get-Variable templateParameters) +MergeHashes $AdditionalParameters $(Get-Variable templateParameters) + +# Include environment-specific parameters only if not already provided as part of the "ArmTemplateParameters" if (($context.Environment.StorageEndpointSuffix) -and (-not ($templateParameters.ContainsKey('storageEndpointSuffix')))) { $templateParameters.Add('storageEndpointSuffix', $context.Environment.StorageEndpointSuffix) } @@ -388,6 +410,8 @@ foreach ($templateFile in $templateFiles) { "$($serviceDirectoryPrefix)STORAGE_ENDPOINT_SUFFIX" = $context.Environment.StorageEndpointSuffix; } + MergeHashes $EnvironmentVariables $(Get-Variable deploymentOutputs) + foreach ($key in $deployment.Outputs.Keys) { $variable = $deployment.Outputs[$key] @@ -422,7 +446,7 @@ foreach ($templateFile in $templateFiles) { foreach ($key in $deploymentOutputs.Keys) { $value = $deploymentOutputs[$key] - $environmentVariables[$key] = $value + $EnvironmentVariables[$key] = $value if ($CI) { # Treat all ARM template output variables as secrets since "SecureString" variables do not set values. @@ -453,7 +477,7 @@ $exitActions.Invoke() # Suppress output locally if ($CI) { - return $environmentVariables + return $EnvironmentVariables } <# @@ -571,8 +595,14 @@ Name of the cloud environment. The default is the Azure Public Cloud ('AzureCloud') .PARAMETER AdditionalParameters +Optional key-value pairs of parameters to pass to the ARM template(s) and pre-post scripts. + +.PARAMETER ArmTemplateParameters Optional key-value pairs of parameters to pass to the ARM template(s). +.PARAMETER EnvironmentVariables +Optional key-value pairs of parameters to set as environment variables to the shell. + .PARAMETER CI Indicates the script is run as part of a Continuous Integration / Continuous Deployment (CI/CD) build (only Azure Pipelines is currently supported). @@ -617,6 +647,4 @@ Run this in an Azure DevOps CI (with approrpiate variables configured) before executing live tests. The script will output variables as secrets (to enable log redaction). -.LINK -Remove-TestResources.ps1 #> diff --git a/eng/common/TestResources/New-TestResources.ps1.md b/eng/common/TestResources/New-TestResources.ps1.md index c41693c87666..515a51bd373c 100644 --- a/eng/common/TestResources/New-TestResources.ps1.md +++ b/eng/common/TestResources/New-TestResources.ps1.md @@ -16,8 +16,9 @@ Deploys live test resources defined for a service directory to Azure. ``` New-TestResources.ps1 [-BaseName ] [-ResourceGroupName ] [-ServiceDirectory] [-TestApplicationId ] [-TestApplicationSecret ] [-TestApplicationOid ] - [-DeleteAfterHours ] [-Location ] [-Environment ] [-AdditionalParameters ] - [-CI] [-Force] [-OutFile] [-WhatIf] [-Confirm] [] + [-DeleteAfterHours ] [-Location ] [-Environment ] [-ArmTemplateParameters ] + [-AdditionalParameters ] [-EnvironmentVariables ] [-CI] [-Force] [-OutFile] [-WhatIf] + [-Confirm] [] ``` ### Provisioner @@ -26,8 +27,8 @@ New-TestResources.ps1 [-BaseName ] [-ResourceGroupName ] [-Servi [-TestApplicationId ] [-TestApplicationSecret ] [-TestApplicationOid ] -TenantId [-SubscriptionId ] -ProvisionerApplicationId -ProvisionerApplicationSecret [-DeleteAfterHours ] [-Location ] - [-Environment ] [-AdditionalParameters ] [-CI] [-Force] [-OutFile] [-WhatIf] [-Confirm] - [] + [-Environment ] [-ArmTemplateParameters ] [-AdditionalParameters ] + [-EnvironmentVariables ] [-CI] [-Force] [-OutFile] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -339,7 +340,7 @@ Accept wildcard characters: False ### -Environment Name of the cloud environment. The default is the Azure Public Cloud -('PublicCloud') +('AzureCloud') ```yaml Type: String @@ -353,7 +354,7 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -AdditionalParameters +### -ArmTemplateParameters Optional key-value pairs of parameters to pass to the ARM template(s). ```yaml @@ -368,6 +369,36 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -AdditionalParameters +Optional key-value pairs of parameters to pass to the ARM template(s) and pre-post scripts. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -EnvironmentVariables +Optional key-value pairs of parameters to set as environment variables to the shell. + +```yaml +Type: Hashtable +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: @{} +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -CI Indicates the script is run as part of a Continuous Integration / Continuous Deployment (CI/CD) build (only Azure Pipelines is currently supported). diff --git a/eng/common/TestResources/Remove-TestResources.ps1 b/eng/common/TestResources/Remove-TestResources.ps1 index 83b1a58c347f..b74ddb42ac23 100644 --- a/eng/common/TestResources/Remove-TestResources.ps1 +++ b/eng/common/TestResources/Remove-TestResources.ps1 @@ -214,6 +214,4 @@ Remove-TestResources.ps1 ` When run in the context of an Azure DevOps pipeline, this script removes the resource group whose name is stored in the environment variable AZURE_RESOURCEGROUP_NAME. -.LINK -New-TestResources.ps1 #> diff --git a/eng/common/TestResources/deploy-test-resources.yml b/eng/common/TestResources/deploy-test-resources.yml index 6f0db25d61a8..031c4b37cccd 100644 --- a/eng/common/TestResources/deploy-test-resources.yml +++ b/eng/common/TestResources/deploy-test-resources.yml @@ -5,7 +5,7 @@ parameters: Location: '' SubscriptionConfiguration: $(sub-config-azure-cloud-test-resources) -# SubscriptionConfiguration will be splat into the parameters of the test +# SubscriptionConfiguration will be splatted into the parameters of the test # resources script. It should be JSON in the form: # { # "SubscriptionId": "", @@ -15,25 +15,43 @@ parameters: # "ProvisionerApplicationId": "", # "ProvisionerApplicationSecret": "", # "Environment": "AzureCloud | AzureGov | AzureChina | " +# "EnvironmentVariables": { +# "SERVICE_MANAGEMENT_URL": "", +# "STORAGE_ENDPOINT_SUFFIX": "", +# "RESOURCE_MANAGER_URL": "", +# "SEARCH_ENDPOINT_SUFFIX": "", +# "COSMOS_TABLES_ENDPOINT_SUFFIX": "" +# }, +# "ArmTemplateParameters": { +# "keyVaultDomainSuffix": "", +# "storageEndpointSuffix": "", +# "endpointSuffix": "", +# "azureAuthorityHost": "", +# "keyVaultEndpointSuffix": "" +# } # } + steps: - template: /eng/common/TestResources/setup-az-modules.yml - pwsh: | eng/common/TestResources/Import-AzModules.ps1 - $subscriptionConfiguration = @" + $subscriptionConfiguration = @' ${{ parameters.SubscriptionConfiguration }} - "@ | ConvertFrom-Json -AsHashtable; + '@ | ConvertFrom-Json -AsHashtable; + # The subscriptionConfiguration may have ArmTemplateParameters defined, so + # pass those in via the ArmTemplateParameters flag, and handle any + # additional parameters from the pipelines via AdditionalParameters eng/common/TestResources/New-TestResources.ps1 ` -BaseName 'Generated' ` - -ServiceDirectory ${{ parameters.ServiceDirectory }} ` + -ServiceDirectory '${{ parameters.ServiceDirectory }}' ` -Location '${{ parameters.Location }}' ` - -DeleteAfterHours ${{ parameters.DeleteAfterHours }} ` - -AdditionalParameters ${{ parameters.ArmTemplateParameters }} ` + -DeleteAfterHours '${{ parameters.DeleteAfterHours }}' ` @subscriptionConfiguration ` + -AdditionalParameters ${{ parameters.ArmTemplateParameters }} ` -CI ` -Force ` -Verbose | Out-Null From 93444da1320150fdcad8c3676066e84ab10a179c Mon Sep 17 00:00:00 2001 From: chradek <51000525+chradek@users.noreply.github.com> Date: Mon, 9 Nov 2020 18:16:32 -0800 Subject: [PATCH 21/35] [core-amqp][event-hubs][service-bus] move DataTransformer from core-amqp to client packages (#12415) Part of the list of breaking changes to core-amqp v2 in #12116 Replaces #12320 (precipitated by https://github.com/Azure/azure-sdk-for-js/pull/12320#discussion_r518438209) This change moves the `DataTransformer` interface and `DefaultDataTransformer` class to service-bus and event-hub packages. When we establish what our data serde strategy is, we can revisit using a shared common serde solution. --- sdk/core/core-amqp/CHANGELOG.md | 5 +- sdk/core/core-amqp/review/core-amqp.api.md | 14 -- .../core-amqp/src/ConnectionContextBase.ts | 13 -- sdk/core/core-amqp/src/index.ts | 1 - sdk/core/core-amqp/test/context.spec.ts | 5 +- sdk/eventhub/event-hubs/rollup.base.config.js | 4 +- .../event-hubs}/src/dataTransformer.ts | 28 +-- sdk/eventhub/event-hubs/src/eventDataBatch.ts | 3 +- .../event-hubs/src/eventHubReceiver.ts | 3 +- sdk/eventhub/event-hubs/src/eventHubSender.ts | 3 +- .../event-hubs}/test/dataTransformer.spec.ts | 15 +- .../service-bus/rollup.base.config.js | 4 +- .../service-bus/src/core/batchingReceiver.ts | 1 - .../service-bus/src/core/managementClient.ts | 8 +- .../service-bus/src/core/messageSender.ts | 5 +- .../service-bus/src/core/streamingReceiver.ts | 1 - .../service-bus/src/dataTransformer.ts | 86 ++++++++ .../service-bus/src/serviceBusMessage.ts | 6 +- .../service-bus/src/serviceBusMessageBatch.ts | 3 +- .../service-bus/src/session/messageSession.ts | 1 - .../test/internal/dataTransformer.spec.ts | 197 ++++++++++++++++++ .../test/internal/serviceBusMessage.spec.ts | 16 +- .../test/internal/unittestUtils.ts | 3 +- 23 files changed, 328 insertions(+), 97 deletions(-) rename sdk/{core/core-amqp => eventhub/event-hubs}/src/dataTransformer.ts (80%) rename sdk/{core/core-amqp => eventhub/event-hubs}/test/dataTransformer.spec.ts (94%) create mode 100644 sdk/servicebus/service-bus/src/dataTransformer.ts create mode 100644 sdk/servicebus/service-bus/test/internal/dataTransformer.spec.ts diff --git a/sdk/core/core-amqp/CHANGELOG.md b/sdk/core/core-amqp/CHANGELOG.md index 56f53b4b837c..13e0d5144753 100644 --- a/sdk/core/core-amqp/CHANGELOG.md +++ b/sdk/core/core-amqp/CHANGELOG.md @@ -2,8 +2,11 @@ ## 2.0.0 (Unreleased) -### Breaking Changes +### Breaking changes +- Continuing our work to clean the public API surface that we started in 2.0.0-beta.1, `DataTransformer` and `DefaultDataTransformer` are no longer exported. + `dataTransformer` has been removed from `ConnectionContextBase` and `ConnectionContextBaseParameters`. + This allows us to consider other forms of implementing serializers in the future. - Previously, `ConnectionConfig.validate()` overridden entityPath if `undefined` with `String(undefined) = "undefined"`. This has been updated to retain `undefined` in the validation. [PR 12321](https://github.com/Azure/azure-sdk-for-js/pull/12321) diff --git a/sdk/core/core-amqp/review/core-amqp.api.md b/sdk/core/core-amqp/review/core-amqp.api.md index 65e55292e054..26323274f28d 100644 --- a/sdk/core/core-amqp/review/core-amqp.api.md +++ b/sdk/core/core-amqp/review/core-amqp.api.md @@ -232,7 +232,6 @@ export interface ConnectionContextBase { connection: Connection; connectionId: string; connectionLock: string; - dataTransformer: DataTransformer; negotiateClaimLock: string; refreshConnection: () => void; wasConnectionCloseCalled: boolean; @@ -373,23 +372,10 @@ export const Constants: { export interface CreateConnectionContextBaseParameters { config: ConnectionConfig; connectionProperties: ConnectionProperties; - dataTransformer?: DataTransformer; isEntityPathRequired?: boolean; operationTimeoutInMs?: number; } -// @public -export interface DataTransformer { - decode: (body: any) => any; - encode: (body: any) => any; -} - -// @public -export class DefaultDataTransformer implements DataTransformer { - decode(body: any): any; - encode(body: any): any; -} - // @public export const defaultLock: AsyncLock; diff --git a/sdk/core/core-amqp/src/ConnectionContextBase.ts b/sdk/core/core-amqp/src/ConnectionContextBase.ts index f77a3a258967..ae10c31c720d 100644 --- a/sdk/core/core-amqp/src/ConnectionContextBase.ts +++ b/sdk/core/core-amqp/src/ConnectionContextBase.ts @@ -3,7 +3,6 @@ import { Connection, ConnectionOptions, generate_uuid } from "rhea-promise"; import { CbsClient } from "./cbs"; -import { DataTransformer, DefaultDataTransformer } from "./dataTransformer"; import { ConnectionConfig } from "./connectionConfig/connectionConfig"; import { Constants } from "./util/constants"; @@ -44,12 +43,6 @@ export interface ConnectionContextBase { * called on the connection object. */ wasConnectionCloseCalled: boolean; - /** - * @property {DataTransformer} dataTransformer A DataTransformer object that has methods named - * - encode Responsible for encoding the AMQP message before sending it on the wire. - * - decode Responsible for decoding the received AMQP message before passing it to the customer. - */ - dataTransformer: DataTransformer; /** * @property {CbsClient} cbsSession A reference to the cbs session ($cbs endpoint) on the * underlying AMQP connection for the EventHub Client. @@ -95,11 +88,6 @@ export interface CreateConnectionContextBaseParameters { * the AMQP connection. */ connectionProperties: ConnectionProperties; - /** - * @property {DataTransformer} [dataTransformer] The datatransformer to be used for encoding and - * decoding messages. Default value: DefaultDataTransformer - */ - dataTransformer?: DataTransformer; /** * @property {boolean} [isEntityPathRequired] Determines whether entity path should be a part of * the connection config. If `true` it must be present, `false` otherwise. Default value false. @@ -178,7 +166,6 @@ export const ConnectionContextBase = { connectionId: connection.id, cbsSession: new CbsClient(connection, connectionLock), config: parameters.config, - dataTransformer: parameters.dataTransformer || new DefaultDataTransformer(), refreshConnection() { const connection = new Connection(connectionOptions); const connectionLock = `${Constants.establishConnection}-${generate_uuid()}`; diff --git a/sdk/core/core-amqp/src/index.ts b/sdk/core/core-amqp/src/index.ts index ca971e056b2c..b8534448730b 100644 --- a/sdk/core/core-amqp/src/index.ts +++ b/sdk/core/core-amqp/src/index.ts @@ -5,7 +5,6 @@ export { RequestResponseLink, SendRequestOptions } from "./requestResponseLink"; export { retry, RetryOptions, RetryConfig, RetryOperationType, RetryMode } from "./retry"; -export { DataTransformer, DefaultDataTransformer } from "./dataTransformer"; export { TokenType } from "./auth/token"; export { ConnectionConfig, ConnectionConfigOptions } from "./connectionConfig/connectionConfig"; diff --git a/sdk/core/core-amqp/test/context.spec.ts b/sdk/core/core-amqp/test/context.spec.ts index 4c51c56b4910..5bb995c7f175 100644 --- a/sdk/core/core-amqp/test/context.spec.ts +++ b/sdk/core/core-amqp/test/context.spec.ts @@ -3,7 +3,7 @@ import * as chai from "chai"; const should = chai.should(); -import { CbsClient, ConnectionConfig, ConnectionContextBase, DefaultDataTransformer } from "../src"; +import { CbsClient, ConnectionConfig, ConnectionContextBase } from "../src"; import { Connection } from "rhea-promise"; import { isNode } from "../src/util/utils"; @@ -26,14 +26,12 @@ describe("ConnectionContextBase", function() { should.exist(context.connectionId); should.exist(context.connectionLock); should.exist(context.negotiateClaimLock); - should.exist(context.dataTransformer); context.wasConnectionCloseCalled.should.equal(false); context.connection.should.instanceOf(Connection); context.connection.options.properties!.product.should.equal("MSJSClient"); context.connection.options.properties!["user-agent"].should.equal("/js-amqp-client"); context.connection.options.properties!.version.should.equal("1.0.0"); context.cbsSession.should.instanceOf(CbsClient); - context.dataTransformer.should.instanceOf(DefaultDataTransformer); done(); }); @@ -133,7 +131,6 @@ describe("ConnectionContextBase", function() { should.exist(context.connectionId); should.exist(context.connectionLock); should.exist(context.negotiateClaimLock); - should.exist(context.dataTransformer); context.wasConnectionCloseCalled.should.equal(false); context.cbsSession.should.instanceOf(CbsClient); diff --git a/sdk/eventhub/event-hubs/rollup.base.config.js b/sdk/eventhub/event-hubs/rollup.base.config.js index 505a27db20e4..13f9a6bdb8b2 100644 --- a/sdk/eventhub/event-hubs/rollup.base.config.js +++ b/sdk/eventhub/event-hubs/rollup.base.config.js @@ -122,7 +122,9 @@ export function browserConfig(test = false) { cjs({ namedExports: { - "@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"] + "@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"], + chai: ["should", "assert"], + assert: ["equal", "deepEqual", "notEqual"] } }), diff --git a/sdk/core/core-amqp/src/dataTransformer.ts b/sdk/eventhub/event-hubs/src/dataTransformer.ts similarity index 80% rename from sdk/core/core-amqp/src/dataTransformer.ts rename to sdk/eventhub/event-hubs/src/dataTransformer.ts index 03580d8d96e1..f09470d8983a 100644 --- a/sdk/core/core-amqp/src/dataTransformer.ts +++ b/sdk/eventhub/event-hubs/src/dataTransformer.ts @@ -2,32 +2,16 @@ // Licensed under the MIT license. import { message } from "rhea-promise"; -import { logErrorStackTrace, logger } from "./log"; import isBuffer from "is-buffer"; import { Buffer } from "buffer"; - -/** - * Describes the transformations that can be performed to encode/decode the data before sending it - * on (or receiving it from) the wire. - */ -export interface DataTransformer { - /** - * @property {Function} encode A function that takes the body property from an EventData object - * and returns an encoded body (some form of AMQP type). - */ - encode: (body: any) => any; - /** - * @property {Function} decode A function that takes the body property from an AMQP message - * and returns the decoded message body. If it cannot decode the body then it returns the body - * as-is. - */ - decode: (body: any) => any; -} +import { logErrorStackTrace, logger } from "./log"; /** * The default data transformer that will be used by the Azure SDK. + * @internal + * @ingore */ -export class DefaultDataTransformer implements DataTransformer { +export const defaultDataTransformer = { /** * A function that takes the body property from an EventData object * and returns an encoded body (some form of AMQP type). @@ -62,7 +46,7 @@ export class DefaultDataTransformer implements DataTransformer { } } return result; - } + }, /** * @property {Function} [decode] A function that takes the body property from an AMQP message @@ -99,4 +83,4 @@ export class DefaultDataTransformer implements DataTransformer { } return processedBody; } -} +}; diff --git a/sdk/eventhub/event-hubs/src/eventDataBatch.ts b/sdk/eventhub/event-hubs/src/eventDataBatch.ts index 5cea888a9c62..65c6373a4431 100644 --- a/sdk/eventhub/event-hubs/src/eventDataBatch.ts +++ b/sdk/eventhub/event-hubs/src/eventDataBatch.ts @@ -8,6 +8,7 @@ import { throwTypeErrorIfParameterMissing } from "./util/error"; import { Span, SpanContext } from "@opentelemetry/api"; import { TRACEPARENT_PROPERTY, instrumentEventData } from "./diagnostics/instrumentEventData"; import { createMessageSpan } from "./diagnostics/messageSpan"; +import { defaultDataTransformer } from "./dataTransformer"; /** * The amount of bytes to reserve as overhead for a small message. @@ -303,7 +304,7 @@ export class EventDataBatchImpl implements EventDataBatch { // Convert EventData to RheaMessage. const amqpMessage = toRheaMessage(eventData, this._partitionKey); - amqpMessage.body = this._context.dataTransformer.encode(eventData.body); + amqpMessage.body = defaultDataTransformer.encode(eventData.body); const encodedMessage = message.encode(amqpMessage); let currentSize = this._sizeInBytes; diff --git a/sdk/eventhub/event-hubs/src/eventHubReceiver.ts b/sdk/eventhub/event-hubs/src/eventHubReceiver.ts index caf691aa0503..019b12090958 100644 --- a/sdk/eventhub/event-hubs/src/eventHubReceiver.ts +++ b/sdk/eventhub/event-hubs/src/eventHubReceiver.ts @@ -25,6 +25,7 @@ import { ConnectionContext } from "./connectionContext"; import { LinkEntity } from "./linkEntity"; import { EventPosition, getEventPositionFilter } from "./eventPosition"; import { AbortError, AbortSignalLike } from "@azure/abort-controller"; +import { defaultDataTransformer } from "./dataTransformer"; /** * @ignore @@ -230,7 +231,7 @@ export class EventHubReceiver extends LinkEntity { const data: EventDataInternal = fromRheaMessage(context.message); const receivedEventData: ReceivedEventData = { - body: this._context.dataTransformer.decode(context.message.body), + body: defaultDataTransformer.decode(context.message.body), properties: data.properties, offset: data.offset!, sequenceNumber: data.sequenceNumber!, diff --git a/sdk/eventhub/event-hubs/src/eventHubSender.ts b/sdk/eventhub/event-hubs/src/eventHubSender.ts index 284cfe79a54e..5f59df81b45b 100644 --- a/sdk/eventhub/event-hubs/src/eventHubSender.ts +++ b/sdk/eventhub/event-hubs/src/eventHubSender.ts @@ -31,6 +31,7 @@ import { SendOptions } from "./models/public"; import { getRetryAttemptTimeoutInMs } from "./util/retries"; import { AbortError, AbortSignalLike } from "@azure/abort-controller"; import { EventDataBatch, isEventDataBatch } from "./eventDataBatch"; +import { defaultDataTransformer } from "./dataTransformer"; /** * Describes the EventHubSender that will send event data to EventHub. @@ -322,7 +323,7 @@ export class EventHubSender extends LinkEntity { // Convert EventData to RheaMessage. for (let i = 0; i < events.length; i++) { const message = toRheaMessage(events[i], partitionKey); - message.body = this._context.dataTransformer.encode(events[i].body); + message.body = defaultDataTransformer.encode(events[i].body); messages[i] = message; } // Encode every amqp message and then convert every encoded message to amqp data section diff --git a/sdk/core/core-amqp/test/dataTransformer.spec.ts b/sdk/eventhub/event-hubs/test/dataTransformer.spec.ts similarity index 94% rename from sdk/core/core-amqp/test/dataTransformer.spec.ts rename to sdk/eventhub/event-hubs/test/dataTransformer.spec.ts index 6c089822a4ef..851bca8fb64f 100644 --- a/sdk/core/core-amqp/test/dataTransformer.spec.ts +++ b/sdk/eventhub/event-hubs/test/dataTransformer.spec.ts @@ -6,8 +6,7 @@ import * as chai from "chai"; const should = chai.should(); import * as assert from "assert"; import isBuffer from "is-buffer"; - -import { DefaultDataTransformer } from "../src"; +import { defaultDataTransformer } from "../src/dataTransformer"; describe("DataTransformer", function() { const objectBody: any = { @@ -38,9 +37,9 @@ describe("DataTransformer", function() { const nullBody: null = null; const undefinedBody: undefined = undefined; const emptyStringBody: string = ""; - const bufferbody: Buffer = Buffer.from("zzz", "utf8"); + const bufferBody: Buffer = Buffer.from("zzz", "utf8"); const hexBufferBody: Buffer = Buffer.from("7468697320697320612074c3a97374", "hex"); - const transformer = new DefaultDataTransformer(); + const transformer = defaultDataTransformer; it("should correctly encode/decode a string message body", function(done) { const encoded: any = transformer.encode(stringBody); @@ -115,11 +114,11 @@ describe("DataTransformer", function() { }); it("should correctly encode/decode a buffer message body", function(done) { - const encoded: any = transformer.encode(bufferbody); + const encoded: any = transformer.encode(bufferBody); encoded.typecode.should.equal(117); isBuffer(encoded.content).should.equal(true); const decoded: any = transformer.decode(encoded); - assert.deepEqual(decoded, bufferbody); + assert.deepEqual(decoded, bufferBody); done(); }); @@ -184,8 +183,8 @@ describe("DataTransformer", function() { }); it("should correctly decode a buffer message body", function(done) { - const decoded: any = transformer.decode(bufferbody); - assert.deepEqual(decoded, bufferbody); + const decoded: any = transformer.decode(bufferBody); + assert.deepEqual(decoded, bufferBody); done(); }); diff --git a/sdk/servicebus/service-bus/rollup.base.config.js b/sdk/servicebus/service-bus/rollup.base.config.js index 98577fd2e786..e584691da98e 100644 --- a/sdk/servicebus/service-bus/rollup.base.config.js +++ b/sdk/servicebus/service-bus/rollup.base.config.js @@ -133,7 +133,9 @@ export function browserConfig(test = false) { namedExports: { events: ["EventEmitter"], long: ["ZERO"], - "@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"] + "@opentelemetry/api": ["CanonicalCode", "SpanKind", "TraceFlags"], + chai: ["should", "assert"], + assert: ["equal", "deepEqual", "notEqual"] } }), diff --git a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts index 0b65e9778789..5d6f4d73a738 100644 --- a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts @@ -253,7 +253,6 @@ export class BatchingReceiverLite { this._createServiceBusMessage = (context: MessageAndDelivery) => { return new ServiceBusMessageImpl( - _connectionContext.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/src/core/managementClient.ts b/sdk/servicebus/service-bus/src/core/managementClient.ts index b1cc4e0dd928..8c2ba2c99d4a 100644 --- a/sdk/servicebus/service-bus/src/core/managementClient.ts +++ b/sdk/servicebus/service-bus/src/core/managementClient.ts @@ -47,6 +47,7 @@ import { OperationOptionsBase } from "./../modelsToBeSharedWithEventHubs"; import { AbortSignalLike } from "@azure/abort-controller"; import { ReceiveMode } from "../models"; import { translateServiceBusError } from "../serviceBusError"; +import { defaultDataTransformer } from "../dataTransformer"; /** * @internal @@ -489,7 +490,7 @@ export class ManagementClient extends LinkEntity { for (const msg of messages) { const decodedMessage = RheaMessageUtil.decode(msg.message); const message = fromRheaMessage(decodedMessage as any); - message.body = this._context.dataTransformer.decode(message.body); + message.body = defaultDataTransformer.decode(message.body); messageList.push(message); this._lastPeekedSequenceNumber = message.sequenceNumber!; } @@ -589,7 +590,7 @@ export class ManagementClient extends LinkEntity { if (!item.messageId) item.messageId = generate_uuid(); item.scheduledEnqueueTimeUtc = scheduledEnqueueTimeUtc; const amqpMessage = toRheaMessage(item); - amqpMessage.body = this._context.dataTransformer.encode(amqpMessage.body); + amqpMessage.body = defaultDataTransformer.encode(amqpMessage.body); try { const entry: any = { @@ -802,7 +803,6 @@ export class ManagementClient extends LinkEntity { for (const msg of messages) { const decodedMessage = RheaMessageUtil.decode(msg.message); const message = new ServiceBusMessageImpl( - this._context.dataTransformer, decodedMessage as any, { tag: msg["lock-token"] } as any, false, @@ -1017,7 +1017,7 @@ export class ManagementClient extends LinkEntity { ); const result = await this._makeManagementRequest(request, receiverLogger, options); return result.body["session-state"] - ? this._context.dataTransformer.decode(result.body["session-state"]) + ? defaultDataTransformer.decode(result.body["session-state"]) : result.body["session-state"]; } catch (err) { const error = translateServiceBusError(err); diff --git a/sdk/servicebus/service-bus/src/core/messageSender.ts b/sdk/servicebus/service-bus/src/core/messageSender.ts index 53e88d70bbac..cb94e01a92de 100644 --- a/sdk/servicebus/service-bus/src/core/messageSender.ts +++ b/sdk/servicebus/service-bus/src/core/messageSender.ts @@ -36,6 +36,7 @@ import { CreateMessageBatchOptions } from "../models"; import { OperationOptionsBase } from "../modelsToBeSharedWithEventHubs"; import { AbortSignalLike } from "@azure/abort-controller"; import { translateServiceBusError } from "../serviceBusError"; +import { defaultDataTransformer } from "../dataTransformer"; /** * @internal @@ -355,7 +356,7 @@ export class MessageSender extends LinkEntity { throwErrorIfConnectionClosed(this._context); try { const amqpMessage = toRheaMessage(data); - amqpMessage.body = this._context.dataTransformer.encode(data.body); + amqpMessage.body = defaultDataTransformer.encode(data.body); // TODO: this body of logic is really similar to what's in sendMessages. Unify what we can. let encodedMessage; @@ -413,7 +414,7 @@ export class MessageSender extends LinkEntity { // Convert Message to AmqpMessage. for (let i = 0; i < inputMessages.length; i++) { const amqpMessage = toRheaMessage(inputMessages[i]); - amqpMessage.body = this._context.dataTransformer.encode(inputMessages[i].body); + amqpMessage.body = defaultDataTransformer.encode(inputMessages[i].body); amqpMessages[i] = amqpMessage; try { encodedMessages[i] = RheaMessageUtil.encode(amqpMessage); diff --git a/sdk/servicebus/service-bus/src/core/streamingReceiver.ts b/sdk/servicebus/service-bus/src/core/streamingReceiver.ts index f49e4790dcf5..53c9e5db4a05 100644 --- a/sdk/servicebus/service-bus/src/core/streamingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/streamingReceiver.ts @@ -222,7 +222,6 @@ export class StreamingReceiver extends MessageReceiver { } const bMessage: ServiceBusMessageImpl = new ServiceBusMessageImpl( - this._context.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/src/dataTransformer.ts b/sdk/servicebus/service-bus/src/dataTransformer.ts new file mode 100644 index 000000000000..9801a4b6c0ac --- /dev/null +++ b/sdk/servicebus/service-bus/src/dataTransformer.ts @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { message } from "rhea-promise"; +import isBuffer from "is-buffer"; +import { Buffer } from "buffer"; +import { logErrorStackTrace, logger } from "./log"; + +/** + * The default data transformer that will be used by the Azure SDK. + * @internal + * @ingore + */ +export const defaultDataTransformer = { + /** + * A function that takes the body property from an EventData object + * and returns an encoded body (some form of AMQP type). + * + * @param {*} body The AMQP message body + * @return {DataSection} encodedBody - The encoded AMQP message body as an AMQP Data type + * (data section in rhea terms). Section object with following properties: + * - typecode: 117 (0x75) + * - content: The given AMQP message body as a Buffer. + * - multiple: true | undefined. + */ + encode(body: any): any { + let result: any; + if (isBuffer(body)) { + result = message.data_section(body); + } else { + // string, undefined, null, boolean, array, object, number should end up here + // coercing undefined to null as that will ensure that null value will be given to the + // customer on receive. + if (body === undefined) body = null; // tslint:disable-line + try { + const bodyStr = JSON.stringify(body); + result = message.data_section(Buffer.from(bodyStr, "utf8")); + } catch (err) { + const msg = + `An error occurred while executing JSON.stringify() on the given body ` + + body + + `${err ? err.stack : JSON.stringify(err)}`; + logger.warning("[encode] " + msg); + logErrorStackTrace(logger, err); + throw new Error(msg); + } + } + return result; + }, + + /** + * @property {Function} [decode] A function that takes the body property from an AMQP message + * (an AMQP Data type (data section in rhea terms)) and returns the decoded message body. + * If it cannot decode the body then it returns the body + * as-is. + * @param {DataSection} body The AMQP message body + * @return {*} decoded body or the given body as-is. + */ + decode(body: any): any { + let processedBody: any = body; + try { + if (body.content && isBuffer(body.content)) { + // This indicates that we are getting the AMQP described type. Let us try decoding it. + processedBody = body.content; + } + try { + // Trying to stringify and JSON.parse() anything else will fail flat and we shall return + // the original type back + const bodyStr: string = processedBody.toString("utf8"); + processedBody = JSON.parse(bodyStr); + } catch (err) { + logger.verbose( + "[decode] An error occurred while trying JSON.parse() on the received body. " + + "The error is %O", + err + ); + } + } catch (err) { + logger.verbose( + "[decode] An error occurred while decoding the received message body. The error is: %O", + err + ); + } + return processedBody; + } +}; diff --git a/sdk/servicebus/service-bus/src/serviceBusMessage.ts b/sdk/servicebus/service-bus/src/serviceBusMessage.ts index 91a7eb44650f..53321c61b905 100644 --- a/sdk/servicebus/service-bus/src/serviceBusMessage.ts +++ b/sdk/servicebus/service-bus/src/serviceBusMessage.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { AmqpAnnotatedMessage, Constants, DataTransformer } from "@azure/core-amqp"; +import { AmqpAnnotatedMessage, Constants } from "@azure/core-amqp"; import { Buffer } from "buffer"; import Long from "long"; import { @@ -11,6 +11,7 @@ import { uuid_to_string, Message as RheaMessage } from "rhea-promise"; +import { defaultDataTransformer } from "./dataTransformer"; import { messageLogger as logger } from "./log"; import { ReceiveMode } from "./models"; import { reorderLockToken } from "./util/utils"; @@ -769,7 +770,6 @@ export class ServiceBusMessageImpl implements ServiceBusReceivedMessage { * @internal */ constructor( - private readonly _dataTransformer: DataTransformer, msg: RheaMessage, delivery: Delivery, shouldReorderLockToken: boolean, @@ -782,7 +782,7 @@ export class ServiceBusMessageImpl implements ServiceBusReceivedMessage { this.lockToken = undefined; } if (msg.body) { - this.body = this._dataTransformer.decode(msg.body); + this.body = defaultDataTransformer.decode(msg.body); } // TODO: _amqpAnnotatedMessage is already being populated in fromRheaMessage(), no need to do it twice this._amqpAnnotatedMessage = AmqpAnnotatedMessage.fromRheaMessage(msg); diff --git a/sdk/servicebus/service-bus/src/serviceBusMessageBatch.ts b/sdk/servicebus/service-bus/src/serviceBusMessageBatch.ts index ecec8f528f40..e41bb888f3cb 100644 --- a/sdk/servicebus/service-bus/src/serviceBusMessageBatch.ts +++ b/sdk/servicebus/service-bus/src/serviceBusMessageBatch.ts @@ -22,6 +22,7 @@ import { } from "./diagnostics/instrumentServiceBusMessage"; import { createMessageSpan } from "./diagnostics/messageSpan"; import { TryAddOptions } from "./modelsToBeSharedWithEventHubs"; +import { defaultDataTransformer } from "./dataTransformer"; /** * @internal @@ -263,7 +264,7 @@ export class ServiceBusMessageBatchImpl implements ServiceBusMessageBatch { // Convert ServiceBusMessage to AmqpMessage. const amqpMessage = toRheaMessage(message); - amqpMessage.body = this._context.dataTransformer.encode(message.body); + amqpMessage.body = defaultDataTransformer.encode(message.body); let encodedMessage: Buffer; try { diff --git a/sdk/servicebus/service-bus/src/session/messageSession.ts b/sdk/servicebus/service-bus/src/session/messageSession.ts index 4b18c09d03a5..0294f7cea44a 100644 --- a/sdk/servicebus/service-bus/src/session/messageSession.ts +++ b/sdk/servicebus/service-bus/src/session/messageSession.ts @@ -621,7 +621,6 @@ export class MessageSession extends LinkEntity { } const bMessage = new ServiceBusMessageImpl( - this._context.dataTransformer, context.message!, context.delivery!, true, diff --git a/sdk/servicebus/service-bus/test/internal/dataTransformer.spec.ts b/sdk/servicebus/service-bus/test/internal/dataTransformer.spec.ts new file mode 100644 index 000000000000..45df00a6fe1e --- /dev/null +++ b/sdk/servicebus/service-bus/test/internal/dataTransformer.spec.ts @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Buffer } from "buffer"; +import * as chai from "chai"; +const should = chai.should(); +import * as assert from "assert"; +import isBuffer from "is-buffer"; +import { defaultDataTransformer } from "../../src/dataTransformer"; + +describe("DataTransformer", function() { + const objectBody: any = { + id: "123-456-789", + weight: 10, + isBlue: true, + siblings: [ + { + id: "098-789-564", + weight: 20, + isBlue: false + } + ] + }; + const arrayBody = [ + { + id: "098-789-564", + weight: 20, + isBlue: false + }, + 10, + 20, + "some string" + ]; + const stringBody: string = "some string"; + const booleanBody: boolean = true; + const numberBody: number = 10.2; + const nullBody: null = null; + const undefinedBody: undefined = undefined; + const emptyStringBody: string = ""; + const bufferBody: Buffer = Buffer.from("zzz", "utf8"); + const hexBufferBody: Buffer = Buffer.from("7468697320697320612074c3a97374", "hex"); + const transformer = defaultDataTransformer; + + it("should correctly encode/decode a string message body", function(done) { + const encoded: any = transformer.encode(stringBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + decoded.should.equal(stringBody); + done(); + }); + + it("should correctly encode/decode a number message body", function(done) { + const encoded: any = transformer.encode(numberBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + decoded.should.equal(numberBody); + done(); + }); + + it("should correctly encode/decode a boolean message body", function(done) { + const encoded: any = transformer.encode(booleanBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + decoded.should.equal(booleanBody); + done(); + }); + + it("should correctly encode/decode a null message body", function(done) { + const encoded: any = transformer.encode(nullBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + should.equal(decoded, nullBody); + done(); + }); + + it("should correctly encode/decode an undefined message body", function(done) { + const encoded: any = transformer.encode(undefinedBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + should.equal(decoded, nullBody); + done(); + }); + + it("should correctly encode/decode an empty string message body", function(done) { + const encoded: any = transformer.encode(emptyStringBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + decoded.should.equal(emptyStringBody); + done(); + }); + + it("should correctly encode/decode an array message body", function(done) { + const encoded: any = transformer.encode(arrayBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + assert.deepEqual(decoded, arrayBody); + done(); + }); + + it("should correctly encode/decode an object message body", function(done) { + const encoded: any = transformer.encode(objectBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + assert.deepEqual(decoded, objectBody); + done(); + }); + + it("should correctly encode/decode a buffer message body", function(done) { + const encoded: any = transformer.encode(bufferBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + assert.deepEqual(decoded, bufferBody); + done(); + }); + + it("should correctly encode/decode a hex buffer message body", function(done) { + const encoded: any = transformer.encode(hexBufferBody); + encoded.typecode.should.equal(117); + isBuffer(encoded.content).should.equal(true); + const decoded: any = transformer.decode(encoded); + assert.deepEqual(decoded, hexBufferBody); + done(); + }); + + describe("decode", function() { + // It is possible that we receive an AMQP value type from the messages that were sent with + // previously shipped version of the sdk. If so then we should be able to handle those scenarios. + it("should correctly decode a string message body", function(done) { + const decoded: any = transformer.decode(stringBody); + decoded.should.equal(stringBody); + done(); + }); + + it("should correctly decode a number message body", function(done) { + const decoded: any = transformer.decode(numberBody); + decoded.should.equal(numberBody); + done(); + }); + + it("should correctly decode a boolean message body", function(done) { + const decoded: any = transformer.decode(booleanBody); + decoded.should.equal(booleanBody); + done(); + }); + + it("should correctly decode a null message body", function(done) { + const decoded: any = transformer.decode(nullBody); + should.equal(decoded, nullBody); + done(); + }); + + it("should correctly decode an undefined message body", function(done) { + const decoded: any = transformer.decode(undefinedBody); + should.equal(decoded, undefined); + done(); + }); + + it("should correctly decode an empty string message body", function(done) { + const decoded: any = transformer.decode(emptyStringBody); + decoded.should.equal(emptyStringBody); + done(); + }); + + it("should correctly decode an array message body", function(done) { + const decoded: any = transformer.decode(arrayBody); + assert.deepEqual(decoded, arrayBody); + done(); + }); + + it("should correctly decode an object message body", function(done) { + const decoded: any = transformer.decode(objectBody); + assert.deepEqual(decoded, objectBody); + done(); + }); + + it("should correctly decode a buffer message body", function(done) { + const decoded: any = transformer.decode(bufferBody); + assert.deepEqual(decoded, bufferBody); + done(); + }); + + it("should correctly decode a hex buffer message body", function(done) { + const decoded: any = transformer.decode(hexBufferBody); + assert.deepEqual(decoded, hexBufferBody); + done(); + }); + }); +}); diff --git a/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts b/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts index f6afb3c727e3..fd37b28bc810 100644 --- a/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts +++ b/sdk/servicebus/service-bus/test/internal/serviceBusMessage.spec.ts @@ -10,13 +10,9 @@ import { Message as RheaMessage } from "rhea-promise"; import chai from "chai"; -import { Constants, DataTransformer } from "@azure/core-amqp"; +import { Constants } from "@azure/core-amqp"; const assert = chai.assert; -const fakeDataTransformer = { - encode: (data) => data, - decode: (data) => data -} as DataTransformer; const fakeDelivery = {} as Delivery; describe("ServiceBusMessageImpl LockToken unit tests", () => { @@ -35,7 +31,6 @@ describe("ServiceBusMessageImpl LockToken unit tests", () => { it("Lock token in peekLock mode", () => { const sbMessage = new ServiceBusMessageImpl( - fakeDataTransformer, amqpMessage, { tag: fakeDeliveryTag } as Delivery, false, @@ -47,7 +42,6 @@ describe("ServiceBusMessageImpl LockToken unit tests", () => { it("Lock token in receiveAndDelete mode", () => { const sbMessage = new ServiceBusMessageImpl( - fakeDataTransformer, amqpMessage, { tag: fakeDeliveryTag } as Delivery, false, @@ -95,13 +89,7 @@ describe("ServiceBusMessageImpl AmqpAnnotations unit tests", () => { user_id: "random_user_id" }; - const sbMessage = new ServiceBusMessageImpl( - fakeDataTransformer, - amqpMessage, - fakeDelivery, - false, - "peekLock" - ); + const sbMessage = new ServiceBusMessageImpl(amqpMessage, fakeDelivery, false, "peekLock"); it("headers match", () => { assert.equal(sbMessage._amqpAnnotatedMessage.header?.firstAcquirer, amqpMessage.first_acquirer); diff --git a/sdk/servicebus/service-bus/test/internal/unittestUtils.ts b/sdk/servicebus/service-bus/test/internal/unittestUtils.ts index 8a35bc44e0e9..3fb4190c63b9 100644 --- a/sdk/servicebus/service-bus/test/internal/unittestUtils.ts +++ b/sdk/servicebus/service-bus/test/internal/unittestUtils.ts @@ -8,7 +8,7 @@ import { ReceiverEvents, ReceiverOptions } from "rhea-promise"; -import { DefaultDataTransformer, Constants } from "@azure/core-amqp"; +import { Constants } from "@azure/core-amqp"; import { AccessToken } from "@azure/core-auth"; import { EventEmitter } from "events"; import { getUniqueName } from "../../src/util/utils"; @@ -88,7 +88,6 @@ export function createConnectionContextForTests( }, async close(): Promise {} }, - dataTransformer: new DefaultDataTransformer(), tokenCredential: { getToken() { return { From 70f3af181148ee4814ab03407b91fbf8477f54a5 Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Mon, 9 Nov 2020 21:12:46 -0800 Subject: [PATCH 22/35] Sync eng/common directory with azure-sdk-tools for PR 1178 (#12423) * Refactor eng/common/README.md * Add doc directory Co-authored-by: Chidozie Ononiwu --- eng/common/README.md | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/eng/common/README.md b/eng/common/README.md index f85e3396ae40..91bd71ae8ae1 100644 --- a/eng/common/README.md +++ b/eng/common/README.md @@ -1,26 +1,3 @@ # Common Engineering System -The `eng/common` directory contains engineering files that are common across the various azure-sdk language repos. -It should remain relatively small and only contain textual based files like scripts, configs, or templates. It -should not contain binary files as they don't play well with git. - -## Updating - -Any updates to files in the `eng/common` directory should be made in the [azure-sdk-tools](https://github.com/azure/azure-sdk-tools) repo. -All changes made will cause a PR to created in all subscribed azure-sdk language repos which will blindly replace all contents of -the `eng/common` directory in that repo. For that reason do **NOT** make changes to files in this directory in the individual azure-sdk -languages repos as they will be overwritten the next time an update is taken from the common azure-sdk-tools repo. - -### Workflow - -The 'Sync eng/common directory' PRs will be created in the language repositories when a pull request that touches the eng/common directory is submitted against the master branch. This will make it easier for changes to be tested in each individual language repo before merging the changes in the azure-sdk-tools repo. The workflow is explained below: - -1. Create a PR (**Tools PR**) in the `azure-sdk-tools` repo with changes to eng/common directory. -2. `azure-sdk-tools - sync - eng-common` pipeline is triggered for the **Tools PR** -3. The `azure-sdk-tools - sync - eng-common` pipeline queues test runs for template pipelines in various languages. These help you test your changes in the **Tools PR**. -4. If there are changes in the **Tools PR** that will affect the release stage you should approve the release test pipelines by clicking the approval gate. The test (template) pipeline will automatically release the next eligible version without needing manual intervention for the versioning. Please approve your test releases as quickly as possible. A race condition may occur due to someone else queueing the pipeline and going all the way to release using your version while yours is still waiting. If this occurs manually rerun the pipeline that failed. -5. If you make additional changes to your **Tools PR** repeat steps 1 - 4 until you have completed the necessary testing of your changes. This includes full releases of the template package, if necessary. -6. Sign off on CreateSyncPRs stage of the sync pipeline using the approval gate. This stage will create the **Sync PRs** in the various language repos. A link to each of the **Sync PRs** will show up in the **Tools PR** for you to click and review. -7. Go review and approve each of your **Sync PRs**. -8. Sign Off on the VerifyAndMerge stage. This will merge any remaining open **Sync PR** and also append `auto-merge` to the **Tools PR**. - * If a **Sync PR** has any failing checks, it will need to be manually merged, even if `/check-enforcer override` has been run ([azure-sdk-tools#1147](https://github.com/Azure/azure-sdk-tools/issues/1147)). +Updates under this directory should only be made in the `azure-sdk-tools` repo as any changes under this directory outside of that repo will end up getting overwritten with future updates. For information about making updates see [common engineering system docs](https://github.com/Azure/azure-sdk-tools/doc/common/common_engsys.md#common-engineering-system) From 126551c67a654e8789774ff324e87668db5c78f0 Mon Sep 17 00:00:00 2001 From: Lin Jian Date: Tue, 10 Nov 2020 14:57:39 +0800 Subject: [PATCH 23/35] version bump up (#12438) --- sdk/eventhub/eventhubs-checkpointstore-blob/package.json | 2 +- sdk/storage/storage-blob-changefeed/package.json | 2 +- sdk/storage/storage-blob/CHANGELOG.md | 2 +- sdk/storage/storage-blob/package.json | 4 ++-- .../storage-blob/src/generated/src/storageClientContext.ts | 4 ++-- sdk/storage/storage-blob/src/utils/constants.ts | 2 +- sdk/storage/storage-file-datalake/CHANGELOG.md | 2 +- sdk/storage/storage-file-datalake/package.json | 4 ++-- sdk/storage/storage-file-datalake/src/utils/constants.ts | 2 +- sdk/storage/storage-file-share/CHANGELOG.md | 2 +- sdk/storage/storage-file-share/package.json | 4 ++-- .../src/generated/src/storageClientContext.ts | 4 ++-- sdk/storage/storage-file-share/src/utils/constants.ts | 2 +- sdk/storage/storage-queue/CHANGELOG.md | 2 +- 14 files changed, 19 insertions(+), 19 deletions(-) diff --git a/sdk/eventhub/eventhubs-checkpointstore-blob/package.json b/sdk/eventhub/eventhubs-checkpointstore-blob/package.json index 26b81c5cd067..e65736e94823 100644 --- a/sdk/eventhub/eventhubs-checkpointstore-blob/package.json +++ b/sdk/eventhub/eventhubs-checkpointstore-blob/package.json @@ -61,7 +61,7 @@ "dependencies": { "@azure/event-hubs": "^5.0.0", "@azure/logger": "^1.0.0", - "@azure/storage-blob": "^12.3.0-beta.1", + "@azure/storage-blob": "^12.3.0", "events": "^3.0.0", "tslib": "^2.0.0" }, diff --git a/sdk/storage/storage-blob-changefeed/package.json b/sdk/storage/storage-blob-changefeed/package.json index 570938190ca3..8fb521a90a4e 100644 --- a/sdk/storage/storage-blob-changefeed/package.json +++ b/sdk/storage/storage-blob-changefeed/package.json @@ -95,7 +95,7 @@ ] }, "dependencies": { - "@azure/storage-blob": "^12.3.0-beta.1", + "@azure/storage-blob": "^12.3.0", "@azure/abort-controller": "^1.0.0", "@azure/core-http": "^1.2.0", "@azure/core-lro": "^1.0.2", diff --git a/sdk/storage/storage-blob/CHANGELOG.md b/sdk/storage/storage-blob/CHANGELOG.md index 1440ee0c6c37..3371f031dc12 100644 --- a/sdk/storage/storage-blob/CHANGELOG.md +++ b/sdk/storage/storage-blob/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 12.3.0-beta.2 (Unreleased) +## 12.3.0 (2020-11-10) - Added `BlockBlobClient.uploadData(data: Buffer | Blob | ArrayBuffer | ArrayBufferView, options)` for parallel uploading. It's avaiable in both Node.js and browsers. - Added new SAS permissions Move(m) and Execute(e) for Blob and Container. Also supports specifying an authorized object ID via `saoid` and a correlation ID via `scid` for user delegation SAS. diff --git a/sdk/storage/storage-blob/package.json b/sdk/storage/storage-blob/package.json index 6366accce0ca..cbc36f9de0a5 100644 --- a/sdk/storage/storage-blob/package.json +++ b/sdk/storage/storage-blob/package.json @@ -1,7 +1,7 @@ { "name": "@azure/storage-blob", "sdk-type": "client", - "version": "12.3.0-beta.2", + "version": "12.3.0", "description": "Microsoft Azure Storage SDK for JavaScript - Blob", "main": "./dist/index.js", "module": "./dist-esm/storage-blob/src/index.js", @@ -32,7 +32,7 @@ }, "scripts": { "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", - "build:autorest": "autorest ./swagger/README.md --typescript --package-version=12.3.0-beta.1 --use=@microsoft.azure/autorest.typescript@5.0.1", + "build:autorest": "autorest ./swagger/README.md --typescript --package-version=12.3.0 --use=@microsoft.azure/autorest.typescript@5.0.1", "build:es6": "tsc -p tsconfig.json", "build:nodebrowser": "rollup -c 2>&1", "build:samples": "npm run clean && npm run build:es6 && cross-env ONLY_NODE=true rollup -c 2>&1 && npm run build:prep-samples", diff --git a/sdk/storage/storage-blob/src/generated/src/storageClientContext.ts b/sdk/storage/storage-blob/src/generated/src/storageClientContext.ts index 6710606071bb..ee45e3ba2635 100644 --- a/sdk/storage/storage-blob/src/generated/src/storageClientContext.ts +++ b/sdk/storage/storage-blob/src/generated/src/storageClientContext.ts @@ -11,7 +11,7 @@ import * as coreHttp from "@azure/core-http"; const packageName = "azure-storage-blob"; -const packageVersion = "12.3.0-beta.1"; +const packageVersion = "12.3.0"; export class StorageClientContext extends coreHttp.ServiceClient { url: string; @@ -39,7 +39,7 @@ export class StorageClientContext extends coreHttp.ServiceClient { super(undefined, options); - this.version = '2020-02-10'; + this.version = "2020-02-10"; this.baseUri = "{url}"; this.requestContentType = "application/json; charset=utf-8"; this.url = url; diff --git a/sdk/storage/storage-blob/src/utils/constants.ts b/sdk/storage/storage-blob/src/utils/constants.ts index 92c5ac1aaf0e..39cdd2ad136e 100644 --- a/sdk/storage/storage-blob/src/utils/constants.ts +++ b/sdk/storage/storage-blob/src/utils/constants.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -export const SDK_VERSION: string = "12.3.0-beta.2"; +export const SDK_VERSION: string = "12.3.0"; export const SERVICE_VERSION: string = "2020-02-10"; export const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES: number = 256 * 1024 * 1024; // 256MB diff --git a/sdk/storage/storage-file-datalake/CHANGELOG.md b/sdk/storage/storage-file-datalake/CHANGELOG.md index 10659d9b75fc..bd6088e16a7e 100644 --- a/sdk/storage/storage-file-datalake/CHANGELOG.md +++ b/sdk/storage/storage-file-datalake/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 12.2.0-beta.2 (Unreleased) +## 12.2.0 (2020-11-10) - Bug fix - Fixes an issue where `DataLakePathClient.move()` will give an `InvalidSourceUri` error when the copy source name contains characters that need to be URL encoded. Fixed bug [11849](https://github.com/Azure/azure-sdk-for-js/issues/11849). diff --git a/sdk/storage/storage-file-datalake/package.json b/sdk/storage/storage-file-datalake/package.json index 533716201ee0..1ddddaae8e63 100644 --- a/sdk/storage/storage-file-datalake/package.json +++ b/sdk/storage/storage-file-datalake/package.json @@ -1,6 +1,6 @@ { "name": "@azure/storage-file-datalake", - "version": "12.2.0-beta.2", + "version": "12.2.0", "description": "Microsoft Azure Storage SDK for JavaScript - DataLake", "sdk-type": "client", "main": "./dist/index.js", @@ -102,7 +102,7 @@ "@azure/core-paging": "^1.1.1", "@azure/core-tracing": "1.0.0-preview.9", "@azure/logger": "^1.0.0", - "@azure/storage-blob": "^12.3.0-beta.1", + "@azure/storage-blob": "^12.3.0", "events": "^3.0.0", "tslib": "^2.0.0" }, diff --git a/sdk/storage/storage-file-datalake/src/utils/constants.ts b/sdk/storage/storage-file-datalake/src/utils/constants.ts index f12ca0190626..6971473ee212 100644 --- a/sdk/storage/storage-file-datalake/src/utils/constants.ts +++ b/sdk/storage/storage-file-datalake/src/utils/constants.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -export const SDK_VERSION: string = "12.2.0-beta.2"; +export const SDK_VERSION: string = "12.2.0"; export const SERVICE_VERSION: string = "2020-02-10"; export const KB: number = 1024; diff --git a/sdk/storage/storage-file-share/CHANGELOG.md b/sdk/storage/storage-file-share/CHANGELOG.md index 6f45f395ad6f..1bef8fabc26c 100644 --- a/sdk/storage/storage-file-share/CHANGELOG.md +++ b/sdk/storage/storage-file-share/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 12.3.0-beta.2 (Unreleased) +## 12.3.0 (2020-11-10) - Removed ability to create a ShareLeaseClient for a Share or Share Snapshot. This feature has been rescheduled for future release. - Replaced `ShareClient.setAccessTier()` with `ShareClient.setProperties()`, which can be used to set both Share Tier and Share Quota. diff --git a/sdk/storage/storage-file-share/package.json b/sdk/storage/storage-file-share/package.json index 779ed3f28c8e..ae51e18fff88 100644 --- a/sdk/storage/storage-file-share/package.json +++ b/sdk/storage/storage-file-share/package.json @@ -1,7 +1,7 @@ { "name": "@azure/storage-file-share", "sdk-type": "client", - "version": "12.3.0-beta.2", + "version": "12.3.0", "description": "Microsoft Azure Storage SDK for JavaScript - File", "main": "./dist/index.js", "module": "./dist-esm/src/index.js", @@ -28,7 +28,7 @@ }, "scripts": { "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", - "build:autorest": "autorest ./swagger/README.md --typescript --package-version=12.3.0-beta.1 --use=@microsoft.azure/autorest.typescript@5.0.1", + "build:autorest": "autorest ./swagger/README.md --typescript --package-version=12.3.0 --use=@microsoft.azure/autorest.typescript@5.0.1", "build:es6": "tsc -p tsconfig.json", "build:nodebrowser": "rollup -c 2>&1", "build:samples": "npm run clean && npm run build:es6 && cross-env ONLY_NODE=true rollup -c 2>&1 && npm run build:prep-samples", diff --git a/sdk/storage/storage-file-share/src/generated/src/storageClientContext.ts b/sdk/storage/storage-file-share/src/generated/src/storageClientContext.ts index 425367cc3303..e4cebd68b311 100644 --- a/sdk/storage/storage-file-share/src/generated/src/storageClientContext.ts +++ b/sdk/storage/storage-file-share/src/generated/src/storageClientContext.ts @@ -11,7 +11,7 @@ import * as coreHttp from "@azure/core-http"; const packageName = "azure-storage-file-share"; -const packageVersion = "12.3.0-beta.2"; +const packageVersion = "12.3.0"; export class StorageClientContext extends coreHttp.ServiceClient { version: string; @@ -44,7 +44,7 @@ export class StorageClientContext extends coreHttp.ServiceClient { super(undefined, options); - this.fileRangeWriteFromUrl = 'update'; + this.fileRangeWriteFromUrl = "update"; this.baseUri = "{url}"; this.requestContentType = "application/json; charset=utf-8"; this.version = version; diff --git a/sdk/storage/storage-file-share/src/utils/constants.ts b/sdk/storage/storage-file-share/src/utils/constants.ts index 9f72c54cf575..95f8a1be7ad3 100644 --- a/sdk/storage/storage-file-share/src/utils/constants.ts +++ b/sdk/storage/storage-file-share/src/utils/constants.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -export const SDK_VERSION: string = "12.3.0-beta.2"; +export const SDK_VERSION: string = "12.3.0"; export const SERVICE_VERSION: string = "2020-02-10"; export const FILE_MAX_SIZE_BYTES: number = 4 * 1024 * 1024 * 1024 * 1024; // 4TB diff --git a/sdk/storage/storage-queue/CHANGELOG.md b/sdk/storage/storage-queue/CHANGELOG.md index ab9daca4cdf0..5e67a8baa003 100644 --- a/sdk/storage/storage-queue/CHANGELOG.md +++ b/sdk/storage/storage-queue/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 12.2.0 (Unreleased) +## 12.2.0 (2020-11-10) - Updated Azure Storage Service API version to 2020-02-10. From 6c8c3e7861d825d1d43999dbeeae589a896989e6 Mon Sep 17 00:00:00 2001 From: KarishmaGhiya Date: Tue, 10 Nov 2020 11:29:16 -0800 Subject: [PATCH 24/35] update release date (#12448) --- sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md index 0cc977b3fbae..1c4f96587dc2 100644 --- a/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md +++ b/sdk/metricsadvisor/ai-metrics-advisor/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.0.0-beta.2 (Unreleased) +## 1.0.0-beta.2 (2020-11-10) - [Breaking] Combine `listAnomaliesForDetectionConfiguration()` and `listAnomaliesForAlert()` into overloads of `listAnomalies()` - [Breaking] Combine `listIncidentsForDetectionConfiguration()` and `listIncidentsForAlert()` into overloads of `listIncidents()` From 8a96b006556e5dd0cfdb2c6e0a4b3907ac90943c Mon Sep 17 00:00:00 2001 From: Harsha Nalluru Date: Tue, 10 Nov 2020 12:12:13 -0800 Subject: [PATCH 25/35] [Service Bus] Mention "CORS not supported" in readme (#12341) ### Issue https://github.com/Azure/azure-sdk-for-js/issues/4983 --- sdk/servicebus/service-bus/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/servicebus/service-bus/README.md b/sdk/servicebus/service-bus/README.md index 7e2355aae9e5..ec3650dfd5a5 100644 --- a/sdk/servicebus/service-bus/README.md +++ b/sdk/servicebus/service-bus/README.md @@ -312,6 +312,8 @@ You can read more about how sessions work [here][docsms_messagesessions]. - Supports authentication with a service bus connection string as well as with the AAD credentials from `@azure/identity` similar to the `ServiceBusClient`. +Note: Service Bus doesn't support setting CORS rules for namespaces yet, hence `ServiceBusAdministrationClient` won't work in the browser without disabling web-security. For more info, refer [here](https://github.com/Azure/azure-sdk-for-js/issues/4983). + ```js // Get the connection string from the portal // OR From 6a97120b18e7b02efe982238db7c69708cd001fd Mon Sep 17 00:00:00 2001 From: Azure SDK Bot <53356347+azure-sdk@users.noreply.github.com> Date: Tue, 10 Nov 2020 12:26:44 -0800 Subject: [PATCH 26/35] Fix broken eng/common doc link (#12447) Co-authored-by: Chidozie Ononiwu --- eng/common/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/common/README.md b/eng/common/README.md index 91bd71ae8ae1..b9867f0705e2 100644 --- a/eng/common/README.md +++ b/eng/common/README.md @@ -1,3 +1,3 @@ # Common Engineering System -Updates under this directory should only be made in the `azure-sdk-tools` repo as any changes under this directory outside of that repo will end up getting overwritten with future updates. For information about making updates see [common engineering system docs](https://github.com/Azure/azure-sdk-tools/doc/common/common_engsys.md#common-engineering-system) +Updates under this directory should only be made in the `azure-sdk-tools` repo as any changes under this directory outside of that repo will end up getting overwritten with future updates. For information about making updates see [common engineering system docs](https://github.com/Azure/azure-sdk-tools/blob/master/doc/common/common_engsys.md) From 007104004f4c63698d60f54e25d1069eec5e59e4 Mon Sep 17 00:00:00 2001 From: Ramya Rao Date: Tue, 10 Nov 2020 12:41:08 -0800 Subject: [PATCH 27/35] [Service Bus] Update client side validation for settling msg, renewing locks (#12404) --- .../service-bus/src/receivers/receiver.ts | 44 +++++-------- .../src/receivers/sessionReceiver.ts | 11 +++- .../service-bus/src/receivers/shared.ts | 66 +++++++------------ .../service-bus/src/serviceBusMessage.ts | 8 --- sdk/servicebus/service-bus/src/util/errors.ts | 55 ++++++++++++++-- .../test/backupMessageSettlement.spec.ts | 2 +- .../service-bus/test/batchReceiver.spec.ts | 29 ++++---- .../service-bus/test/deferredMessage.spec.ts | 2 +- .../test/receiveAndDeleteMode.spec.ts | 22 +++---- .../service-bus/test/renewLock.spec.ts | 3 +- .../service-bus/test/serviceBusClient.spec.ts | 9 ++- .../test/streamingReceiver.spec.ts | 18 ++--- .../test/streamingReceiverSessions.spec.ts | 20 ++---- 13 files changed, 150 insertions(+), 139 deletions(-) diff --git a/sdk/servicebus/service-bus/src/receivers/receiver.ts b/sdk/servicebus/service-bus/src/receivers/receiver.ts index 868779f2a9fb..2f78cd6cda54 100644 --- a/sdk/servicebus/service-bus/src/receivers/receiver.ts +++ b/sdk/servicebus/service-bus/src/receivers/receiver.ts @@ -14,11 +14,11 @@ import { ServiceBusReceivedMessage } from "../serviceBusMessage"; import { ConnectionContext } from "../connectionContext"; import { getAlreadyReceivingErrorMsg, - getErrorMessageNotSupportedInReceiveAndDeleteMode, getReceiverClosedErrorMsg, throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing, - throwTypeErrorIfParameterNotLong + throwTypeErrorIfParameterNotLong, + throwErrorIfInvalidOperationOnMessage } from "../util/errors"; import { OnError, OnMessage, ReceiveOptions } from "../core/messageReceiver"; import { StreamingReceiverInitArgs, StreamingReceiver } from "../core/streamingReceiver"; @@ -155,7 +155,7 @@ export interface ServiceBusReceiver { * if the lock on the message has expired or the AMQP link with which the message was received is * no longer alive. The latter can happen if the receiver was explicitly closed by the user or the * AMQP link got closed by the library due to network loss or service error. - * @throws Error if the message is already settled. To avoid this error check the `isSettled` + * @throws Error if the message is already settled. * property on the message if you are not sure whether the message is settled. * @throws Error if used in `receiveAndDelete` mode because all messages received in this mode * are pre-settled. To avoid this error, update your code to not settle a message which is received @@ -178,7 +178,7 @@ export interface ServiceBusReceiver { * if the lock on the message has expired or the AMQP link with which the message was received is * no longer alive. The latter can happen if the receiver was explicitly closed by the user or the * AMQP link got closed by the library due to network loss or service error. - * @throws Error if the message is already settled. To avoid this error check the `isSettled` + * @throws Error if the message is already settled. * property on the message if you are not sure whether the message is settled. * @throws Error if used in `receiveAndDelete` mode because all messages received in this mode * are pre-settled. To avoid this error, update your code to not settle a message which is received @@ -206,7 +206,7 @@ export interface ServiceBusReceiver { * if the lock on the message has expired or the AMQP link with which the message was received is * no longer alive. The latter can happen if the receiver was explicitly closed by the user or the * AMQP link got closed by the library due to network loss or service error. - * @throws Error if the message is already settled. To avoid this error check the `isSettled` + * @throws Error if the message is already settled. * property on the message if you are not sure whether the message is settled. * @throws Error if used in `receiveAndDelete` mode because all messages received in this mode * are pre-settled. To avoid this error, update your code to not settle a message which is received @@ -234,7 +234,7 @@ export interface ServiceBusReceiver { * if the lock on the message has expired or the AMQP link with which the message was received is * no longer alive. The latter can happen if the receiver was explicitly closed by the user or the * AMQP link got closed by the library due to network loss or service error. - * @throws Error if the message is already settled. To avoid this error check the `isSettled` + * @throws Error if the message is already settled. * property on the message if you are not sure whether the message is settled. * @throws Error if used in `receiveAndDelete` mode because all messages received in this mode * are pre-settled. To avoid this error, update your code to not settle a message which is received @@ -624,6 +624,8 @@ export class ServiceBusReceiverImpl implements ServiceBusReceiver { } async completeMessage(message: ServiceBusReceivedMessage): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return completeMessage(msgImpl, this._context, this.entityPath); } @@ -632,6 +634,8 @@ export class ServiceBusReceiverImpl implements ServiceBusReceiver { message: ServiceBusReceivedMessage, propertiesToModify?: { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return abandonMessage(msgImpl, this._context, this.entityPath, propertiesToModify); } @@ -640,6 +644,8 @@ export class ServiceBusReceiverImpl implements ServiceBusReceiver { message: ServiceBusReceivedMessage, propertiesToModify?: { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return deferMessage(msgImpl, this._context, this.entityPath, propertiesToModify); } @@ -648,35 +654,19 @@ export class ServiceBusReceiverImpl implements ServiceBusReceiver { message: ServiceBusReceivedMessage, options?: DeadLetterOptions & { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return deadLetterMessage(msgImpl, this._context, this.entityPath, options); } async renewMessageLock(message: ServiceBusReceivedMessage): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); + const msgImpl = message as ServiceBusMessageImpl; - if (!msgImpl.delivery) { - throw new Error("A peeked message does not have a lock to be renewed."); - } let associatedLinkName: string | undefined; - let error: Error | undefined; - if (!message.lockToken) { - error = new Error( - getErrorMessageNotSupportedInReceiveAndDeleteMode(`renew the lock on the message`) - ); - } else if (msgImpl.delivery.remote_settled) { - error = new Error(`Failed to renew the lock as this message is already settled.`); - } - if (error) { - logger.logError( - error, - "[%s] An error occurred when renewing the lock on the message with id '%s'", - this._context.connectionId, - message.messageId - ); - throw error; - } - if (msgImpl.delivery.link) { const associatedReceiver = this._context.getReceiverFromCache(msgImpl.delivery.link.name); associatedLinkName = associatedReceiver?.name; diff --git a/sdk/servicebus/service-bus/src/receivers/sessionReceiver.ts b/sdk/servicebus/service-bus/src/receivers/sessionReceiver.ts index 1dab97d36632..fa5efa6ef00f 100644 --- a/sdk/servicebus/service-bus/src/receivers/sessionReceiver.ts +++ b/sdk/servicebus/service-bus/src/receivers/sessionReceiver.ts @@ -10,7 +10,8 @@ import { getReceiverClosedErrorMsg, throwErrorIfConnectionClosed, throwTypeErrorIfParameterMissing, - throwTypeErrorIfParameterNotLong + throwTypeErrorIfParameterNotLong, + throwErrorIfInvalidOperationOnMessage } from "../util/errors"; import { OnError, OnMessage } from "../core/messageReceiver"; import { @@ -494,6 +495,8 @@ export class ServiceBusSessionReceiverImpl implements ServiceBusSessionReceiver } async completeMessage(message: ServiceBusReceivedMessage): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return completeMessage(msgImpl, this._context, this.entityPath); } @@ -502,6 +505,8 @@ export class ServiceBusSessionReceiverImpl implements ServiceBusSessionReceiver message: ServiceBusReceivedMessage, propertiesToModify?: { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return abandonMessage(msgImpl, this._context, this.entityPath, propertiesToModify); } @@ -510,6 +515,8 @@ export class ServiceBusSessionReceiverImpl implements ServiceBusSessionReceiver message: ServiceBusReceivedMessage, propertiesToModify?: { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return deferMessage(msgImpl, this._context, this.entityPath, propertiesToModify); } @@ -518,6 +525,8 @@ export class ServiceBusSessionReceiverImpl implements ServiceBusSessionReceiver message: ServiceBusReceivedMessage, options?: DeadLetterOptions & { [key: string]: any } ): Promise { + this._throwIfReceiverOrConnectionClosed(); + throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId); const msgImpl = message as ServiceBusMessageImpl; return deadLetterMessage(msgImpl, this._context, this.entityPath, options); } diff --git a/sdk/servicebus/service-bus/src/receivers/shared.ts b/sdk/servicebus/service-bus/src/receivers/shared.ts index f627b4736a94..4ec74b70de5a 100644 --- a/sdk/servicebus/service-bus/src/receivers/shared.ts +++ b/sdk/servicebus/service-bus/src/receivers/shared.ts @@ -14,8 +14,8 @@ import { } from "../serviceBusMessage"; import { DispositionStatusOptions } from "../core/managementClient"; import { ConnectionContext } from "../connectionContext"; -import { getErrorMessageNotSupportedInReceiveAndDeleteMode } from "../util/errors"; import { ErrorNameConditionMapper } from "@azure/core-amqp"; +import { MessageAlreadySettled } from "../util/errors"; /** * @internal @@ -202,14 +202,29 @@ function settleMessage( entityPath: string, options?: DispositionStatusOptions ): Promise { - if (!message.delivery) { - throw new Error("A peeked message cannot be settled."); + const isDeferredMessage = !message.delivery.link; + const receiver = isDeferredMessage + ? undefined + : context.getReceiverFromCache(message.delivery.link.name, message.sessionId); + const associatedLinkName = receiver?.name; + + let error: Error | undefined; + if (message.delivery.remote_settled) { + error = new Error(MessageAlreadySettled); + } else if ( + !isDeferredMessage && + (!receiver || !receiver.isOpen()) && + message.sessionId != undefined + ) { + error = translateServiceBusError({ + description: + `Failed to ${operation} the message as the AMQP link with which the message was ` + + `received is no longer alive.`, + condition: ErrorNameConditionMapper.SessionLockLostError + }); } - if (!message.lockToken) { - const error = new Error( - getErrorMessageNotSupportedInReceiveAndDeleteMode(`${operation} the message`) - ); + if (error) { receiverLogger.logError( error, "[%s] An error occurred when settling a message with id '%s'", @@ -218,41 +233,6 @@ function settleMessage( ); throw error; } - const isDeferredMessage = !message.delivery.link; - const receiver = isDeferredMessage - ? undefined - : context.getReceiverFromCache(message.delivery.link.name, message.sessionId); - const associatedLinkName = receiver?.name; - - if (!isDeferredMessage) { - // In case the message wasn't from a deferred queue, - // 1. We can verify the remote_settled flag on the delivery - // - If the flag is true, throw an error since the message has been settled (Specifically, with a receive link) - // - If the flag is false, we can't say that the message has not been settled - // since settling with the management link won't update the delivery (In this case, service would throw an error) - // 2. If the message has a session-id and if the associated receiver link is unavailable, - // then throw an error since we need a lock on the session to settle the message. - let error: Error | undefined; - if (message.delivery.remote_settled) { - error = new Error(`Failed to ${operation} the message as this message is already settled.`); - } else if ((!receiver || !receiver.isOpen()) && message.sessionId != undefined) { - error = translateServiceBusError({ - description: - `Failed to ${operation} the message as the AMQP link with which the message was ` + - `received is no longer alive.`, - condition: ErrorNameConditionMapper.SessionLockLostError - }); - } - if (error) { - receiverLogger.logError( - error, - "[%s] An error occurred when settling a message with id '%s'", - context.connectionId, - message.messageId - ); - throw error; - } - } // Message Settlement with managementLink // 1. If the received message is deferred as such messages can only be settled using managementLink @@ -260,7 +240,7 @@ function settleMessage( if (isDeferredMessage || ((!receiver || !receiver.isOpen()) && message.sessionId == undefined)) { return context .getManagementClient(entityPath) - .updateDispositionStatus(message.lockToken, operation, { + .updateDispositionStatus(message.lockToken!, operation, { ...options, associatedLinkName, sessionId: message.sessionId diff --git a/sdk/servicebus/service-bus/src/serviceBusMessage.ts b/sdk/servicebus/service-bus/src/serviceBusMessage.ts index 53321c61b905..a3253bd9f9de 100644 --- a/sdk/servicebus/service-bus/src/serviceBusMessage.ts +++ b/sdk/servicebus/service-bus/src/serviceBusMessage.ts @@ -758,14 +758,6 @@ export class ServiceBusMessageImpl implements ServiceBusReceivedMessage { * @readonly */ readonly deadLetterErrorDescription?: string; - /** - * @property Boolean denoting if the message has already been settled. - * @readonly - */ - public get isSettled(): boolean { - return this.delivery.remote_settled; - } - /** * @internal */ diff --git a/sdk/servicebus/service-bus/src/util/errors.ts b/sdk/servicebus/service-bus/src/util/errors.ts index e537b7eb647d..317ec3cacd7b 100644 --- a/sdk/servicebus/service-bus/src/util/errors.ts +++ b/sdk/servicebus/service-bus/src/util/errors.ts @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { logger } from "../log"; +import { logger, receiverLogger } from "../log"; import Long from "long"; import { ConnectionContext } from "../connectionContext"; +import { ServiceBusReceivedMessage } from "../serviceBusMessage"; +import { ReceiveMode } from "../models"; /** * Error message to use when EntityPath in connection string does not match the @@ -190,10 +192,51 @@ export function throwTypeErrorIfParameterIsEmptyString( /** * @internal * @ignore - * Gets error message for when an operation is not supported in ReceiveAndDelete mode - * @param failedToDo A string to add to the placeholder in the error message. Denotes the action - * that is not supported in ReceiveAndDelete mode + * The error message for operations on the receiver that are invalid for a message received in receiveAndDelete mode. */ -export function getErrorMessageNotSupportedInReceiveAndDeleteMode(failedToDo: string): string { - return `Failed to ${failedToDo} as the operation is only supported in 'PeekLock' receive mode.`; +export const InvalidOperationInReceiveAndDeleteMode = + "The operation is not supported in 'receiveAndDelete' receive mode."; + +/** + * @internal + * @ignore + * The error message for operations on the receiver that are invalid for a peeked message. + */ +export const InvalidOperationForPeekedMessage = + "This operation is not supported for peeked messages. Only messages received using 'receiveMessages()', 'subscribe()' and 'getMessageIterator()' methods on the receiver in 'peekLock' receive mode can be settled."; + +/** + * @internal + * @ignore + * The error message for when one attempts to settle an already settled message. + */ +export const MessageAlreadySettled = "The message has either been deleted or already settled"; + +/** + * Throws error if the ServiceBusReceivedMessage cannot be settled. + * @internal + * @ignore + */ +export function throwErrorIfInvalidOperationOnMessage( + message: ServiceBusReceivedMessage, + receiveMode: ReceiveMode, + connectionId: string +) { + let error: Error | undefined; + + if (receiveMode === "receiveAndDelete") { + error = new Error(InvalidOperationInReceiveAndDeleteMode); + } else if (!message.lockToken) { + error = new Error(InvalidOperationForPeekedMessage); + } + + if (error) { + receiverLogger.logError( + error, + "[%s] An error occurred for message with id '%s'", + connectionId, + message.messageId + ); + throw error; + } } diff --git a/sdk/servicebus/service-bus/test/backupMessageSettlement.spec.ts b/sdk/servicebus/service-bus/test/backupMessageSettlement.spec.ts index 4cfbbfd2838f..e2d77580a222 100644 --- a/sdk/servicebus/service-bus/test/backupMessageSettlement.spec.ts +++ b/sdk/servicebus/service-bus/test/backupMessageSettlement.spec.ts @@ -258,7 +258,7 @@ describe("Message settlement After Receiver is Closed - Through ManagementLink", ? TestMessage.getSessionSample() : TestMessage.getSample(); const msg = await sendReceiveMsg(testMessages); - await receiver.close(); + const msgDeliveryLink = (msg as ServiceBusMessageImpl).delivery.link.name; if (entityNames.usesSessions) { diff --git a/sdk/servicebus/service-bus/test/batchReceiver.spec.ts b/sdk/servicebus/service-bus/test/batchReceiver.spec.ts index a06e36d5959a..7903ba9cdb7d 100644 --- a/sdk/servicebus/service-bus/test/batchReceiver.spec.ts +++ b/sdk/servicebus/service-bus/test/batchReceiver.spec.ts @@ -5,7 +5,7 @@ import chai from "chai"; import Long from "long"; import chaiAsPromised from "chai-as-promised"; import { ServiceBusMessage, delay, ProcessErrorArgs } from "../src"; -import { getAlreadyReceivingErrorMsg } from "../src/util/errors"; +import { getAlreadyReceivingErrorMsg, InvalidOperationForPeekedMessage } from "../src/util/errors"; import { TestClientType, TestMessage } from "./utils/testUtils"; import { ServiceBusReceiver, ServiceBusReceiverImpl } from "../src/receivers/receiver"; import { ServiceBusSender } from "../src/sender"; @@ -38,12 +38,7 @@ let deadLetterReceiver: ServiceBusReceiver; async function beforeEachTest(entityType: TestClientType): Promise { entityNames = await serviceBusClient.test.createTestEntities(entityType); - receiver = await serviceBusClient.test.createPeekLockReceiver(entityNames, { - // prior to a recent change the behavior was always to _not_ auto-renew locks. - // for compat with these tests I'm just disabling this. There are tests in renewLocks.spec.ts that - // ensure lock renewal does work with batching. - maxAutoLockRenewalDurationInMs: 0 - }); + receiver = await serviceBusClient.test.createPeekLockReceiver(entityNames); sender = serviceBusClient.test.addToCleanup( serviceBusClient.createSender(entityNames.queue ?? entityNames.topic!) @@ -389,13 +384,18 @@ describe("Batching Receiver", () => { await sender.sendMessages(testMessages); const [peekedMsg] = await receiver.peekMessages(1); + if (!peekedMsg) { + // Sometimes the peek call does not return any messages :( + return; + } + should.equal( - !(peekedMsg as any)["delivery"], + !peekedMsg.lockToken, true, - "Peeked msg was not meant to have delivery! We use this assumption to differentiate between peeked msg and other messages." + "Peeked msg was not meant to have lockToken! We use this assumption to differentiate between peeked msg and other messages." ); - const expectedErrorMsg = "A peeked message cannot be settled."; + const expectedErrorMsg = InvalidOperationForPeekedMessage; try { await receiver.completeMessage(peekedMsg); assert.fail("completeMessage should have failed"); @@ -782,11 +782,10 @@ describe("Batching Receiver", () => { : TestMessage.getSample(); await sender.sendMessages(testMessages); - // If using sessions, we need a receiver with lock renewal disabled so that + // We need a receiver with lock renewal disabled so that // the message lands back in the queue/subscription to be picked up again. + await receiver.close(); if (entityNames.usesSessions) { - await receiver.close(); - receiver = await serviceBusClient.test.acceptSessionWithPeekLock( entityNames, testMessages.sessionId!, @@ -794,6 +793,10 @@ describe("Batching Receiver", () => { maxAutoLockRenewalDurationInMs: 0 } ); + } else { + receiver = await serviceBusClient.test.createPeekLockReceiver(entityNames, { + maxAutoLockRenewalDurationInMs: 0 + }); } let batch = await receiver.receiveMessages(1); diff --git a/sdk/servicebus/service-bus/test/deferredMessage.spec.ts b/sdk/servicebus/service-bus/test/deferredMessage.spec.ts index a334b41a01ae..2ed438120780 100644 --- a/sdk/servicebus/service-bus/test/deferredMessage.spec.ts +++ b/sdk/servicebus/service-bus/test/deferredMessage.spec.ts @@ -106,7 +106,7 @@ describe("Deferred Messages", () => { should.equal( !!(deferredMsg as any)["delivery"], true, - "Deferred msg should have delivery! We use this assumption to differentiate between peeked msg and other messages." + "Deferred msg should have delivery! We use this assumption to differentiate between deferred msg and other messages when settling." ); should.equal(deferredMsg.body, testMessage.body, "MessageBody is different than expected"); should.equal( diff --git a/sdk/servicebus/service-bus/test/receiveAndDeleteMode.spec.ts b/sdk/servicebus/service-bus/test/receiveAndDeleteMode.spec.ts index 5b77030efecf..b56c9457cab0 100644 --- a/sdk/servicebus/service-bus/test/receiveAndDeleteMode.spec.ts +++ b/sdk/servicebus/service-bus/test/receiveAndDeleteMode.spec.ts @@ -15,7 +15,7 @@ import { import { TestClientType, TestMessage, checkWithTimeout } from "./utils/testUtils"; -import { getErrorMessageNotSupportedInReceiveAndDeleteMode } from "../src/util/errors"; +import { InvalidOperationInReceiveAndDeleteMode } from "../src/util/errors"; import { ServiceBusSender } from "../src/sender"; import { EntityName, @@ -242,9 +242,9 @@ describe("receive and delete", () => { return msgs[0]; } - const testError = (err: Error, operation: DispositionType): void => { - expect(err.message.toLowerCase(), "ErrorMessage is different than expected").includes( - `failed to ${operation} the message as the operation is only supported in \'peeklock\' receive mode.` + const testError = (err: Error): void => { + expect(err.message, "ErrorMessage is different than expected").equals( + InvalidOperationInReceiveAndDeleteMode ); }; @@ -266,7 +266,7 @@ describe("receive and delete", () => { } } catch (err) { errorWasThrown = true; - testError(err, operation); + testError(err); } should.equal(errorWasThrown, true, "Error thrown flag must be true"); @@ -320,7 +320,7 @@ describe("receive and delete", () => { await receiver.renewMessageLock(msg).catch((err) => { should.equal( err.message, - getErrorMessageNotSupportedInReceiveAndDeleteMode("renew the lock on the message"), + InvalidOperationInReceiveAndDeleteMode, "ErrorMessage is different than expected" ); errorWasThrown = true; @@ -453,9 +453,9 @@ describe("receive and delete", () => { return deferredMsg; } - const testError = (err: Error, operation: DispositionType): void => { - expect(err.message.toLowerCase(), "ErrorMessage is different than expected").includes( - `failed to ${operation} the message as the operation is only supported in \'peeklock\' receive mode.` + const testError = (err: Error): void => { + expect(err.message, "ErrorMessage is different than expected").equals( + InvalidOperationInReceiveAndDeleteMode ); }; @@ -477,7 +477,7 @@ describe("receive and delete", () => { } } catch (err) { errorWasThrown = true; - testError(err, operation); + testError(err); } should.equal(errorWasThrown, true, "Error thrown flag must be true"); @@ -521,7 +521,7 @@ describe("receive and delete", () => { await receiver.renewMessageLock(deferredMsg).catch((err) => { should.equal( err.message, - getErrorMessageNotSupportedInReceiveAndDeleteMode("renew the lock on the message"), + InvalidOperationInReceiveAndDeleteMode, "ErrorMessage is different than expected" ); errorWasThrown = true; diff --git a/sdk/servicebus/service-bus/test/renewLock.spec.ts b/sdk/servicebus/service-bus/test/renewLock.spec.ts index b256b300279e..cef0eaa81161 100644 --- a/sdk/servicebus/service-bus/test/renewLock.spec.ts +++ b/sdk/servicebus/service-bus/test/renewLock.spec.ts @@ -18,6 +18,7 @@ import { ServiceBusReceiver } from "../src/receivers/receiver"; import { ServiceBusSender } from "../src/sender"; import { ServiceBusReceivedMessage } from "../src/serviceBusMessage"; import { ProcessErrorArgs } from "../src/models"; +import { InvalidOperationForPeekedMessage } from "../src/util/errors"; describe("Message Lock Renewal", () => { let serviceBusClient: ServiceBusClientForTests; @@ -78,7 +79,7 @@ describe("Message Lock Renewal", () => { await receiver.renewMessageLock(peekedMsg); assert.fail("renewMessageLock should have failed"); } catch (error) { - should.equal(error.message, "A peeked message does not have a lock to be renewed."); + should.equal(error.message, InvalidOperationForPeekedMessage); } // Clean up any left over messages diff --git a/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts b/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts index 7b747fa8c801..e2676ca7b801 100644 --- a/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts +++ b/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts @@ -501,9 +501,10 @@ describe("ServiceBusClient live tests", () => { caughtError = error; } - const expectedErrorMsg = - `Failed to ${operation} the message as the AMQP link with which the message was ` + - `received is no longer alive.`; + const expectedErrorMsg = getReceiverClosedErrorMsg( + receiver.entityPath, + receivedMessage.sessionId + ); should.equal(caughtError && caughtError.message, expectedErrorMsg); } @@ -730,6 +731,8 @@ describe("ServiceBusClient live tests", () => { await beforeEachTest(noSessionTestClientType, entityToClose); await testReceiver(getReceiverClosedErrorMsg(receiver.entityPath)); + + await testAllDispositions(); }); it( diff --git a/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts b/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts index 1abbbc5f79e3..508e3ce5b874 100644 --- a/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts +++ b/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts @@ -4,7 +4,7 @@ import chai from "chai"; import chaiAsPromised from "chai-as-promised"; import { ServiceBusReceivedMessage, delay, ProcessErrorArgs } from "../src"; -import { getAlreadyReceivingErrorMsg } from "../src/util/errors"; +import { getAlreadyReceivingErrorMsg, MessageAlreadySettled } from "../src/util/errors"; import { TestMessage, checkWithTimeout, TestClientType } from "./utils/testUtils"; import { DispositionType, ServiceBusMessageImpl } from "../src/serviceBusMessage"; import { ServiceBusReceiver } from "../src/receivers/receiver"; @@ -494,12 +494,8 @@ describe("Streaming Receiver Tests", () => { await beforeEachTest(); }); - const testError = (err: Error, operation: DispositionType): void => { - should.equal( - err.message, - `Failed to ${operation} the message as this message is already settled.`, - "ErrorMessage is different than expected" - ); + const testError = (err: Error): void => { + should.equal(err.message, MessageAlreadySettled, "ErrorMessage is different than expected"); errorWasThrown = true; }; @@ -544,13 +540,13 @@ describe("Streaming Receiver Tests", () => { await testPeekMsgsLength(receiver, 0); if (operation === DispositionType.complete) { - await receiver.completeMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.completeMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.abandon) { - await receiver.abandonMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.abandonMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.deadletter) { - await receiver.deadLetterMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.deadLetterMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.defer) { - await receiver.deferMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.deferMessage(receivedMsgs[0]).catch((err) => testError(err)); } should.equal(errorWasThrown, true, "Error thrown flag must be true"); diff --git a/sdk/servicebus/service-bus/test/streamingReceiverSessions.spec.ts b/sdk/servicebus/service-bus/test/streamingReceiverSessions.spec.ts index 813c92863a43..d1c54605e4de 100644 --- a/sdk/servicebus/service-bus/test/streamingReceiverSessions.spec.ts +++ b/sdk/servicebus/service-bus/test/streamingReceiverSessions.spec.ts @@ -4,7 +4,7 @@ import chai from "chai"; import chaiAsPromised from "chai-as-promised"; import { ServiceBusReceivedMessage, delay, ProcessErrorArgs } from "../src"; -import { getAlreadyReceivingErrorMsg } from "../src/util/errors"; +import { getAlreadyReceivingErrorMsg, MessageAlreadySettled } from "../src/util/errors"; import { TestClientType, TestMessage, checkWithTimeout } from "./utils/testUtils"; import { DispositionType } from "../src/serviceBusMessage"; import { @@ -530,12 +530,8 @@ describe("Streaming with sessions", () => { await beforeEachTest(); }); - const testError = (err: Error, operation: DispositionType): void => { - should.equal( - err.message, - `Failed to ${operation} the message as this message is already settled.`, - "ErrorMessage is different than expected" - ); + const testError = (err: Error): void => { + should.equal(err.message, MessageAlreadySettled, "ErrorMessage is different than expected"); errorWasThrown = true; }; @@ -581,15 +577,13 @@ describe("Streaming with sessions", () => { await testPeekMsgsLength(receiver, 0); if (operation === DispositionType.complete) { - await receiver.completeMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.completeMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.abandon) { - await receiver.abandonMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.abandonMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.deadletter) { - await receiver - .deadLetterMessage(receivedMsgs[0]) - .catch((err) => testError(err, operation)); + await receiver.deadLetterMessage(receivedMsgs[0]).catch((err) => testError(err)); } else if (operation === DispositionType.defer) { - await receiver.deferMessage(receivedMsgs[0]).catch((err) => testError(err, operation)); + await receiver.deferMessage(receivedMsgs[0]).catch((err) => testError(err)); } should.equal(errorWasThrown, true, "Error thrown flag must be true"); From 87b095dae558ed7fdb9128bea9ff574919709ffb Mon Sep 17 00:00:00 2001 From: chradek <51000525+chradek@users.noreply.github.com> Date: Tue, 10 Nov 2020 12:46:44 -0800 Subject: [PATCH 28/35] [core-amqp] prepare for 2.0.0 release (#12449) --- sdk/core/core-amqp/CHANGELOG.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sdk/core/core-amqp/CHANGELOG.md b/sdk/core/core-amqp/CHANGELOG.md index 13e0d5144753..7924398e2f7d 100644 --- a/sdk/core/core-amqp/CHANGELOG.md +++ b/sdk/core/core-amqp/CHANGELOG.md @@ -1,10 +1,12 @@ # Release History -## 2.0.0 (Unreleased) +## 2.0.0 (2020-11-10) + +- This release marks the general availability of the `@azure/core-amqp` version 2 package. ### Breaking changes -- Continuing our work to clean the public API surface that we started in 2.0.0-beta.1, `DataTransformer` and `DefaultDataTransformer` are no longer exported. +- Continuing our work to clean the public API surface that we started in 2.0.0-beta.1, `DataTransformer` and `DefaultDataTransformer` are no longer exported. `dataTransformer` has been removed from `ConnectionContextBase` and `ConnectionContextBaseParameters`. This allows us to consider other forms of implementing serializers in the future. - Previously, `ConnectionConfig.validate()` overridden entityPath if `undefined` with `String(undefined) = "undefined"`. This has been updated to retain `undefined` in the validation. From 0cd78d79e1c04703c81e4171a8a81fc627cceb79 Mon Sep 17 00:00:00 2001 From: Sarangan Rajamanickam Date: Tue, 10 Nov 2020 20:58:02 +0000 Subject: [PATCH 29/35] Release 5.2.0 version of customvision training (#12427) --- .../package.json | 2 +- .../rollup.config.js | 4 +- .../src/models/index.ts | 191 ++++++++++++++---- .../src/models/mappers.ts | 136 ++++++++++++- .../src/models/parameters.ts | 5 +- .../src/trainingAPIClient.ts | 30 +-- .../src/trainingAPIClientContext.ts | 9 +- 7 files changed, 315 insertions(+), 62 deletions(-) diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/package.json b/sdk/cognitiveservices/cognitiveservices-customvision-training/package.json index e981fe1e64c0..66c6ad641c5c 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/package.json +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/package.json @@ -2,7 +2,7 @@ "name": "@azure/cognitiveservices-customvision-training", "author": "Microsoft Corporation", "description": "TrainingAPIClient Library with typescript type definitions for node.js and browser.", - "version": "5.1.2", + "version": "5.2.0", "dependencies": { "@azure/ms-rest-js": "^2.0.4", "tslib": "^1.10.0" diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/rollup.config.js b/sdk/cognitiveservices/cognitiveservices-customvision-training/rollup.config.js index 479c41e4b7ef..fc6f565c06aa 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/rollup.config.js +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/rollup.config.js @@ -21,8 +21,8 @@ const config = { "@azure/ms-rest-azure-js": "msRestAzure" }, banner: `/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/index.ts b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/index.ts index 4fc048edaad4..e633b72c0d0e 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/index.ts +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/index.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -31,6 +31,36 @@ export interface BoundingBox { height: number; } +/** + * Options used for createProject. + */ +export interface CreateProjectOptions { + /** + * The uri to the Azure Storage container that will be used to store exported models. + */ + exportModelContainerUri?: string; + /** + * The uri to the Azure Storage queue that will be used to send project-related notifications. + * See Storage notifications + * documentation for setup and message format. + */ + notificationQueueUri?: string; +} + +/** + * An interface representing CustomBaseModelInfo. + */ +export interface CustomBaseModelInfo { + /** + * Project Id of the previously trained project to be used for current iteration's training. + */ + projectId: string; + /** + * Iteration Id of the previously trained project to be used for current iteration's training. + */ + iterationId: string; +} + /** * An interface representing CustomVisionError. */ @@ -57,23 +87,27 @@ export interface CustomVisionError { * 'BadRequestExceededQuota', 'BadRequestCannotMigrateProjectWithName', * 'BadRequestNotLimitedTrial', 'BadRequestImageBatch', 'BadRequestImageStream', * 'BadRequestImageUrl', 'BadRequestImageFormat', 'BadRequestImageSizeBytes', - * 'BadRequestImageDimensions', 'BadRequestImageExceededCount', 'BadRequestTrainingNotNeeded', - * 'BadRequestTrainingNotNeededButTrainingPipelineUpdated', 'BadRequestTrainingValidationFailed', - * 'BadRequestClassificationTrainingValidationFailed', + * 'BadRequestImageDimensions', 'BadRequestImageAspectRatio', 'BadRequestImageExceededCount', + * 'BadRequestTrainingNotNeeded', 'BadRequestTrainingNotNeededButTrainingPipelineUpdated', + * 'BadRequestTrainingValidationFailed', 'BadRequestClassificationTrainingValidationFailed', * 'BadRequestMultiClassClassificationTrainingValidationFailed', * 'BadRequestMultiLabelClassificationTrainingValidationFailed', * 'BadRequestDetectionTrainingValidationFailed', 'BadRequestTrainingAlreadyInProgress', * 'BadRequestDetectionTrainingNotAllowNegativeTag', 'BadRequestInvalidEmailAddress', + * 'BadRequestRetiredDomainNotSupportedForTraining', * 'BadRequestDomainNotSupportedForAdvancedTraining', * 'BadRequestExportPlatformNotSupportedForAdvancedTraining', * 'BadRequestReservedBudgetInHoursNotEnoughForAdvancedTraining', - * 'BadRequestExportValidationFailed', 'BadRequestExportAlreadyInProgress', - * 'BadRequestPredictionIdsMissing', 'BadRequestPredictionIdsExceededCount', - * 'BadRequestPredictionTagsExceededCount', 'BadRequestPredictionResultsExceededCount', - * 'BadRequestPredictionInvalidApplicationName', 'BadRequestPredictionInvalidQueryParameters', - * 'BadRequestInvalidImportToken', 'BadRequestExportWhileTraining', 'BadRequestImageMetadataKey', - * 'BadRequestImageMetadataValue', 'BadRequestOperationNotSupported', - * 'BadRequestInvalidArtifactUri', 'BadRequestCustomerManagedKeyRevoked', 'BadRequestInvalid', + * 'BadRequestCustomBaseModelIterationStatusNotCompleted', + * 'BadRequestCustomBaseModelDomainNotCompatible', + * 'BadRequestCustomBaseModelArchitectureRetired', 'BadRequestExportValidationFailed', + * 'BadRequestExportAlreadyInProgress', 'BadRequestPredictionIdsMissing', + * 'BadRequestPredictionIdsExceededCount', 'BadRequestPredictionTagsExceededCount', + * 'BadRequestPredictionResultsExceededCount', 'BadRequestPredictionInvalidApplicationName', + * 'BadRequestPredictionInvalidQueryParameters', 'BadRequestInvalidImportToken', + * 'BadRequestExportWhileTraining', 'BadRequestImageMetadataKey', 'BadRequestImageMetadataValue', + * 'BadRequestOperationNotSupported', 'BadRequestInvalidArtifactUri', + * 'BadRequestCustomerManagedKeyRevoked', 'BadRequestInvalidUri', 'BadRequestInvalid', * 'UnsupportedMediaType', 'Forbidden', 'ForbiddenUser', 'ForbiddenUserResource', * 'ForbiddenUserSignupDisabled', 'ForbiddenUserSignupAllowanceExceeded', * 'ForbiddenUserDoesNotExist', 'ForbiddenUserDisabled', 'ForbiddenUserInsufficientCapability', @@ -91,7 +125,7 @@ export interface CustomVisionError { * 'ErrorExporterInvalidFeaturizer', 'ErrorExporterInvalidClassifier', * 'ErrorPredictionServiceUnavailable', 'ErrorPredictionModelNotFound', * 'ErrorPredictionModelNotCached', 'ErrorPrediction', 'ErrorPredictionStorage', - * 'ErrorRegionProposal', 'ErrorUnknownBaseModel', 'ErrorInvalid' + * 'ErrorRegionProposal', 'ErrorUnknownBaseModel', 'ErrorServerTimeOut', 'ErrorInvalid' */ code: CustomVisionErrorCodes; /** @@ -101,30 +135,62 @@ export interface CustomVisionError { } /** - * An interface representing Domain. + * Model information. + */ +export interface ModelInformation { + /** + * Estimation of the exported FP32 Onnx model size (2 tags) in megabytes. This information is not + * present if the model cannot be exported. + */ + estimatedModelSizeInMegabytes?: number; + /** + * Model description. + */ + description: string; +} + +/** + * Domains are used as the starting point for your project. Each domain is optimized for specific + * types of images. Domains with compact in their name can be exported. For more information visit + * the domain documentation. */ export interface Domain { /** + * Domain id. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** + * Name of the domain, describing the types of images used to train it. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** - * Possible values include: 'Classification', 'ObjectDetection' + * Domain type: Classification or ObjectDetection. Possible values include: 'Classification', + * 'ObjectDetection' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: DomainType; /** + * Indicating if the domain is exportable. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly exportable?: boolean; /** + * Indicating if the domain is enabled. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly enabled?: boolean; + /** + * Platforms that the domain can be exported to. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly exportablePlatforms?: string[]; + /** + * Model information. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly modelInformation?: ModelInformation; } /** @@ -133,7 +199,7 @@ export interface Domain { export interface ExportModel { /** * Platform of the export. Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX', - * 'VAIDK' + * 'VAIDK', 'OpenVino' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly platform?: ExportPlatform; @@ -295,7 +361,7 @@ export interface ImageCreateResult { * Status of the image creation. Possible values include: 'OK', 'OKDuplicate', 'ErrorSource', * 'ErrorImageFormat', 'ErrorImageSize', 'ErrorStorage', 'ErrorLimitExceed', * 'ErrorTagLimitExceed', 'ErrorRegionLimitExceed', 'ErrorUnknown', - * 'ErrorNegativeAndRegularTagOnSameImage' + * 'ErrorNegativeAndRegularTagOnSameImage', 'ErrorImageDimensions', 'ErrorInvalidTag' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: ImageCreateStatus; @@ -365,8 +431,8 @@ export interface ImageFileCreateBatch { images?: ImageFileCreateEntry[]; tagIds?: string[]; /** - * The metadata of image. Limited to 50 key-value pairs per image. The length of key is limited - * to 256. The length of value is limited to 512. + * The metadata of image. Limited to 10 key-value pairs per image. The length of key is limited + * to 128. The length of value is limited to 256. */ metadata?: { [propertyName: string]: string }; } @@ -390,8 +456,8 @@ export interface ImageIdCreateBatch { images?: ImageIdCreateEntry[]; tagIds?: string[]; /** - * The metadata of image. Limited to 50 key-value pairs per image. The length of key is limited - * to 256. The length of value is limited to 512. + * The metadata of image. Limited to 10 key-value pairs per image. The length of key is limited + * to 128. The length of value is limited to 256. */ metadata?: { [propertyName: string]: string }; } @@ -469,34 +535,45 @@ export interface ImagePerformance { */ readonly predictions?: Prediction[]; /** + * Id of the image. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** + * Date the image was created. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly created?: Date; /** + * Width of the image. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly width?: number; /** + * Height of the image. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly height?: number; /** + * The URI to the image used for training. If VNET feature is enabled this will be a relative + * path to be used with GetArtifact, otherwise this will be an absolute URI to the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly imageUri?: string; /** + * The URI to the thumbnail of the original image. If VNET feature is enabled this will be a + * relative path to be used with GetArtifact, otherwise this will be an absolute URI to the + * resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbnailUri?: string; /** + * Tags associated with this image. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tags?: ImageTag[]; /** + * Regions associated with this image. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly regions?: ImageRegion[]; @@ -728,8 +805,8 @@ export interface ImageUrlCreateBatch { images?: ImageUrlCreateEntry[]; tagIds?: string[]; /** - * The metadata of image. Limited to 50 key-value pairs per image. The length of key is limited - * to 256. The length of value is limited to 512. + * The metadata of image. Limited to 10 key-value pairs per image. The length of key is limited + * to 128. The length of value is limited to 256. */ metadata?: { [propertyName: string]: string }; } @@ -818,6 +895,20 @@ export interface Iteration { * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly originalPublishResourceId?: string; + /** + * Information of the previously trained iteration which provides the base model for current + * iteration's training. + * Default value of null specifies that no previously trained iteration will be used for + * incremental learning. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly customBaseModelInfo?: CustomBaseModelInfo; + /** + * Training error details, when training fails. + * Value is null when training succeeds. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly trainingErrorDetails?: string; } /** @@ -1023,6 +1114,18 @@ export interface ProjectSettings { * Gets or sets image preprocessing settings. */ imageProcessingSettings?: ImageProcessingSettings; + /** + * The uri to the Azure Storage container that will be used to store exported models. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly exportModelContainerUri?: string; + /** + * The uri to the Azure Storage queue that will be used to send project-related notifications. + * See Storage notifications + * documentation for setup and message format. + * **NOTE: This property will not be serialized. It can only be populated by the server.** + */ + readonly notificationQueueUri?: string; } /** @@ -1322,6 +1425,11 @@ export interface TrainingParameters { * List of tags selected for this training session, other tags in the project will be ignored. */ selectedTags?: string[]; + /** + * Information of the previously trained iteration which provides the base model for current + * iteration's training. + */ + customBaseModelInfo?: CustomBaseModelInfo; } /** @@ -1345,6 +1453,10 @@ export interface TrainingAPIClientCreateProjectOptionalParams extends msRest.Req * List of platforms the trained model is intending exporting to. */ targetExportPlatforms?: string[]; + /** + * Additional project creation options. + */ + options?: CreateProjectOptions; } /** @@ -1725,25 +1837,29 @@ export interface TrainingAPIClientImportProjectOptionalParams extends msRest.Req * 'BadRequestExceedTagPerImageLimit', 'BadRequestExceededQuota', * 'BadRequestCannotMigrateProjectWithName', 'BadRequestNotLimitedTrial', 'BadRequestImageBatch', * 'BadRequestImageStream', 'BadRequestImageUrl', 'BadRequestImageFormat', - * 'BadRequestImageSizeBytes', 'BadRequestImageDimensions', 'BadRequestImageExceededCount', - * 'BadRequestTrainingNotNeeded', 'BadRequestTrainingNotNeededButTrainingPipelineUpdated', - * 'BadRequestTrainingValidationFailed', 'BadRequestClassificationTrainingValidationFailed', + * 'BadRequestImageSizeBytes', 'BadRequestImageDimensions', 'BadRequestImageAspectRatio', + * 'BadRequestImageExceededCount', 'BadRequestTrainingNotNeeded', + * 'BadRequestTrainingNotNeededButTrainingPipelineUpdated', 'BadRequestTrainingValidationFailed', + * 'BadRequestClassificationTrainingValidationFailed', * 'BadRequestMultiClassClassificationTrainingValidationFailed', * 'BadRequestMultiLabelClassificationTrainingValidationFailed', * 'BadRequestDetectionTrainingValidationFailed', 'BadRequestTrainingAlreadyInProgress', * 'BadRequestDetectionTrainingNotAllowNegativeTag', 'BadRequestInvalidEmailAddress', + * 'BadRequestRetiredDomainNotSupportedForTraining', * 'BadRequestDomainNotSupportedForAdvancedTraining', * 'BadRequestExportPlatformNotSupportedForAdvancedTraining', * 'BadRequestReservedBudgetInHoursNotEnoughForAdvancedTraining', + * 'BadRequestCustomBaseModelIterationStatusNotCompleted', + * 'BadRequestCustomBaseModelDomainNotCompatible', 'BadRequestCustomBaseModelArchitectureRetired', * 'BadRequestExportValidationFailed', 'BadRequestExportAlreadyInProgress', * 'BadRequestPredictionIdsMissing', 'BadRequestPredictionIdsExceededCount', * 'BadRequestPredictionTagsExceededCount', 'BadRequestPredictionResultsExceededCount', * 'BadRequestPredictionInvalidApplicationName', 'BadRequestPredictionInvalidQueryParameters', * 'BadRequestInvalidImportToken', 'BadRequestExportWhileTraining', 'BadRequestImageMetadataKey', * 'BadRequestImageMetadataValue', 'BadRequestOperationNotSupported', - * 'BadRequestInvalidArtifactUri', 'BadRequestCustomerManagedKeyRevoked', 'BadRequestInvalid', - * 'UnsupportedMediaType', 'Forbidden', 'ForbiddenUser', 'ForbiddenUserResource', - * 'ForbiddenUserSignupDisabled', 'ForbiddenUserSignupAllowanceExceeded', + * 'BadRequestInvalidArtifactUri', 'BadRequestCustomerManagedKeyRevoked', 'BadRequestInvalidUri', + * 'BadRequestInvalid', 'UnsupportedMediaType', 'Forbidden', 'ForbiddenUser', + * 'ForbiddenUserResource', 'ForbiddenUserSignupDisabled', 'ForbiddenUserSignupAllowanceExceeded', * 'ForbiddenUserDoesNotExist', 'ForbiddenUserDisabled', 'ForbiddenUserInsufficientCapability', * 'ForbiddenDRModeEnabled', 'ForbiddenInvalid', 'NotFound', 'NotFoundProject', * 'NotFoundProjectDefaultIteration', 'NotFoundIteration', 'NotFoundIterationPerformance', @@ -1759,11 +1875,11 @@ export interface TrainingAPIClientImportProjectOptionalParams extends msRest.Req * 'ErrorExporterInvalidFeaturizer', 'ErrorExporterInvalidClassifier', * 'ErrorPredictionServiceUnavailable', 'ErrorPredictionModelNotFound', * 'ErrorPredictionModelNotCached', 'ErrorPrediction', 'ErrorPredictionStorage', - * 'ErrorRegionProposal', 'ErrorUnknownBaseModel', 'ErrorInvalid' + * 'ErrorRegionProposal', 'ErrorUnknownBaseModel', 'ErrorServerTimeOut', 'ErrorInvalid' * @readonly * @enum {string} */ -export type CustomVisionErrorCodes = 'NoError' | 'BadRequest' | 'BadRequestExceededBatchSize' | 'BadRequestNotSupported' | 'BadRequestInvalidIds' | 'BadRequestProjectName' | 'BadRequestProjectNameNotUnique' | 'BadRequestProjectDescription' | 'BadRequestProjectUnknownDomain' | 'BadRequestProjectUnknownClassification' | 'BadRequestProjectUnsupportedDomainTypeChange' | 'BadRequestProjectUnsupportedExportPlatform' | 'BadRequestProjectImagePreprocessingSettings' | 'BadRequestProjectDuplicated' | 'BadRequestIterationName' | 'BadRequestIterationNameNotUnique' | 'BadRequestIterationDescription' | 'BadRequestIterationIsNotTrained' | 'BadRequestIterationValidationFailed' | 'BadRequestWorkspaceCannotBeModified' | 'BadRequestWorkspaceNotDeletable' | 'BadRequestTagName' | 'BadRequestTagNameNotUnique' | 'BadRequestTagDescription' | 'BadRequestTagType' | 'BadRequestMultipleNegativeTag' | 'BadRequestMultipleGeneralProductTag' | 'BadRequestImageTags' | 'BadRequestImageRegions' | 'BadRequestNegativeAndRegularTagOnSameImage' | 'BadRequestUnsupportedDomain' | 'BadRequestRequiredParamIsNull' | 'BadRequestIterationIsPublished' | 'BadRequestInvalidPublishName' | 'BadRequestInvalidPublishTarget' | 'BadRequestUnpublishFailed' | 'BadRequestIterationNotPublished' | 'BadRequestSubscriptionApi' | 'BadRequestExceedProjectLimit' | 'BadRequestExceedIterationPerProjectLimit' | 'BadRequestExceedTagPerProjectLimit' | 'BadRequestExceedTagPerImageLimit' | 'BadRequestExceededQuota' | 'BadRequestCannotMigrateProjectWithName' | 'BadRequestNotLimitedTrial' | 'BadRequestImageBatch' | 'BadRequestImageStream' | 'BadRequestImageUrl' | 'BadRequestImageFormat' | 'BadRequestImageSizeBytes' | 'BadRequestImageDimensions' | 'BadRequestImageExceededCount' | 'BadRequestTrainingNotNeeded' | 'BadRequestTrainingNotNeededButTrainingPipelineUpdated' | 'BadRequestTrainingValidationFailed' | 'BadRequestClassificationTrainingValidationFailed' | 'BadRequestMultiClassClassificationTrainingValidationFailed' | 'BadRequestMultiLabelClassificationTrainingValidationFailed' | 'BadRequestDetectionTrainingValidationFailed' | 'BadRequestTrainingAlreadyInProgress' | 'BadRequestDetectionTrainingNotAllowNegativeTag' | 'BadRequestInvalidEmailAddress' | 'BadRequestDomainNotSupportedForAdvancedTraining' | 'BadRequestExportPlatformNotSupportedForAdvancedTraining' | 'BadRequestReservedBudgetInHoursNotEnoughForAdvancedTraining' | 'BadRequestExportValidationFailed' | 'BadRequestExportAlreadyInProgress' | 'BadRequestPredictionIdsMissing' | 'BadRequestPredictionIdsExceededCount' | 'BadRequestPredictionTagsExceededCount' | 'BadRequestPredictionResultsExceededCount' | 'BadRequestPredictionInvalidApplicationName' | 'BadRequestPredictionInvalidQueryParameters' | 'BadRequestInvalidImportToken' | 'BadRequestExportWhileTraining' | 'BadRequestImageMetadataKey' | 'BadRequestImageMetadataValue' | 'BadRequestOperationNotSupported' | 'BadRequestInvalidArtifactUri' | 'BadRequestCustomerManagedKeyRevoked' | 'BadRequestInvalid' | 'UnsupportedMediaType' | 'Forbidden' | 'ForbiddenUser' | 'ForbiddenUserResource' | 'ForbiddenUserSignupDisabled' | 'ForbiddenUserSignupAllowanceExceeded' | 'ForbiddenUserDoesNotExist' | 'ForbiddenUserDisabled' | 'ForbiddenUserInsufficientCapability' | 'ForbiddenDRModeEnabled' | 'ForbiddenInvalid' | 'NotFound' | 'NotFoundProject' | 'NotFoundProjectDefaultIteration' | 'NotFoundIteration' | 'NotFoundIterationPerformance' | 'NotFoundTag' | 'NotFoundImage' | 'NotFoundDomain' | 'NotFoundApimSubscription' | 'NotFoundInvalid' | 'Conflict' | 'ConflictInvalid' | 'ErrorUnknown' | 'ErrorIterationCopyFailed' | 'ErrorPreparePerformanceMigrationFailed' | 'ErrorProjectInvalidWorkspace' | 'ErrorProjectInvalidPipelineConfiguration' | 'ErrorProjectInvalidDomain' | 'ErrorProjectTrainingRequestFailed' | 'ErrorProjectImportRequestFailed' | 'ErrorProjectExportRequestFailed' | 'ErrorFeaturizationServiceUnavailable' | 'ErrorFeaturizationQueueTimeout' | 'ErrorFeaturizationInvalidFeaturizer' | 'ErrorFeaturizationAugmentationUnavailable' | 'ErrorFeaturizationUnrecognizedJob' | 'ErrorFeaturizationAugmentationError' | 'ErrorExporterInvalidPlatform' | 'ErrorExporterInvalidFeaturizer' | 'ErrorExporterInvalidClassifier' | 'ErrorPredictionServiceUnavailable' | 'ErrorPredictionModelNotFound' | 'ErrorPredictionModelNotCached' | 'ErrorPrediction' | 'ErrorPredictionStorage' | 'ErrorRegionProposal' | 'ErrorUnknownBaseModel' | 'ErrorInvalid'; +export type CustomVisionErrorCodes = 'NoError' | 'BadRequest' | 'BadRequestExceededBatchSize' | 'BadRequestNotSupported' | 'BadRequestInvalidIds' | 'BadRequestProjectName' | 'BadRequestProjectNameNotUnique' | 'BadRequestProjectDescription' | 'BadRequestProjectUnknownDomain' | 'BadRequestProjectUnknownClassification' | 'BadRequestProjectUnsupportedDomainTypeChange' | 'BadRequestProjectUnsupportedExportPlatform' | 'BadRequestProjectImagePreprocessingSettings' | 'BadRequestProjectDuplicated' | 'BadRequestIterationName' | 'BadRequestIterationNameNotUnique' | 'BadRequestIterationDescription' | 'BadRequestIterationIsNotTrained' | 'BadRequestIterationValidationFailed' | 'BadRequestWorkspaceCannotBeModified' | 'BadRequestWorkspaceNotDeletable' | 'BadRequestTagName' | 'BadRequestTagNameNotUnique' | 'BadRequestTagDescription' | 'BadRequestTagType' | 'BadRequestMultipleNegativeTag' | 'BadRequestMultipleGeneralProductTag' | 'BadRequestImageTags' | 'BadRequestImageRegions' | 'BadRequestNegativeAndRegularTagOnSameImage' | 'BadRequestUnsupportedDomain' | 'BadRequestRequiredParamIsNull' | 'BadRequestIterationIsPublished' | 'BadRequestInvalidPublishName' | 'BadRequestInvalidPublishTarget' | 'BadRequestUnpublishFailed' | 'BadRequestIterationNotPublished' | 'BadRequestSubscriptionApi' | 'BadRequestExceedProjectLimit' | 'BadRequestExceedIterationPerProjectLimit' | 'BadRequestExceedTagPerProjectLimit' | 'BadRequestExceedTagPerImageLimit' | 'BadRequestExceededQuota' | 'BadRequestCannotMigrateProjectWithName' | 'BadRequestNotLimitedTrial' | 'BadRequestImageBatch' | 'BadRequestImageStream' | 'BadRequestImageUrl' | 'BadRequestImageFormat' | 'BadRequestImageSizeBytes' | 'BadRequestImageDimensions' | 'BadRequestImageAspectRatio' | 'BadRequestImageExceededCount' | 'BadRequestTrainingNotNeeded' | 'BadRequestTrainingNotNeededButTrainingPipelineUpdated' | 'BadRequestTrainingValidationFailed' | 'BadRequestClassificationTrainingValidationFailed' | 'BadRequestMultiClassClassificationTrainingValidationFailed' | 'BadRequestMultiLabelClassificationTrainingValidationFailed' | 'BadRequestDetectionTrainingValidationFailed' | 'BadRequestTrainingAlreadyInProgress' | 'BadRequestDetectionTrainingNotAllowNegativeTag' | 'BadRequestInvalidEmailAddress' | 'BadRequestRetiredDomainNotSupportedForTraining' | 'BadRequestDomainNotSupportedForAdvancedTraining' | 'BadRequestExportPlatformNotSupportedForAdvancedTraining' | 'BadRequestReservedBudgetInHoursNotEnoughForAdvancedTraining' | 'BadRequestCustomBaseModelIterationStatusNotCompleted' | 'BadRequestCustomBaseModelDomainNotCompatible' | 'BadRequestCustomBaseModelArchitectureRetired' | 'BadRequestExportValidationFailed' | 'BadRequestExportAlreadyInProgress' | 'BadRequestPredictionIdsMissing' | 'BadRequestPredictionIdsExceededCount' | 'BadRequestPredictionTagsExceededCount' | 'BadRequestPredictionResultsExceededCount' | 'BadRequestPredictionInvalidApplicationName' | 'BadRequestPredictionInvalidQueryParameters' | 'BadRequestInvalidImportToken' | 'BadRequestExportWhileTraining' | 'BadRequestImageMetadataKey' | 'BadRequestImageMetadataValue' | 'BadRequestOperationNotSupported' | 'BadRequestInvalidArtifactUri' | 'BadRequestCustomerManagedKeyRevoked' | 'BadRequestInvalidUri' | 'BadRequestInvalid' | 'UnsupportedMediaType' | 'Forbidden' | 'ForbiddenUser' | 'ForbiddenUserResource' | 'ForbiddenUserSignupDisabled' | 'ForbiddenUserSignupAllowanceExceeded' | 'ForbiddenUserDoesNotExist' | 'ForbiddenUserDisabled' | 'ForbiddenUserInsufficientCapability' | 'ForbiddenDRModeEnabled' | 'ForbiddenInvalid' | 'NotFound' | 'NotFoundProject' | 'NotFoundProjectDefaultIteration' | 'NotFoundIteration' | 'NotFoundIterationPerformance' | 'NotFoundTag' | 'NotFoundImage' | 'NotFoundDomain' | 'NotFoundApimSubscription' | 'NotFoundInvalid' | 'Conflict' | 'ConflictInvalid' | 'ErrorUnknown' | 'ErrorIterationCopyFailed' | 'ErrorPreparePerformanceMigrationFailed' | 'ErrorProjectInvalidWorkspace' | 'ErrorProjectInvalidPipelineConfiguration' | 'ErrorProjectInvalidDomain' | 'ErrorProjectTrainingRequestFailed' | 'ErrorProjectImportRequestFailed' | 'ErrorProjectExportRequestFailed' | 'ErrorFeaturizationServiceUnavailable' | 'ErrorFeaturizationQueueTimeout' | 'ErrorFeaturizationInvalidFeaturizer' | 'ErrorFeaturizationAugmentationUnavailable' | 'ErrorFeaturizationUnrecognizedJob' | 'ErrorFeaturizationAugmentationError' | 'ErrorExporterInvalidPlatform' | 'ErrorExporterInvalidFeaturizer' | 'ErrorExporterInvalidClassifier' | 'ErrorPredictionServiceUnavailable' | 'ErrorPredictionModelNotFound' | 'ErrorPredictionModelNotCached' | 'ErrorPrediction' | 'ErrorPredictionStorage' | 'ErrorRegionProposal' | 'ErrorUnknownBaseModel' | 'ErrorServerTimeOut' | 'ErrorInvalid'; /** * Defines values for DomainType. @@ -1775,11 +1891,11 @@ export type DomainType = 'Classification' | 'ObjectDetection'; /** * Defines values for ExportPlatform. - * Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX', 'VAIDK' + * Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX', 'VAIDK', 'OpenVino' * @readonly * @enum {string} */ -export type ExportPlatform = 'CoreML' | 'TensorFlow' | 'DockerFile' | 'ONNX' | 'VAIDK'; +export type ExportPlatform = 'CoreML' | 'TensorFlow' | 'DockerFile' | 'ONNX' | 'VAIDK' | 'OpenVino'; /** * Defines values for ExportStatus. @@ -1802,11 +1918,12 @@ export type ExportFlavor = 'Linux' | 'Windows' | 'ONNX10' | 'ONNX12' | 'ARM' | ' * Defines values for ImageCreateStatus. * Possible values include: 'OK', 'OKDuplicate', 'ErrorSource', 'ErrorImageFormat', * 'ErrorImageSize', 'ErrorStorage', 'ErrorLimitExceed', 'ErrorTagLimitExceed', - * 'ErrorRegionLimitExceed', 'ErrorUnknown', 'ErrorNegativeAndRegularTagOnSameImage' + * 'ErrorRegionLimitExceed', 'ErrorUnknown', 'ErrorNegativeAndRegularTagOnSameImage', + * 'ErrorImageDimensions', 'ErrorInvalidTag' * @readonly * @enum {string} */ -export type ImageCreateStatus = 'OK' | 'OKDuplicate' | 'ErrorSource' | 'ErrorImageFormat' | 'ErrorImageSize' | 'ErrorStorage' | 'ErrorLimitExceed' | 'ErrorTagLimitExceed' | 'ErrorRegionLimitExceed' | 'ErrorUnknown' | 'ErrorNegativeAndRegularTagOnSameImage'; +export type ImageCreateStatus = 'OK' | 'OKDuplicate' | 'ErrorSource' | 'ErrorImageFormat' | 'ErrorImageSize' | 'ErrorStorage' | 'ErrorLimitExceed' | 'ErrorTagLimitExceed' | 'ErrorRegionLimitExceed' | 'ErrorUnknown' | 'ErrorNegativeAndRegularTagOnSameImage' | 'ErrorImageDimensions' | 'ErrorInvalidTag'; /** * Defines values for ImageMetadataUpdateStatus. @@ -1947,11 +2064,11 @@ export type TrainingType1 = 'Regular' | 'Advanced'; /** * Defines values for Platform. - * Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX', 'VAIDK' + * Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX', 'VAIDK', 'OpenVino' * @readonly * @enum {string} */ -export type Platform = 'CoreML' | 'TensorFlow' | 'DockerFile' | 'ONNX' | 'VAIDK'; +export type Platform = 'CoreML' | 'TensorFlow' | 'DockerFile' | 'ONNX' | 'VAIDK' | 'OpenVino'; /** * Contains response data for the getDomains operation. diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/mappers.ts b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/mappers.ts index de3a69f46cf7..37d24b69f010 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/mappers.ts +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/mappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -51,6 +51,56 @@ export const BoundingBox: msRest.CompositeMapper = { } }; +export const CreateProjectOptions: msRest.CompositeMapper = { + serializedName: "CreateProjectOptions", + type: { + name: "Composite", + className: "CreateProjectOptions", + modelProperties: { + exportModelContainerUri: { + nullable: false, + serializedName: "exportModelContainerUri", + type: { + name: "String" + } + }, + notificationQueueUri: { + nullable: false, + serializedName: "notificationQueueUri", + type: { + name: "String" + } + } + } + } +}; + +export const CustomBaseModelInfo: msRest.CompositeMapper = { + serializedName: "CustomBaseModelInfo", + type: { + name: "Composite", + className: "CustomBaseModelInfo", + modelProperties: { + projectId: { + required: true, + nullable: false, + serializedName: "projectId", + type: { + name: "Uuid" + } + }, + iterationId: { + required: true, + nullable: false, + serializedName: "iterationId", + type: { + name: "Uuid" + } + } + } + } +}; + export const CustomVisionError: msRest.CompositeMapper = { serializedName: "CustomVisionError", type: { @@ -75,6 +125,30 @@ export const CustomVisionError: msRest.CompositeMapper = { } }; +export const ModelInformation: msRest.CompositeMapper = { + serializedName: "ModelInformation", + type: { + name: "Composite", + className: "ModelInformation", + modelProperties: { + estimatedModelSizeInMegabytes: { + serializedName: "estimatedModelSizeInMegabytes", + type: { + name: "Number" + } + }, + description: { + required: true, + nullable: false, + serializedName: "description", + type: { + name: "String" + } + } + } + } +}; + export const Domain: msRest.CompositeMapper = { serializedName: "Domain", type: { @@ -120,6 +194,26 @@ export const Domain: msRest.CompositeMapper = { type: { name: "Boolean" } + }, + exportablePlatforms: { + readOnly: true, + serializedName: "exportablePlatforms", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + }, + modelInformation: { + readOnly: true, + serializedName: "modelInformation", + type: { + name: "Composite", + className: "ModelInformation" + } } } } @@ -1582,6 +1676,21 @@ export const Iteration: msRest.CompositeMapper = { type: { name: "String" } + }, + customBaseModelInfo: { + readOnly: true, + serializedName: "customBaseModelInfo", + type: { + name: "Composite", + className: "CustomBaseModelInfo" + } + }, + trainingErrorDetails: { + readOnly: true, + serializedName: "trainingErrorDetails", + type: { + name: "String" + } } } } @@ -1992,6 +2101,22 @@ export const ProjectSettings: msRest.CompositeMapper = { name: "Composite", className: "ImageProcessingSettings" } + }, + exportModelContainerUri: { + nullable: true, + readOnly: true, + serializedName: "exportModelContainerUri", + type: { + name: "String" + } + }, + notificationQueueUri: { + nullable: true, + readOnly: true, + serializedName: "notificationQueueUri", + type: { + name: "String" + } } } } @@ -2486,6 +2611,13 @@ export const TrainingParameters: msRest.CompositeMapper = { } } } + }, + customBaseModelInfo: { + serializedName: "customBaseModelInfo", + type: { + name: "Composite", + className: "CustomBaseModelInfo" + } } } } diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/parameters.ts b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/parameters.ts index 61a9d3cffbe0..d9dbbcf9a120 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/parameters.ts +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/models/parameters.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClient.ts b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClient.ts index 8566f3c856b6..ea4d9583d4d1 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClient.ts +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClient.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -519,8 +518,8 @@ class TrainingAPIClient extends TrainingAPIClientContext { * @summary Update metadata of images. * @param projectId The project id. * @param imageIds The list of image ids to update. Limited to 64. - * @param metadata The metadata to be updated to the specified images. Limited to 50 key-value - * pairs per image. The length of key is limited to 256. The length of value is limited to 512. + * @param metadata The metadata to be updated to the specified images. Limited to 10 key-value + * pairs per image. The length of key is limited to 128. The length of value is limited to 256. * @param [options] The optional parameters * @returns Promise */ @@ -528,16 +527,16 @@ class TrainingAPIClient extends TrainingAPIClientContext { /** * @param projectId The project id. * @param imageIds The list of image ids to update. Limited to 64. - * @param metadata The metadata to be updated to the specified images. Limited to 50 key-value - * pairs per image. The length of key is limited to 256. The length of value is limited to 512. + * @param metadata The metadata to be updated to the specified images. Limited to 10 key-value + * pairs per image. The length of key is limited to 128. The length of value is limited to 256. * @param callback The callback */ updateImageMetadata(projectId: string, imageIds: string[], metadata: { [propertyName: string]: string }, callback: msRest.ServiceCallback): void; /** * @param projectId The project id. * @param imageIds The list of image ids to update. Limited to 64. - * @param metadata The metadata to be updated to the specified images. Limited to 50 key-value - * pairs per image. The length of key is limited to 256. The length of value is limited to 512. + * @param metadata The metadata to be updated to the specified images. Limited to 10 key-value + * pairs per image. The length of key is limited to 128. The length of value is limited to 256. * @param options The optional parameters * @param callback The callback */ @@ -1136,7 +1135,7 @@ class TrainingAPIClient extends TrainingAPIClientContext { * @param projectId The project id. * @param iterationId The iteration id. * @param platform The target platform. Possible values include: 'CoreML', 'TensorFlow', - * 'DockerFile', 'ONNX', 'VAIDK' + * 'DockerFile', 'ONNX', 'VAIDK', 'OpenVino' * @param [options] The optional parameters * @returns Promise */ @@ -1145,7 +1144,7 @@ class TrainingAPIClient extends TrainingAPIClientContext { * @param projectId The project id. * @param iterationId The iteration id. * @param platform The target platform. Possible values include: 'CoreML', 'TensorFlow', - * 'DockerFile', 'ONNX', 'VAIDK' + * 'DockerFile', 'ONNX', 'VAIDK', 'OpenVino' * @param callback The callback */ exportIteration(projectId: string, iterationId: string, platform: Models.Platform, callback: msRest.ServiceCallback): void; @@ -1153,7 +1152,7 @@ class TrainingAPIClient extends TrainingAPIClientContext { * @param projectId The project id. * @param iterationId The iteration id. * @param platform The target platform. Possible values include: 'CoreML', 'TensorFlow', - * 'DockerFile', 'ONNX', 'VAIDK' + * 'DockerFile', 'ONNX', 'VAIDK', 'OpenVino' * @param options The optional parameters * @param callback The callback */ @@ -1829,6 +1828,13 @@ const createProjectOperationSpec: msRest.OperationSpec = { Parameters.classificationType, Parameters.targetExportPlatforms ], + requestBody: { + parameterPath: [ + "options", + "options" + ], + mapper: Mappers.CreateProjectOptions + }, responses: { 200: { bodyMapper: Mappers.Project diff --git a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClientContext.ts b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClientContext.ts index f9a97a277880..5d60a8609bc1 100644 --- a/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClientContext.ts +++ b/sdk/cognitiveservices/cognitiveservices-customvision-training/src/trainingAPIClientContext.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -11,7 +10,7 @@ import * as msRest from "@azure/ms-rest-js"; const packageName = "@azure/cognitiveservices-customvision-training"; -const packageVersion = "5.1.2"; +const packageVersion = "5.2.0"; export class TrainingAPIClientContext extends msRest.ServiceClient { endpoint: string; @@ -42,7 +41,7 @@ export class TrainingAPIClientContext extends msRest.ServiceClient { super(credentials, options); - this.baseUri = "{Endpoint}/customvision/v3.3/training"; + this.baseUri = "{Endpoint}/customvision/v3.4-preview/training"; this.requestContentType = "application/json; charset=utf-8"; this.endpoint = endpoint; this.credentials = credentials; From a79e081ede8b951b0f2dd592a5726f9717b60d59 Mon Sep 17 00:00:00 2001 From: Harsha Nalluru Date: Tue, 10 Nov 2020 15:04:34 -0800 Subject: [PATCH 30/35] [Service Bus] Fix log message at `actionAfterWaitTimeout` (#12322) --- sdk/servicebus/service-bus/CHANGELOG.md | 2 +- .../service-bus/src/core/batchingReceiver.ts | 24 ++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/sdk/servicebus/service-bus/CHANGELOG.md b/sdk/servicebus/service-bus/CHANGELOG.md index 37561f37483c..5eb812d6d74c 100644 --- a/sdk/servicebus/service-bus/CHANGELOG.md +++ b/sdk/servicebus/service-bus/CHANGELOG.md @@ -6,7 +6,7 @@ ### New features: -- A helper method `parseServiceBusConnectionString` has been added which validates and parses a given connection string for Azure Service Bus. You can use this to extract the namespace and entitypath details from the connection string. +- A helper method `parseServiceBusConnectionString` has been added which validates and parses a given connection string for Azure Service Bus. You can use this to extract the namespace and entityPath details from the connection string. [PR 11949](https://github.com/Azure/azure-sdk-for-js/pull/11949) - All methods that take an array as input are updated to ensure they gracefully do a no-op rather than throw errors. For example: `receiveDeferredMessages()`, `scheduleMessages()` and `cancelScheduledMessages()`. - Tracing, using [@azure/core-tracing](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/core/core-tracing/README.md), has been added for sending and receiving of messages. diff --git a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts index 5d6f4d73a738..ff100d12dfbc 100644 --- a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts @@ -410,8 +410,13 @@ export class BatchingReceiverLite { // a chance to have fewer messages internally that could get lost if the user's // app crashes in receiveAndDelete mode. if (totalWaitTimer) clearTimeout(totalWaitTimer); - - totalWaitTimer = setTimeout(actionAfterWaitTimeout, getRemainingWaitTimeInMs()); + const remainingWaitTimeInMs = getRemainingWaitTimeInMs(); + totalWaitTimer = setTimeout(() => { + logger.verbose( + `${loggingPrefix} Batching, waited for ${remainingWaitTimeInMs} milliseconds after receiving the first message.` + ); + finalAction(); + }, remainingWaitTimeInMs); } } @@ -486,14 +491,6 @@ export class BatchingReceiverLite { reject(err); }, args.abortSignal); - // Action to be performed after the max wait time is over. - const actionAfterWaitTimeout = (): void => { - logger.verbose( - `${loggingPrefix} Batching, max wait time in milliseconds ${args.maxWaitTimeInMs} over.` - ); - return finalAction(); - }; - logger.verbose( `${loggingPrefix} Adding credit for receiving ${args.maxMessageCount} messages.` ); @@ -508,7 +505,12 @@ export class BatchingReceiverLite { `${loggingPrefix} Setting the wait timer for ${args.maxWaitTimeInMs} milliseconds.` ); - totalWaitTimer = setTimeout(actionAfterWaitTimeout, args.maxWaitTimeInMs); + totalWaitTimer = setTimeout(() => { + logger.verbose( + `${loggingPrefix} Batching, waited for max wait time ${args.maxWaitTimeInMs} milliseconds.` + ); + finalAction(); + }, args.maxWaitTimeInMs); receiver.on(ReceiverEvents.message, onReceiveMessage); receiver.on(ReceiverEvents.receiverError, onError); From 3d76cc1d9550c8697a4aa43a6c89222e11462724 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Rodr=C3=ADguez?= Date: Tue, 10 Nov 2020 18:20:51 -0500 Subject: [PATCH 31/35] [Identity] Client side authentication Markdown sample (#12452) * [Identity] Client side authentication Markdown sample * blob example should be copy-pasteable * some fixes * Jonathans feedback --- .../samples/ClientSideUserAuthentication.md | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 sdk/identity/identity/samples/ClientSideUserAuthentication.md diff --git a/sdk/identity/identity/samples/ClientSideUserAuthentication.md b/sdk/identity/identity/samples/ClientSideUserAuthentication.md new file mode 100644 index 000000000000..d0449da895f9 --- /dev/null +++ b/sdk/identity/identity/samples/ClientSideUserAuthentication.md @@ -0,0 +1,62 @@ +# Client side user authentication + +Client side applications often need to authenticate users to interact with resources in Azure. Some examples of this might be a command line tool which fetches secrets a user has access to from a key vault to setup a local test environment, or a GUI based application which allows a user to browse storage blobs they have access to. This sample demonstrates authenticating users with the `@azure/identity` library. + +## Interactive user authentication + +Most often authenticating users requires some user interaction. Properly handling this user interaction for OAuth2 authorization code or device code authentication can be challenging. To simplify this for client side applications the `@azure/identity` library provides the `InteractiveBrowserCredential` and the `DeviceCodeCredential`. These credentials are designed to handle the user interactions needed to authenticate via these two client side authentication flows, so the application developer can simply create the credential and authenticate clients with it. + +## Authenticating users with the InteractiveBrowserCredential + +For clients which have a default browser available, the `InteractiveBrowserCredential` provides the most simple user authentication experience. In the sample below an application authenticates a `KeyClient` (from [@azure/keyvault-keys](https://www.npmjs.com/package/@azure/keyvault-keys)) using the `InteractiveBrowserCredential`. + +```ts +const { InteractiveBrowserCredential } = require("@azure/identity"); +const { KeyClient } = require("@azure/keyvault-keys"); + +async function main() { + const credential = new InteractiveBrowserCredential({ + // By default, tenantId will be "organizations". You might assign a specific tenant this way. + tenantId: process.env.AZURE_TENANT_ID, + // By default, clientId will be the same used by the Azure CLI. You might assign a specific client ID this way. + clientId: process.env.AZURE_CLIENT_ID + }); + + const keyVaultUrl = `https://key-vault-name.vault.azure.net`; + const client = new KeyClient(keyVaultUrl, credential); + + // Retrieving the properties of the existing keys in that specific Key Vault. + console.log(await client.listPropertiesOfKeys().next()); +} + +main().then(console.log).catch((e) => console.error(e)); +``` + +As code uses the `SecretClient` in the above sample, the `InteractiveBrowserCredential` will automatically authenticate the user by launching the default system browser prompting the user to login. Once the user successfully logs in, the user can then call into Azure services. + +## Authenticating users with the DeviceCodeCredential + +For terminal clients without an available web browser, or clients with limited UI capabilities the `DeviceCodeCredential` provides the ability to authenticate any client using a device code. The next sample shows authenticating a `BlobServiceClient` (from [@azure/storage-blob](https://www.npmjs.com/package/@azure/storage-blob)) using the `DeviceCodeCredential`. + +```ts +const { DeviceCodeCredential } = require("@azure/identity"); +const { BlobServiceClient } = require("@azure/storage-blob"); + +async function main() { + const credential = new DeviceCodeCredential( + // By default, tenantId will be "organizations". You might assign a specific tenant this way. + process.env.AZURE_TENANT_ID, + // By default, clientId will be the same used by the Azure CLI. You might assign a specific client ID this way. + process.env.AZURE_CLIENT_ID + ); + const client = new BlobServiceClient("https://myaccount.blob.core.windows.net/mycontainer/myblob", credential); + + const containerClient = blobServiceClient.getContainerClient(""); + const createContainerResponse = await containerClient.create(); + console.log(`Successfully created a container`, createContainerResponse.requestId); +} + +main().then(console.log).catch((e) => console.error(e)); +``` + +Similarly to the `InteractiveBrowserCredential` the `DeviceCodeCredential` will also initiate the user interaction automatically as needed. To instantiate the `DeviceCodeCredential` the application must provide a callback which is called to display the device code along with details on how to authenticate to the user. By default, a message with a URL and a code will be presented to the user through the device's console. Once the user loads the given URL and enters the code, the authentication will be complete, and the user will be able to call into Azure services. From 121ed8838d5010aaf236412366ba737455af2125 Mon Sep 17 00:00:00 2001 From: chradek <51000525+chradek@users.noreply.github.com> Date: Tue, 10 Nov 2020 15:23:15 -0800 Subject: [PATCH 32/35] [core-amqp] remove v1 samples and snippets from README (#12454) * [core-amqp] remove v1 samples and snippets from README * [core-amqp] add readme exception --- eng/.docsettings.yml | 1 + sdk/core/core-amqp/README.md | 153 ------------------ sdk/core/core-amqp/package.json | 2 +- sdk/core/core-amqp/samples/cbsAuthUsingAad.ts | 78 --------- sdk/core/core-amqp/samples/cbsAuthUsingSas.ts | 87 ---------- sdk/core/core-amqp/samples/receive.ts | 104 ------------ sdk/core/core-amqp/samples/send.ts | 96 ----------- sdk/core/core-amqp/samples/tsconfig.json | 13 -- 8 files changed, 2 insertions(+), 532 deletions(-) delete mode 100644 sdk/core/core-amqp/samples/cbsAuthUsingAad.ts delete mode 100644 sdk/core/core-amqp/samples/cbsAuthUsingSas.ts delete mode 100644 sdk/core/core-amqp/samples/receive.ts delete mode 100644 sdk/core/core-amqp/samples/send.ts delete mode 100644 sdk/core/core-amqp/samples/tsconfig.json diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index 1f7581423adb..3b333bb08446 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -99,6 +99,7 @@ known_content_issues: - ["sdk/cognitiveservices/cognitiveservices-visualsearch/README.md",  "#1583"] - ["sdk/cognitiveservices/cognitiveservices-websearch/README.md",  "#1583"] - ["sdk/core/abort-controller/README.md",  "#1583"] + - ["sdk/core/core-amqp/README.md",  "#1583"] - ["sdk/core/core-auth/README.md",  "#1583"] - ["sdk/core/core-tracing/README.md",  "#1583"] - ["sdk/core/logger/README.md",  "#1583"] diff --git a/sdk/core/core-amqp/README.md b/sdk/core/core-amqp/README.md index 34edba572ad8..56471cce61ff 100644 --- a/sdk/core/core-amqp/README.md +++ b/sdk/core/core-amqp/README.md @@ -14,164 +14,15 @@ Install this library using npm as follows: npm install @azure/core-amqp ``` -**Note**: [`rhea-promise`](https://github.com/amqp/rhea-promise) is a peer dependency. You need to explicitly install this library as a dependency -in your application. - ## Key concepts Some of the key features of Azure Core AMQP library are: - [Claims based Authorization](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-amqp-protocol-guide#claims-based-authorization) - Request-Response link for [sending request and receiving response over AMQP](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-amqp-protocol-guide#amqp-management) -- A Data Transformer class to encode given data to an AMQP message and decode a given AMQP message. Useful for sending and receiving messages that are not of type Buffer. - Error translation of AMQP error codes along with errors specific to Azure Service Bus and Azure Event Hubs. - RetryPolicy for retrying a given operation if a retryable error was encountered. -## Examples - -[Claims Based Authorization](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-amqp-protocol-guide#claims-based-authorization) -need to be done for every AMQP link that your application creates. The claims also has to be renewed periodically. -For more details on CBS, please see the [CBS Specification](https://www.oasis-open.org/committees/download.php/62097/amqp-cbs-v1.0-wd05.doc). - -In the below examples, we use the Shared Key details present in the connection string to create a SAS token. -This token is then used to make a request on the \$cbs link to carry out Claims Based Authorization for a link to the given entity -in Azure Service Bus or Azure Event Hubs. - -The examples below expect a connection string to a Azure Service Bus or Azure Event Hubs instance. -The entity path refers to an Event Hub name in case of Azure Event Hubs and a queue or a topic name -in case of Azure Service Bus. - -## Create a sender link - -In the below example, we first create a `ConnectionContext` which is used to carry out the claims -based authorization. Then, we create a sender link using the `ConnectionContext.connection` to -send a message. - -```js -async function main() { - const connectionConfig = ConnectionConfig.create( - "your-connection-string-with-shared-key", - "entity-path" - ); - const connectionContext = ConnectionContextBase.create({ - config: connectionConfig, - connectionProperties: { - product: "product", - userAgent: "/user-agent", - version: "0.0.0" - } - }); - - // Carry out the Claims Based Authorization - await connectionContext.cbsSession.init(); - const token = await connectionContext.tokenCredential.getToken(audience); - await connectionContext.cbsSession.negotiateClaim(audience, token, TokenType.CbsTokenTypeSas); - - // Create a sender - const senderName = "your-sender-name"; - const senderOptions = { - name: senderName, - target: { - // For an EventHub Sender bound to a partition, the address will be "/Partitions/" - address: `${connectionConfig.entityPath}` - }, - onError: (context) => { - const senderError = context.sender && context.sender.error; - if (senderError) { - console.log("An error occurred for sender '%s': %O.", senderName, senderError); - } - }, - onSessionError: (context) => { - const sessionError = context.session && context.session.error; - if (sessionError) { - console.log("An error occurred for session of sender '%s': %O.", senderName, sessionError); - } - } - }; - const sender = await connectionContext.connection.createSender(senderOptions); - - // Send a message - const delivery = await sender.send({ body: "your-message-body" }); - - await sender.close(); - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); -``` - -## Create a receiver link - -In the below example, we first create a `ConnectionContext` which is used to carry out the claims -based authorization. Then, we create a receiver link using the `ConnectionContext.connection` to -receive messages for 30 seconds. - -```js -async function main() { - const connectionConfig = ConnectionConfig.create( - "your-connection-string-with-shared-key", - "entity-path" - ); - const connectionContext = ConnectionContextBase.create({ - config: connectionConfig, - connectionProperties: { - product: "product", - userAgent: "/user-agent", - version: "0.0.0" - } - }); - - // Carry out the Claims Based Authorization - await connectionContext.cbsSession.init(); - const token = await connectionContext.tokenCredential.getToken(audience); - await connectionContext.cbsSession.negotiateClaim(audience, token, TokenType.CbsTokenTypeSas); - - // Create a receiver - const receiverName = "your-receiver-name"; - const filterClause = `amqp.annotation.x-opt-enqueued-time > '${Date.now() - 3600 * 1000}'`; // Get messages from the past hour - const receiverAddress = `${connectionConfig.entityPath}/ConsumerGroups/$default/Partitions/0`; // For ServiceBus "" - const receiverOptions = { - name: receiverName, - source: { - address: receiverAddress, - filter: { - // May not be required for ServiceBus. The current example is for EventHubs. - "apache.org:selector-filter:string": types.wrap_described(filterClause, 0x468c00000004) - } - }, - onError: (context) => { - const receiverError = context.receiver && context.receiver.error; - if (receiverError) { - console.log("An error occurred for receiver '%s': %O.", receiverName, receiverError); - } - }, - onMessage: (context) => { - console.log("Received message: %O", context.message); - }, - onSessionError: (context) => { - const sessionError = context.session && context.session.error; - if (sessionError) { - console.log( - "An error occurred for session of receiver '%s': %O.", - receiverName, - sessionError - ); - } - } - }; - const receiver = await connectionContext.connection.createReceiver(receiverOptions); - - // sleeping for 30 seconds to let the receiver receive messages - await new Promise((r) => setTimeout(r, 30000)); - - // Close the receiver to stop receiving messages - await receiver.close(); - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); -``` - ## Troubleshooting The core-amqp library depends on the [rhea-promise](https://github.com/amqp/rhea-promise) library for managing connections, and for sending and receiving events over the [AMQP](https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-complete-v1.0-os.pdf) protocol. @@ -243,10 +94,6 @@ export DEBUG=azure:core-amqp:(error|warning),rhea-promise:error,rhea:events,rhea node your-test-script.js &> out.log ``` -# Next steps - -Please take a look at the [samples](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/core/core-amqp/samples) directory for detailed samples. - # Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a diff --git a/sdk/core/core-amqp/package.json b/sdk/core/core-amqp/package.json index 1238ee543b11..cdd91f6d4596 100644 --- a/sdk/core/core-amqp/package.json +++ b/sdk/core/core-amqp/package.json @@ -35,7 +35,7 @@ ], "scripts": { "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", - "build:samples": "cd samples && tsc -p .", + "build:samples": "echo skipped", "build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1", "build:types": "downlevel-dts types/latest types/3.1", "build": "tsc -p . && rollup -c 2>&1 && api-extractor run --local && npm run build:types", diff --git a/sdk/core/core-amqp/samples/cbsAuthUsingAad.ts b/sdk/core/core-amqp/samples/cbsAuthUsingAad.ts deleted file mode 100644 index 6a96016f163a..000000000000 --- a/sdk/core/core-amqp/samples/cbsAuthUsingAad.ts +++ /dev/null @@ -1,78 +0,0 @@ -/*Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the MIT License. See License.txt in the project root for license information. - -This sample utilizes Event Hubs and demonstrates how to authenticate using AAD token credentials -obtained from using Service Principal Secrets. - -Setup : - Please ensure that your Azure Event Hubs resource is in US East, US East 2, or West Europe - region. AAD Role Based Access Control is not supported in other regions yet. - -Register a new application in AAD and assign the "owner" role to it - - See https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app - to register a new application in the Azure Active Directory. - - Note down the CLIENT_ID and TENANT_ID from the above step. - - In the "Certificates & Secrets" tab, create a secret and note that down. - - In the Azure portal, go to your Even Hubs resource and click on the Access control(IAM) - tab.Here, assign "owner" role to the registered application. -*/ - -import { - ConnectionContextBase, - CbsResponse, - EventHubConnectionConfig, - TokenType, - Constants -} from "@azure/core-amqp"; -import { DefaultAzureCredential } from "@azure/identity"; - -// Define connection string and related Event Hubs entity name here -const connectionString = ""; -const eventHubName = ""; - -// Define AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET of your AAD application in your environment - -const ehConnectionConfig = EventHubConnectionConfig.create(connectionString, eventHubName); -const parameters = { - config: ehConnectionConfig, - connectionProperties: { - product: "MSJSClient", - userAgent: "/js-core-amqp", - version: "0.1.0" - } -}; -const connectionContext = ConnectionContextBase.create(parameters); - -async function authenticate( - audience: string, - closeConnection: boolean = false -): Promise { - await connectionContext.cbsSession.init(); - const credential = new DefaultAzureCredential(); - const tokenObject = await credential.getToken(Constants.aadEventHubsScope); - if (!tokenObject) { - throw new Error("Aad token cannot be null"); - } - const result = await connectionContext.cbsSession.negotiateClaim( - audience, - tokenObject, - TokenType.CbsTokenTypeJwt - ); - console.log("Result is: %O", result); - if (closeConnection) { - await connectionContext.connection.close(); - console.log("Successfully closed the connection."); - } - return result; -} - -async function main(): Promise { - await authenticate(ehConnectionConfig.getSenderAudience()); - /* - Add code here to create a sender or receiver link for which you have - just sent the authentication request -*/ - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); diff --git a/sdk/core/core-amqp/samples/cbsAuthUsingSas.ts b/sdk/core/core-amqp/samples/cbsAuthUsingSas.ts deleted file mode 100644 index a38bfb29f0a3..000000000000 --- a/sdk/core/core-amqp/samples/cbsAuthUsingSas.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the MIT Licence. - - This sample utilizes Service Bus/Event Hubs and demonstrates how to authenticate using SharedKeyCredential. -*/ - -import { - ConnectionContextBase, - ConnectionConfig, - CbsResponse, - TokenType, - SharedKeyCredential -} from "@azure/core-amqp"; - -// Define connection string and related entity path here -const connectionString = ""; -const path = ""; - -const connectionConfig = ConnectionConfig.create(connectionString, path); -const parameters = { - config: connectionConfig, - connectionProperties: { - product: "MSJSClient", - userAgent: "/js-core-amqp", - version: "0.1.0" - } -}; -const connectionContext = ConnectionContextBase.create(parameters); - -/** - * audience The entity token audience in one of the following forms: - * - * - **ServiceBus** - * - **Sender** - * - `"sb://.servicebus.windows.net/"` - * - `"sb://.servicebus.windows.net/"` - * - * - **Receiver** - * - `"sb://.servicebus.windows.net/"` - * - `"sb://.servicebus.windows.net/"` - * - * - **ManagementClient** - * - `"sb://.servicebus.windows.net//$management"`. - * - `"sb://.servicebus.windows.net//$management"`. - * - * - **EventHubs** - * - **Sender** - * - `"sb://.servicebus.windows.net/"` - * - `"sb://.servicebus.windows.net//Partitions/"`. - * - * - **Receiver** - * - `"sb://.servicebus.windows.net//ConsumerGroups//Partitions/"`. - * - * - **ManagementClient** - * - `"sb://.servicebus.windows.net//$management"`. - */ -export async function authenticate( - audience: string, - closeConnection: boolean -): Promise { - await connectionContext.cbsSession.init(); - const sharedKeyCredential = connectionContext.tokenCredential; - const tokenObject = sharedKeyCredential.getToken(audience); - const result = await connectionContext.cbsSession.negotiateClaim( - audience, - tokenObject, - TokenType.CbsTokenTypeSas - ); - console.log("Result is: %O", result); - if (closeConnection) { - await connectionContext.connection.close(); - console.log("Successfully closed the connection."); - } - return result; -} - -async function main(): Promise { - await authenticate(`${connectionConfig.endpoint}${connectionConfig.entityPath}`, false); - /* - Add code here to create a sender or receiver link for which you have - just sent the authentication request -*/ - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); diff --git a/sdk/core/core-amqp/samples/receive.ts b/sdk/core/core-amqp/samples/receive.ts deleted file mode 100644 index b73174a1c7a6..000000000000 --- a/sdk/core/core-amqp/samples/receive.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the MIT Licence. - - This sample demonstrates how to receive messages/events from Service Bus/Event Hubs - by authenticating the receiver link using the shared key information in the connection string -*/ - -import { - Receiver, - ReceiverOptions, - ReceiverEvents, - delay, - types, - EventContext -} from "rhea-promise"; - -import { - ConnectionContextBase, - CbsResponse, - ConnectionConfig, - TokenType, - SharedKeyCredential -} from "@azure/core-amqp"; - -// Define connection string and related entity path here -const connectionString = ""; -const path = ""; - -const connectionConfig = ConnectionConfig.create(connectionString, path); -const parameters = { - config: connectionConfig, - connectionProperties: { - product: "MSJSClient", - userAgent: "/js-core-amqp", - version: "0.1.0" - } -}; -const connectionContext = ConnectionContextBase.create(parameters); - -async function authenticate(audience: string): Promise { - await connectionContext.cbsSession.init(); - // We use the shared key information in the connection string to perform the authentication. - // If you want to use Azure Active Directory, then refer `cbsAuthUsingAad.ts` sample. - const sharedKeyCredential = connectionContext.tokenCredential; - const tokenObject = sharedKeyCredential.getToken(audience); - const result = await connectionContext.cbsSession.negotiateClaim( - audience, - tokenObject, - TokenType.CbsTokenTypeSas - ); - console.log("Result is: %O", result); - return result; -} - -async function main(): Promise { - await authenticate(`${connectionConfig.endpoint}${connectionConfig.entityPath}`); - const receiverName = "receiver-1"; - const filterClause = `amqp.annotation.x-opt-enqueued-time > '${Date.now() - 3600 * 1000}'`; // Get messages from the past hour - const receiverAddress = `${connectionConfig.entityPath}/ConsumerGroups/$default/Partitions/0`; // For ServiceBus "" - const receiverOptions: ReceiverOptions = { - name: receiverName, - source: { - address: receiverAddress, - filter: { - // May not be required for ServiceBus. The current example is for EventHubs. - "apache.org:selector-filter:string": types.wrap_described(filterClause, 0x468c00000004) - } - }, - onSessionError: (context: EventContext) => { - const sessionError = context.session && context.session.error; - if (sessionError) { - console.log( - "[%s] An error occurred for session of receiver '%s': %O.", - connectionContext.connection.id, - receiverName, - sessionError - ); - } - } - }; - - const receiver: Receiver = await connectionContext.connection.createReceiver(receiverOptions); - receiver.on(ReceiverEvents.message, (context: EventContext) => { - console.log("Received message: %O", context.message); - }); - receiver.on(ReceiverEvents.receiverError, (context: EventContext) => { - const receiverError = context.receiver && context.receiver.error; - if (receiverError) { - console.log( - "[%s] An error occurred for receiver '%s': %O.", - connectionContext.connection.id, - receiverName, - receiverError - ); - } - }); - // Waiting long enough before closing the receiver to receive messages/events - await delay(120000); - await receiver.close(); - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); diff --git a/sdk/core/core-amqp/samples/send.ts b/sdk/core/core-amqp/samples/send.ts deleted file mode 100644 index 1901f3a7e202..000000000000 --- a/sdk/core/core-amqp/samples/send.ts +++ /dev/null @@ -1,96 +0,0 @@ -/* - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the MIT Licence. - - This sample demonstrates how to send messages/events to Service Bus/Event Hubs - by authenticating the sender link using the shared key information in the connection string -*/ - -import { - ConnectionContextBase, - CbsResponse, - ConnectionConfig, - TokenType, - SharedKeyCredential -} from "@azure/core-amqp"; - -import { Sender, SenderOptions, EventContext, Message, Delivery } from "rhea-promise"; - -// Define connection string and related entity path here -const connectionString = ""; -const path = ""; - -const connectionConfig = ConnectionConfig.create(connectionString, path); -const parameters = { - config: connectionConfig, - connectionProperties: { - product: "MSJSClient", - userAgent: "/js-core-amqp", - version: "0.1.0" - } -}; -const connectionContext = ConnectionContextBase.create(parameters); - -async function authenticate(audience: string): Promise { - await connectionContext.cbsSession.init(); - // We use the shared key information in the connection string to perform the authentication. - // If you want to use Azure Active Directory, then refer `cbsAuthUsingAad.ts` sample. - const sharedKeyCredential = connectionContext.tokenCredential; - const tokenObject = sharedKeyCredential.getToken(audience); - const result = await connectionContext.cbsSession.negotiateClaim( - audience, - tokenObject, - TokenType.CbsTokenTypeSas - ); - console.log("Result is: %O", result); - return result; -} - -async function main(): Promise { - await authenticate(`${connectionConfig.endpoint}${connectionConfig.entityPath}`); - const senderName = "sender-1"; - const senderOptions: SenderOptions = { - name: senderName, - target: { - // Address for EventHub Sender, it can be "" or "/Partitions/" - // For ServiceBus Queue, it will be "" - address: `${connectionConfig.entityPath}` - }, - onError: (context: EventContext) => { - const senderError = context.sender && context.sender.error; - if (senderError) { - console.log( - "[%s] An error occurred for sender '%s': %O.", - connectionContext.connection.id, - senderName, - senderError - ); - } - }, - onSessionError: (context: EventContext) => { - const sessionError = context.session && context.session.error; - if (sessionError) { - console.log( - "[%s] An error occurred for session of sender '%s': %O.", - connectionContext.connection.id, - senderName, - sessionError - ); - } - } - }; - - const sender: Sender = await connectionContext.connection.createSender(senderOptions); - const message: Message = { - body: "Hello World!!", - message_id: "12343434343434" - }; - - const delivery: Delivery = await sender.send(message); - console.log("[%s] Delivery id: ", connectionContext.connection.id, delivery.id); - - await sender.close(); - await connectionContext.connection.close(); -} - -main().catch((err) => console.log(err)); diff --git a/sdk/core/core-amqp/samples/tsconfig.json b/sdk/core/core-amqp/samples/tsconfig.json deleted file mode 100644 index c400c95a8623..000000000000 --- a/sdk/core/core-amqp/samples/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "module": "commonjs" - }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "../node_modules", - "../typings/**", - ] -} From 1dbfebad4ee023f804fa0368ffcc06b543cf1387 Mon Sep 17 00:00:00 2001 From: Jonathan Turner Date: Wed, 11 Nov 2020 13:37:34 +1300 Subject: [PATCH 33/35] [Identity] Change version to 1.2.0 and update changelog (#12451) * Update changelog and identity package version * Update changelog and identity package version * Add json * Fix broken tenant id * Add date to changelog --- .../app-configuration/test/testHelpers.ts | 2 +- sdk/identity/identity/CHANGELOG.md | 20 ++++++++++++++++--- sdk/identity/identity/package.json | 2 +- sdk/storage/storage-blob/package.json | 1 + .../storage-blob/rollup.base.config.js | 2 ++ .../storage-file-datalake/package.json | 1 + .../rollup.base.config.js | 2 ++ 7 files changed, 25 insertions(+), 5 deletions(-) diff --git a/sdk/appconfiguration/app-configuration/test/testHelpers.ts b/sdk/appconfiguration/app-configuration/test/testHelpers.ts index 3f17e89f8ea3..d7b91f40ba1d 100644 --- a/sdk/appconfiguration/app-configuration/test/testHelpers.ts +++ b/sdk/appconfiguration/app-configuration/test/testHelpers.ts @@ -31,7 +31,7 @@ export function startRecorder(that: any) { AZ_CONFIG_ENDPOINT: "https://myappconfig.azconfig.io", AZURE_CLIENT_ID: "azure_client_id", AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "azure_tenant_id" + AZURE_TENANT_ID: "azuretenantid" }, customizationsOnRecordings: [ (recording: any): any => diff --git a/sdk/identity/identity/CHANGELOG.md b/sdk/identity/identity/CHANGELOG.md index 1d0c7b0df8a6..7cff752e47c5 100644 --- a/sdk/identity/identity/CHANGELOG.md +++ b/sdk/identity/identity/CHANGELOG.md @@ -1,16 +1,30 @@ # Release History -## 1.2.0-beta.3 (Unreleased) +## 1.2.0 (2020-11-11) + +### Changes since 1.1.\* + +- With 1.2, we've added support for Azure Arc to our Managed Identity credential. +- We've also added an Interactive Browser credential for Node, which spawns the user's browser and connects via + a browser-based auth code flow. This is powered by the Microsoft Authentication Library (MSAL) +- We've moved `DeviceCodeCredential` to also use the Microsoft Authentication Library (MSAL) +- Identity now supports Subject Name/Issuer (SNI) as part of authentication for ClientCertificateCredential. +- Added Active Directory Federation Services authority host support to the node credentials. +- `ManagedIdentityCredential` has been aligned with other languages, and now treats expected errors properly. +- Added support for multiple clouds on `VisualStudioCodeCredential`. + +### Changes since the latest 1.2-beta - `ManagedIdentityCredential` now only checks for available MSIs once per class instance. - `ManagedIdentityCredential` now supports Azure Arc environments. - `ManagedIdentityCredential` now supports Azure Service Fabric environments. - Added authority host for multiple clouds on `VisualStudioCodeCredential`, and specified `AzureCloud` as the default cloud name. - `DeviceCodeCredential` now has both of its constructor parameters, `tenantId` and `clientId`, as optional parameters. The default value of `tenantId` is "organizations", and the Azure CLI's client ID is the default value of `clientId`. +- We've removed the persistent cache support from the previous beta. ## 1.2.0-beta.2 (2020-10-06) -- `DefaultAzureCredential` now by default shows the Device Code message on the console. This can still be overwritten with a custom behavior by specifying a function as the third parameter, `userPromptCallback`. +- `DeviceCodeCredential` now by default shows the Device Code message on the console. This can still be overwritten with a custom behavior by specifying a function as the third parameter, `userPromptCallback`. - Added support for multiple clouds on `VisualStudioCodeCredential`. Fixes customer issue [11452](https://github.com/Azure/azure-sdk-for-js/issues/11452). - `ManagedIdentityCredential` has been aligned with other languages, now treating expected errors properly. This fixes customer issue [11451](https://github.com/Azure/azure-sdk-for-js/issues/11451). - `InteractiveBrowserCredential` authentication now uses the silent flow if the user provides a cache and authentication record for lookup. @@ -26,7 +40,7 @@ ## 1.1.0 (2020-08-11) -### Changes since 1.0.* +### Changes since 1.0.\* - With 1.1.0, new developer credentials are now available: `VisualStudioCodeCredential` and `AzureCliCredential`. - `VisualStudioCodeCredential` allows developers to log into Azure using the credentials available after logging in through the Azure Account extension in Visual Studio Code. diff --git a/sdk/identity/identity/package.json b/sdk/identity/identity/package.json index bf64d3d9db93..9381047c0206 100644 --- a/sdk/identity/identity/package.json +++ b/sdk/identity/identity/package.json @@ -1,7 +1,7 @@ { "name": "@azure/identity", "sdk-type": "client", - "version": "1.2.0-beta.3", + "version": "1.2.0", "description": "Provides credential implementations for Azure SDK libraries that can authenticate with Azure Active Directory", "main": "dist/index.js", "module": "dist-esm/src/index.js", diff --git a/sdk/storage/storage-blob/package.json b/sdk/storage/storage-blob/package.json index cbc36f9de0a5..84d48a9d63cc 100644 --- a/sdk/storage/storage-blob/package.json +++ b/sdk/storage/storage-blob/package.json @@ -135,6 +135,7 @@ "@microsoft/api-extractor": "7.7.11", "@rollup/plugin-multi-entry": "^3.0.0", "@rollup/plugin-replace": "^2.2.0", + "@rollup/plugin-json": "^4.0.0", "@types/mocha": "^7.0.2", "@types/node": "^8.0.0", "assert": "^1.4.1", diff --git a/sdk/storage/storage-blob/rollup.base.config.js b/sdk/storage/storage-blob/rollup.base.config.js index a30f76c1f82a..fd7612fe2392 100644 --- a/sdk/storage/storage-blob/rollup.base.config.js +++ b/sdk/storage/storage-blob/rollup.base.config.js @@ -4,6 +4,7 @@ import nodeResolve from "@rollup/plugin-node-resolve"; import multiEntry from "@rollup/plugin-multi-entry"; import cjs from "@rollup/plugin-commonjs"; +import json from "@rollup/plugin-json"; import replace from "@rollup/plugin-replace"; import { terser } from "rollup-plugin-terser"; import sourcemaps from "rollup-plugin-sourcemaps"; @@ -51,6 +52,7 @@ export function nodeConfig(test = false) { "if (!isNode)": "if (false)" }), nodeResolve({ preferBuiltins: true }), + json(), cjs() ], onwarn(warning, warn) { diff --git a/sdk/storage/storage-file-datalake/package.json b/sdk/storage/storage-file-datalake/package.json index 1ddddaae8e63..cb7a678a221c 100644 --- a/sdk/storage/storage-file-datalake/package.json +++ b/sdk/storage/storage-file-datalake/package.json @@ -114,6 +114,7 @@ "@microsoft/api-extractor": "7.7.11", "@opentelemetry/api": "^0.10.2", "@rollup/plugin-commonjs": "11.0.2", + "@rollup/plugin-json": "^4.0.0", "@rollup/plugin-multi-entry": "^3.0.0", "@rollup/plugin-node-resolve": "^8.0.0", "@rollup/plugin-replace": "^2.2.0", diff --git a/sdk/storage/storage-file-datalake/rollup.base.config.js b/sdk/storage/storage-file-datalake/rollup.base.config.js index eaff02044be6..36b052b0e58b 100644 --- a/sdk/storage/storage-file-datalake/rollup.base.config.js +++ b/sdk/storage/storage-file-datalake/rollup.base.config.js @@ -2,6 +2,7 @@ // Licensed under the MIT License. import replace from "@rollup/plugin-replace"; import cjs from "@rollup/plugin-commonjs"; +import json from "@rollup/plugin-json"; import multiEntry from "@rollup/plugin-multi-entry"; import nodeResolve from "@rollup/plugin-node-resolve"; import shim from "rollup-plugin-shim"; @@ -50,6 +51,7 @@ export function nodeConfig(test = false) { "if (isNode)": "if (true)" }), nodeResolve({ preferBuiltins: true }), + json(), cjs({ namedExports: { events: ["EventEmitter"], From be84b9f31f7b65b8657ebd6864d3782802e15080 Mon Sep 17 00:00:00 2001 From: Dominik Date: Tue, 10 Nov 2020 17:55:08 -0800 Subject: [PATCH 34/35] [Communication] Fix homepage links in package.json (#12446) --- sdk/communication/communication-administration/package.json | 2 +- .../samples/javascript/package.json | 2 +- .../samples/typescript/package.json | 2 +- sdk/communication/communication-chat/package.json | 2 +- sdk/communication/communication-common/package.json | 2 +- sdk/communication/communication-sms/package.json | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/communication/communication-administration/package.json b/sdk/communication/communication-administration/package.json index 908bc550e666..6854a2fed324 100644 --- a/sdk/communication/communication-administration/package.json +++ b/sdk/communication/communication-administration/package.json @@ -56,7 +56,7 @@ "engines": { "node": ">=8.0.0" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/communication/communication-administration/", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-administration/", "sideEffects": false, "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", "dependencies": { diff --git a/sdk/communication/communication-administration/samples/javascript/package.json b/sdk/communication/communication-administration/samples/javascript/package.json index 268ddee07c85..ead8d5cc7fc5 100644 --- a/sdk/communication/communication-administration/samples/javascript/package.json +++ b/sdk/communication/communication-administration/samples/javascript/package.json @@ -20,7 +20,7 @@ "bugs": { "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-configuration", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-administration", "sideEffects": false, "dependencies": { "@azure/communication-administration": "latest", diff --git a/sdk/communication/communication-administration/samples/typescript/package.json b/sdk/communication/communication-administration/samples/typescript/package.json index a2a3941de76d..1d40ecef0353 100644 --- a/sdk/communication/communication-administration/samples/typescript/package.json +++ b/sdk/communication/communication-administration/samples/typescript/package.json @@ -24,7 +24,7 @@ "bugs": { "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-configuration", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-administration", "sideEffects": false, "dependencies": { "@azure/communication-administration": "latest", diff --git a/sdk/communication/communication-chat/package.json b/sdk/communication/communication-chat/package.json index 480a587cf077..9540fc514c2c 100644 --- a/sdk/communication/communication-chat/package.json +++ b/sdk/communication/communication-chat/package.json @@ -60,7 +60,7 @@ "engines": { "node": ">=8.0.0" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/communication/chat/", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-chat/", "sideEffects": false, "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", "dependencies": { diff --git a/sdk/communication/communication-common/package.json b/sdk/communication/communication-common/package.json index d6dbada3656b..26e79237b9d0 100644 --- a/sdk/communication/communication-common/package.json +++ b/sdk/communication/communication-common/package.json @@ -58,7 +58,7 @@ "engines": { "node": ">=8.0.0" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/communication/communication-common/", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-common/", "sideEffects": false, "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", "dependencies": { diff --git a/sdk/communication/communication-sms/package.json b/sdk/communication/communication-sms/package.json index 07fb4a0fa563..c2c31c93834a 100644 --- a/sdk/communication/communication-sms/package.json +++ b/sdk/communication/communication-sms/package.json @@ -60,7 +60,7 @@ "engines": { "node": ">=8.0.0" }, - "homepage": "https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/communication/sms/", + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/communication/communication-sms/", "sideEffects": false, "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", "dependencies": { From 5deb57d6e087d829e36ac981a066750cc1b4e143 Mon Sep 17 00:00:00 2001 From: SDK Automation Date: Wed, 11 Nov 2020 04:03:55 +0000 Subject: [PATCH 35/35] Generated from 73677f19181157fb0c154a084922a92fa6b528cd --- sdk/monitor/arm-monitor/LICENSE.txt | 2 +- sdk/monitor/arm-monitor/README.md | 11 +- sdk/monitor/arm-monitor/rollup.config.js | 4 +- .../src/models/actionGroupsMappers.ts | 6 +- .../src/models/activityLogAlertsMappers.ts | 6 +- .../src/models/activityLogsMappers.ts | 4 +- .../src/models/alertRuleIncidentsMappers.ts | 4 +- .../src/models/alertRulesMappers.ts | 6 +- .../src/models/autoscaleSettingsMappers.ts | 6 +- .../src/models/baselinesMappers.ts | 4 +- ...nosticSettingsCategoryOperationsMappers.ts | 6 +- .../diagnosticSettingsOperationsMappers.ts | 6 +- .../src/models/eventCategoriesMappers.ts | 4 +- sdk/monitor/arm-monitor/src/models/index.ts | 171 ++++++++++++++++-- .../src/models/logProfilesMappers.ts | 6 +- sdk/monitor/arm-monitor/src/models/mappers.ts | 110 ++++++++++- .../src/models/metricAlertsMappers.ts | 6 +- .../src/models/metricAlertsStatusMappers.ts | 4 +- .../src/models/metricBaselineMappers.ts | 4 +- .../src/models/metricDefinitionsMappers.ts | 4 +- .../src/models/metricNamespacesMappers.ts | 4 +- .../arm-monitor/src/models/metricsMappers.ts | 4 +- .../src/models/operationsMappers.ts | 4 +- .../arm-monitor/src/models/parameters.ts | 5 +- .../src/models/scheduledQueryRulesMappers.ts | 6 +- .../src/models/tenantActivityLogsMappers.ts | 4 +- .../src/models/vMInsightsMappers.ts | 6 +- .../src/monitorManagementClient.ts | 5 +- .../src/monitorManagementClientContext.ts | 7 +- .../src/operations/actionGroups.ts | 5 +- .../src/operations/activityLogAlerts.ts | 5 +- .../src/operations/activityLogs.ts | 61 ++++++- .../src/operations/alertRuleIncidents.ts | 5 +- .../arm-monitor/src/operations/alertRules.ts | 18 +- .../src/operations/autoscaleSettings.ts | 11 +- .../arm-monitor/src/operations/baselines.ts | 5 +- .../diagnosticSettingsCategoryOperations.ts | 5 +- .../diagnosticSettingsOperations.ts | 5 +- .../src/operations/eventCategories.ts | 5 +- .../arm-monitor/src/operations/index.ts | 5 +- .../arm-monitor/src/operations/logProfiles.ts | 5 +- .../src/operations/metricAlerts.ts | 5 +- .../src/operations/metricAlertsStatus.ts | 5 +- .../src/operations/metricBaseline.ts | 5 +- .../src/operations/metricDefinitions.ts | 5 +- .../src/operations/metricNamespaces.ts | 5 +- .../arm-monitor/src/operations/metrics.ts | 5 +- .../arm-monitor/src/operations/operations.ts | 5 +- .../src/operations/scheduledQueryRules.ts | 5 +- .../src/operations/tenantActivityLogs.ts | 16 +- .../arm-monitor/src/operations/vMInsights.ts | 5 +- 51 files changed, 456 insertions(+), 159 deletions(-) diff --git a/sdk/monitor/arm-monitor/LICENSE.txt b/sdk/monitor/arm-monitor/LICENSE.txt index b73b4a1293c3..ea8fb1516028 100644 --- a/sdk/monitor/arm-monitor/LICENSE.txt +++ b/sdk/monitor/arm-monitor/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2019 Microsoft +Copyright (c) 2020 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/sdk/monitor/arm-monitor/README.md b/sdk/monitor/arm-monitor/README.md index 04373a170952..c22c7725ef89 100644 --- a/sdk/monitor/arm-monitor/README.md +++ b/sdk/monitor/arm-monitor/README.md @@ -15,7 +15,7 @@ npm install @azure/arm-monitor ### How to use -#### nodejs - Authentication, client creation and listByResourceGroup autoscaleSettings as an example written in TypeScript. +#### nodejs - client creation and listByResourceGroup autoscaleSettings as an example written in TypeScript. ##### Install @azure/ms-rest-nodeauth @@ -26,11 +26,10 @@ npm install @azure/ms-rest-nodeauth@"^3.0.0" ##### Sample code +While the below sample uses the interactive login, other authentication options can be found in the [README.md file of @azure/ms-rest-nodeauth](https://www.npmjs.com/package/@azure/ms-rest-nodeauth) package ```typescript -import * as msRest from "@azure/ms-rest-js"; -import * as msRestAzure from "@azure/ms-rest-azure-js"; -import * as msRestNodeAuth from "@azure/ms-rest-nodeauth"; -import { MonitorManagementClient, MonitorManagementModels, MonitorManagementMappers } from "@azure/arm-monitor"; +const msRestNodeAuth = require("@azure/ms-rest-nodeauth"); +const { MonitorManagementClient } = require("@azure/arm-monitor"); const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"]; msRestNodeAuth.interactiveLogin().then((creds) => { @@ -98,4 +97,4 @@ See https://github.com/Azure/ms-rest-browserauth to learn how to authenticate to - [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js) -![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fmonitor%2Farm-monitor%2FREADME.png) +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js/sdk/monitor/arm-monitor/README.png) diff --git a/sdk/monitor/arm-monitor/rollup.config.js b/sdk/monitor/arm-monitor/rollup.config.js index 60aa3b0cb549..b33f5ee53343 100644 --- a/sdk/monitor/arm-monitor/rollup.config.js +++ b/sdk/monitor/arm-monitor/rollup.config.js @@ -21,8 +21,8 @@ const config = { "@azure/ms-rest-azure-js": "msRestAzure" }, banner: `/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/actionGroupsMappers.ts b/sdk/monitor/arm-monitor/src/models/actionGroupsMappers.ts index 11486f297d29..6f6063457eee 100644 --- a/sdk/monitor/arm-monitor/src/models/actionGroupsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/actionGroupsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -76,6 +76,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -86,5 +87,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/activityLogAlertsMappers.ts b/sdk/monitor/arm-monitor/src/models/activityLogAlertsMappers.ts index d949c6e04f10..77a836d11d5f 100644 --- a/sdk/monitor/arm-monitor/src/models/activityLogAlertsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/activityLogAlertsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -75,6 +75,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -85,5 +86,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/activityLogsMappers.ts b/sdk/monitor/arm-monitor/src/models/activityLogsMappers.ts index 80edb96348be..2a13149046c4 100644 --- a/sdk/monitor/arm-monitor/src/models/activityLogsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/activityLogsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/alertRuleIncidentsMappers.ts b/sdk/monitor/arm-monitor/src/models/alertRuleIncidentsMappers.ts index 1980277abff7..22e97bf9cbd2 100644 --- a/sdk/monitor/arm-monitor/src/models/alertRuleIncidentsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/alertRuleIncidentsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/alertRulesMappers.ts b/sdk/monitor/arm-monitor/src/models/alertRulesMappers.ts index 91bb37022f98..2b1e0503c38b 100644 --- a/sdk/monitor/arm-monitor/src/models/alertRulesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/alertRulesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -76,6 +76,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -86,5 +87,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/autoscaleSettingsMappers.ts b/sdk/monitor/arm-monitor/src/models/autoscaleSettingsMappers.ts index 68da5c7050e0..c9c876e0a030 100644 --- a/sdk/monitor/arm-monitor/src/models/autoscaleSettingsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/autoscaleSettingsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -75,6 +75,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -85,5 +86,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/baselinesMappers.ts b/sdk/monitor/arm-monitor/src/models/baselinesMappers.ts index b49d6f14718e..d00dd70e6bc9 100644 --- a/sdk/monitor/arm-monitor/src/models/baselinesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/baselinesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/diagnosticSettingsCategoryOperationsMappers.ts b/sdk/monitor/arm-monitor/src/models/diagnosticSettingsCategoryOperationsMappers.ts index 7402d3661f02..2d1247ebb504 100644 --- a/sdk/monitor/arm-monitor/src/models/diagnosticSettingsCategoryOperationsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/diagnosticSettingsCategoryOperationsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -74,6 +74,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -84,5 +85,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/diagnosticSettingsOperationsMappers.ts b/sdk/monitor/arm-monitor/src/models/diagnosticSettingsOperationsMappers.ts index f0ba9bbf166f..c340c0e9f57b 100644 --- a/sdk/monitor/arm-monitor/src/models/diagnosticSettingsOperationsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/diagnosticSettingsOperationsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -74,6 +74,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -84,5 +85,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/eventCategoriesMappers.ts b/sdk/monitor/arm-monitor/src/models/eventCategoriesMappers.ts index 3be0e41dbda8..8c9ac0515afa 100644 --- a/sdk/monitor/arm-monitor/src/models/eventCategoriesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/eventCategoriesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/index.ts b/sdk/monitor/arm-monitor/src/models/index.ts index 88cfd9ddd4cf..833d92a817e7 100644 --- a/sdk/monitor/arm-monitor/src/models/index.ts +++ b/sdk/monitor/arm-monitor/src/models/index.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -60,6 +60,26 @@ export interface ScaleCapacity { default: string; } +/** + * Specifies an auto scale rule metric dimension. + */ +export interface ScaleRuleMetricDimension { + /** + * Name of the dimension. + */ + dimensionName: string; + /** + * the dimension operator. Only 'Equals' and 'NotEquals' are supported. 'Equals' being equal to + * any of the values. 'NotEquals' being not equal to all of the values. Possible values include: + * 'Equals', 'NotEquals' + */ + operator: ScaleRuleMetricDimensionOperationType; + /** + * list of dimension values. For example: ["App1","App2"]. + */ + values: string[]; +} + /** * The trigger that results in a scaling action. */ @@ -68,6 +88,10 @@ export interface MetricTrigger { * the name of the metric that defines what the rule monitors. */ metricName: string; + /** + * the namespace of the metric that defines what the rule monitors. + */ + metricNamespace?: string; /** * the resource identifier of the resource the rule monitors. */ @@ -104,6 +128,11 @@ export interface MetricTrigger { * the threshold of the metric that triggers the scale action. */ threshold: number; + /** + * List of dimension conditions. For example: + * [{"DimensionName":"AppName","Operator":"Equals","Values":["App1"]},{"DimensionName":"Deployment","Operator":"Equals","Values":["default"]}]. + */ + dimensions?: ScaleRuleMetricDimension[]; } /** @@ -2113,13 +2142,13 @@ export interface MetricAlertAction { /** * The properties of a webhook object. */ - webhookProperties?: { [propertyName: string]: string }; + webHookProperties?: { [propertyName: string]: string }; } /** * Contains the possible cases for MetricAlertCriteria. */ -export type MetricAlertCriteriaUnion = MetricAlertCriteria | MetricAlertSingleResourceMultipleMetricCriteria | MetricAlertMultipleResourceMultipleMetricCriteria; +export type MetricAlertCriteriaUnion = MetricAlertCriteria | MetricAlertSingleResourceMultipleMetricCriteria | WebtestLocationAvailabilityCriteria | MetricAlertMultipleResourceMultipleMetricCriteria; /** * The rule criteria that defines the conditions of the alert rule. @@ -2179,7 +2208,7 @@ export interface MetricAlertResource extends Resource { */ criteria: MetricAlertCriteriaUnion; /** - * the flag that indicates whether the alert should be auto resolved or not. + * the flag that indicates whether the alert should be auto resolved or not. The default is true. */ autoMitigate?: boolean; /** @@ -2242,7 +2271,7 @@ export interface MetricAlertResourcePatch { */ criteria: MetricAlertCriteriaUnion; /** - * the flag that indicates whether the alert should be auto resolved or not. + * the flag that indicates whether the alert should be auto resolved or not. The default is true. */ autoMitigate?: boolean; /** @@ -2340,6 +2369,11 @@ export interface MultiMetricCriteria { * List of dimension conditions. */ dimensions?: MetricDimension[]; + /** + * Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric + * validation to be skipped. + */ + skipMetricValidation?: boolean; /** * Describes unknown properties. The value of an unknown property can be of "any" type. */ @@ -2375,9 +2409,15 @@ export interface MetricCriteria { */ dimensions?: MetricDimension[]; /** - * the criteria operator. + * Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric + * validation to be skipped. */ - operator: any; + skipMetricValidation?: boolean; + /** + * the criteria operator. Possible values include: 'Equals', 'NotEquals', 'GreaterThan', + * 'GreaterThanOrEqual', 'LessThan', 'LessThanOrEqual' + */ + operator: Operator; /** * the criteria threshold value that activates the alert. */ @@ -2398,6 +2438,28 @@ export interface MetricAlertSingleResourceMultipleMetricCriteria { allOf?: MetricCriteria[]; } +/** + * Specifies the metric alert rule criteria for a web test resource. + */ +export interface WebtestLocationAvailabilityCriteria { + /** + * Polymorphic Discriminator + */ + odatatype: "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria"; + /** + * The Application Insights web test Id. + */ + webTestId: string; + /** + * The Application Insights resource Id. + */ + componentId: string; + /** + * The number of failed locations. + */ + failedLocationCount: number; +} + /** * Specifies a metric dimension. */ @@ -2476,14 +2538,20 @@ export interface DynamicMetricCriteria { */ dimensions?: MetricDimension[]; /** - * The operator used to compare the metric value against the threshold. + * Allows creating an alert rule on a custom metric that isn't yet emitted, by causing the metric + * validation to be skipped. + */ + skipMetricValidation?: boolean; + /** + * The operator used to compare the metric value against the threshold. Possible values include: + * 'GreaterThan', 'LessThan', 'GreaterOrLessThan' */ - operator: any; + operator: DynamicThresholdOperator; /** * The extent of deviation required to trigger an alert. This will affect how tight the threshold - * is to the metric series pattern. + * is to the metric series pattern. Possible values include: 'Low', 'Medium', 'High' */ - alertSensitivity: any; + alertSensitivity: DynamicThresholdSensitivity; /** * The minimum number of violations required within the selected lookback time window required to * raise an alert. @@ -2877,6 +2945,21 @@ export interface ActivityLogsListOptionalParams extends msRest.RequestOptionsBas select?: string; } +/** + * Optional Parameters. + */ +export interface ActivityLogsListNextOptionalParams extends msRest.RequestOptionsBase { + /** + * Used to fetch events with only the given properties.
The **$select** argument is a comma + * separated list of property names to be returned. Possible values are: *authorization*, + * *claims*, *correlationId*, *description*, *eventDataId*, *eventName*, *eventTimestamp*, + * *httpRequest*, *level*, *operationId*, *operationName*, *properties*, *resourceGroupName*, + * *resourceProviderName*, *resourceId*, *status*, *submissionTimestamp*, *subStatus*, + * *subscriptionId* + */ + select?: string; +} + /** * Optional Parameters. */ @@ -2908,6 +2991,37 @@ export interface TenantActivityLogsListOptionalParams extends msRest.RequestOpti select?: string; } +/** + * Optional Parameters. + */ +export interface TenantActivityLogsListNextOptionalParams extends msRest.RequestOptionsBase { + /** + * Reduces the set of data collected.
The **$filter** is very restricted and allows only the + * following patterns.
- List events for a resource group: $filter=eventTimestamp ge '' and eventTimestamp le '' and eventChannels eq 'Admin, Operation' and + * resourceGroupName eq ''.
- List events for resource: + * $filter=eventTimestamp ge '' and eventTimestamp le '' and eventChannels + * eq 'Admin, Operation' and resourceUri eq ''.
- List events for a subscription: + * $filter=eventTimestamp ge '' and eventTimestamp le '' and eventChannels + * eq 'Admin, Operation'.
- List events for a resource provider: $filter=eventTimestamp ge + * '' and eventTimestamp le '' and eventChannels eq 'Admin, Operation' and + * resourceProvider eq ''.
- List events for a correlation Id: + * api-version=2014-04-01&$filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z' and eventChannels eq 'Admin, Operation' and + * correlationId eq ''.
**NOTE**: No other syntax is allowed. + */ + filter?: string; + /** + * Used to fetch events with only the given properties.
The **$select** argument is a comma + * separated list of property names to be returned. Possible values are: *authorization*, + * *claims*, *correlationId*, *description*, *eventDataId*, *eventName*, *eventTimestamp*, + * *httpRequest*, *level*, *operationId*, *operationName*, *properties*, *resourceGroupName*, + * *resourceProviderName*, *resourceId*, *status*, *submissionTimestamp*, *subStatus*, + * *subscriptionId* + */ + select?: string; +} + /** * Optional Parameters. */ @@ -3233,6 +3347,14 @@ export type TimeAggregationType = 'Average' | 'Minimum' | 'Maximum' | 'Total' | */ export type ComparisonOperationType = 'Equals' | 'NotEquals' | 'GreaterThan' | 'GreaterThanOrEqual' | 'LessThan' | 'LessThanOrEqual'; +/** + * Defines values for ScaleRuleMetricDimensionOperationType. + * Possible values include: 'Equals', 'NotEquals' + * @readonly + * @enum {string} + */ +export type ScaleRuleMetricDimensionOperationType = 'Equals' | 'NotEquals'; + /** * Defines values for ScaleDirection. * Possible values include: 'None', 'Increase', 'Decrease' @@ -3331,6 +3453,31 @@ export type Sensitivity = 'Low' | 'Medium' | 'High'; */ export type BaselineSensitivity = 'Low' | 'Medium' | 'High'; +/** + * Defines values for Operator. + * Possible values include: 'Equals', 'NotEquals', 'GreaterThan', 'GreaterThanOrEqual', 'LessThan', + * 'LessThanOrEqual' + * @readonly + * @enum {string} + */ +export type Operator = 'Equals' | 'NotEquals' | 'GreaterThan' | 'GreaterThanOrEqual' | 'LessThan' | 'LessThanOrEqual'; + +/** + * Defines values for DynamicThresholdOperator. + * Possible values include: 'GreaterThan', 'LessThan', 'GreaterOrLessThan' + * @readonly + * @enum {string} + */ +export type DynamicThresholdOperator = 'GreaterThan' | 'LessThan' | 'GreaterOrLessThan'; + +/** + * Defines values for DynamicThresholdSensitivity. + * Possible values include: 'Low', 'Medium', 'High' + * @readonly + * @enum {string} + */ +export type DynamicThresholdSensitivity = 'Low' | 'Medium' | 'High'; + /** * Defines values for Enabled. * Possible values include: 'true', 'false' diff --git a/sdk/monitor/arm-monitor/src/models/logProfilesMappers.ts b/sdk/monitor/arm-monitor/src/models/logProfilesMappers.ts index a1ad33c209e5..d9aa57b662cf 100644 --- a/sdk/monitor/arm-monitor/src/models/logProfilesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/logProfilesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -76,6 +76,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -86,5 +87,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/mappers.ts b/sdk/monitor/arm-monitor/src/models/mappers.ts index 3528feefba03..ed121f4a0a26 100644 --- a/sdk/monitor/arm-monitor/src/models/mappers.ts +++ b/sdk/monitor/arm-monitor/src/models/mappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -92,6 +92,42 @@ export const ScaleCapacity: msRest.CompositeMapper = { } }; +export const ScaleRuleMetricDimension: msRest.CompositeMapper = { + serializedName: "ScaleRuleMetricDimension", + type: { + name: "Composite", + className: "ScaleRuleMetricDimension", + modelProperties: { + dimensionName: { + required: true, + serializedName: "DimensionName", + type: { + name: "String" + } + }, + operator: { + required: true, + serializedName: "Operator", + type: { + name: "String" + } + }, + values: { + required: true, + serializedName: "Values", + type: { + name: "Sequence", + element: { + type: { + name: "String" + } + } + } + } + } + } +}; + export const MetricTrigger: msRest.CompositeMapper = { serializedName: "MetricTrigger", type: { @@ -105,6 +141,12 @@ export const MetricTrigger: msRest.CompositeMapper = { name: "String" } }, + metricNamespace: { + serializedName: "metricNamespace", + type: { + name: "String" + } + }, metricResourceUri: { required: true, serializedName: "metricResourceUri", @@ -175,6 +217,18 @@ export const MetricTrigger: msRest.CompositeMapper = { type: { name: "Number" } + }, + dimensions: { + serializedName: "dimensions", + type: { + name: "Sequence", + element: { + type: { + name: "Composite", + className: "ScaleRuleMetricDimension" + } + } + } } } } @@ -3591,8 +3645,8 @@ export const MetricAlertAction: msRest.CompositeMapper = { name: "String" } }, - webhookProperties: { - serializedName: "webhookProperties", + webHookProperties: { + serializedName: "webHookProperties", type: { name: "Dictionary", value: { @@ -3997,6 +4051,12 @@ export const MultiMetricCriteria: msRest.CompositeMapper = { } } }, + skipMetricValidation: { + serializedName: "skipMetricValidation", + type: { + name: "Boolean" + } + }, criterionType: { required: true, serializedName: "criterionType", @@ -4026,7 +4086,7 @@ export const MetricCriteria: msRest.CompositeMapper = { required: true, serializedName: "operator", type: { - name: "Object" + name: "String" } }, threshold: { @@ -4068,6 +4128,41 @@ export const MetricAlertSingleResourceMultipleMetricCriteria: msRest.CompositeMa } }; +export const WebtestLocationAvailabilityCriteria: msRest.CompositeMapper = { + serializedName: "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria", + type: { + name: "Composite", + polymorphicDiscriminator: MetricAlertCriteria.type.polymorphicDiscriminator, + uberParent: "MetricAlertCriteria", + className: "WebtestLocationAvailabilityCriteria", + modelProperties: { + ...MetricAlertCriteria.type.modelProperties, + webTestId: { + required: true, + serializedName: "webTestId", + type: { + name: "String" + } + }, + componentId: { + required: true, + serializedName: "componentId", + type: { + name: "String" + } + }, + failedLocationCount: { + required: true, + serializedName: "failedLocationCount", + type: { + name: "Number" + } + } + }, + additionalProperties: MetricAlertCriteria.type.additionalProperties + } +}; + export const MetricDimension: msRest.CompositeMapper = { serializedName: "MetricDimension", type: { @@ -4172,14 +4267,14 @@ export const DynamicMetricCriteria: msRest.CompositeMapper = { required: true, serializedName: "operator", type: { - name: "Object" + name: "String" } }, alertSensitivity: { required: true, serializedName: "alertSensitivity", type: { - name: "Object" + name: "String" } }, failingPeriods: { @@ -5140,6 +5235,7 @@ export const discriminators = { 'MetricAlertCriteria' : MetricAlertCriteria, 'MultiMetricCriteria.StaticThresholdCriterion' : MetricCriteria, 'MetricAlertCriteria.Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria' : MetricAlertSingleResourceMultipleMetricCriteria, + 'MetricAlertCriteria.Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria' : WebtestLocationAvailabilityCriteria, 'MultiMetricCriteria' : MultiMetricCriteria, 'MetricAlertCriteria.Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria' : MetricAlertMultipleResourceMultipleMetricCriteria, 'MultiMetricCriteria.DynamicThresholdCriterion' : DynamicMetricCriteria, diff --git a/sdk/monitor/arm-monitor/src/models/metricAlertsMappers.ts b/sdk/monitor/arm-monitor/src/models/metricAlertsMappers.ts index a6d76f72efbc..9cabd47b83c2 100644 --- a/sdk/monitor/arm-monitor/src/models/metricAlertsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricAlertsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -76,6 +76,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -86,5 +87,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/metricAlertsStatusMappers.ts b/sdk/monitor/arm-monitor/src/models/metricAlertsStatusMappers.ts index a044e8994582..8c4636ce6a53 100644 --- a/sdk/monitor/arm-monitor/src/models/metricAlertsStatusMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricAlertsStatusMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/metricBaselineMappers.ts b/sdk/monitor/arm-monitor/src/models/metricBaselineMappers.ts index 7fbb371a4578..ba6e2fc8c24e 100644 --- a/sdk/monitor/arm-monitor/src/models/metricBaselineMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricBaselineMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/metricDefinitionsMappers.ts b/sdk/monitor/arm-monitor/src/models/metricDefinitionsMappers.ts index 31046db255a5..3f54d4385ddb 100644 --- a/sdk/monitor/arm-monitor/src/models/metricDefinitionsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricDefinitionsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/metricNamespacesMappers.ts b/sdk/monitor/arm-monitor/src/models/metricNamespacesMappers.ts index 2e78b28244cd..d45faccf423a 100644 --- a/sdk/monitor/arm-monitor/src/models/metricNamespacesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricNamespacesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/metricsMappers.ts b/sdk/monitor/arm-monitor/src/models/metricsMappers.ts index 0796246e9fe7..1b5fdcd9a4ca 100644 --- a/sdk/monitor/arm-monitor/src/models/metricsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/metricsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/operationsMappers.ts b/sdk/monitor/arm-monitor/src/models/operationsMappers.ts index 65fc7dd1800a..1cf01eeef205 100644 --- a/sdk/monitor/arm-monitor/src/models/operationsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/operationsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/parameters.ts b/sdk/monitor/arm-monitor/src/models/parameters.ts index eac83a80fc9e..642a663f160f 100644 --- a/sdk/monitor/arm-monitor/src/models/parameters.ts +++ b/sdk/monitor/arm-monitor/src/models/parameters.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/models/scheduledQueryRulesMappers.ts b/sdk/monitor/arm-monitor/src/models/scheduledQueryRulesMappers.ts index 0fffe5f5617c..5a847b7161d9 100644 --- a/sdk/monitor/arm-monitor/src/models/scheduledQueryRulesMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/scheduledQueryRulesMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -75,6 +75,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -85,5 +86,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/models/tenantActivityLogsMappers.ts b/sdk/monitor/arm-monitor/src/models/tenantActivityLogsMappers.ts index 80edb96348be..2a13149046c4 100644 --- a/sdk/monitor/arm-monitor/src/models/tenantActivityLogsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/tenantActivityLogsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. diff --git a/sdk/monitor/arm-monitor/src/models/vMInsightsMappers.ts b/sdk/monitor/arm-monitor/src/models/vMInsightsMappers.ts index 3e0639f45f11..f4ff64755344 100644 --- a/sdk/monitor/arm-monitor/src/models/vMInsightsMappers.ts +++ b/sdk/monitor/arm-monitor/src/models/vMInsightsMappers.ts @@ -1,6 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. @@ -74,6 +74,7 @@ export { ScaleAction, ScaleCapacity, ScaleRule, + ScaleRuleMetricDimension, Schedule, SmsReceiver, Source, @@ -84,5 +85,6 @@ export { VoiceReceiver, WebhookNotification, WebhookReceiver, + WebtestLocationAvailabilityCriteria, WorkspaceInfo } from "../models/mappers"; diff --git a/sdk/monitor/arm-monitor/src/monitorManagementClient.ts b/sdk/monitor/arm-monitor/src/monitorManagementClient.ts index a498d7b03d34..9c6083fa0521 100644 --- a/sdk/monitor/arm-monitor/src/monitorManagementClient.ts +++ b/sdk/monitor/arm-monitor/src/monitorManagementClient.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/monitorManagementClientContext.ts b/sdk/monitor/arm-monitor/src/monitorManagementClientContext.ts index aacdc007667d..a12d2ef7ee3b 100644 --- a/sdk/monitor/arm-monitor/src/monitorManagementClientContext.ts +++ b/sdk/monitor/arm-monitor/src/monitorManagementClientContext.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -13,7 +12,7 @@ import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; const packageName = "@azure/arm-monitor"; -const packageVersion = "5.4.0"; +const packageVersion = "6.0.0"; export class MonitorManagementClientContext extends msRestAzure.AzureServiceClient { credentials: msRest.ServiceClientCredentials; diff --git a/sdk/monitor/arm-monitor/src/operations/actionGroups.ts b/sdk/monitor/arm-monitor/src/operations/actionGroups.ts index f0d61a682139..d9ea51a92776 100644 --- a/sdk/monitor/arm-monitor/src/operations/actionGroups.ts +++ b/sdk/monitor/arm-monitor/src/operations/actionGroups.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/activityLogAlerts.ts b/sdk/monitor/arm-monitor/src/operations/activityLogAlerts.ts index 257a6277a91e..ca1477d42b33 100644 --- a/sdk/monitor/arm-monitor/src/operations/activityLogAlerts.ts +++ b/sdk/monitor/arm-monitor/src/operations/activityLogAlerts.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/activityLogs.ts b/sdk/monitor/arm-monitor/src/operations/activityLogs.ts index 561f7d7f4eba..dd517a8535a7 100644 --- a/sdk/monitor/arm-monitor/src/operations/activityLogs.ts +++ b/sdk/monitor/arm-monitor/src/operations/activityLogs.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -96,25 +95,68 @@ export class ActivityLogs { /** * Provides the list of records from the activity logs. * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param filter Reduces the set of data collected.
This argument is required and it also + * requires at least the start date/time.
The **$filter** argument is very restricted and allows + * only the following patterns.
- *List events for a resource group*: $filter=eventTimestamp ge + * '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and + * resourceGroupName eq 'resourceGroupName'.
- *List events for resource*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.
- *List events for a + * subscription in a time range*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z'.
- *List events for a resource provider*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.
- *List events + * for a correlation Id*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq + * 'correlationID'.

**NOTE**: No other syntax is allowed. * @param [options] The optional parameters * @returns Promise */ - listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise; + listNext(nextPageLink: string, filter: string, options?: Models.ActivityLogsListNextOptionalParams): Promise; /** * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param filter Reduces the set of data collected.
This argument is required and it also + * requires at least the start date/time.
The **$filter** argument is very restricted and allows + * only the following patterns.
- *List events for a resource group*: $filter=eventTimestamp ge + * '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and + * resourceGroupName eq 'resourceGroupName'.
- *List events for resource*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.
- *List events for a + * subscription in a time range*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z'.
- *List events for a resource provider*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.
- *List events + * for a correlation Id*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq + * 'correlationID'.

**NOTE**: No other syntax is allowed. * @param callback The callback */ - listNext(nextPageLink: string, callback: msRest.ServiceCallback): void; + listNext(nextPageLink: string, filter: string, callback: msRest.ServiceCallback): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param filter Reduces the set of data collected.
This argument is required and it also + * requires at least the start date/time.
The **$filter** argument is very restricted and allows + * only the following patterns.
- *List events for a resource group*: $filter=eventTimestamp ge + * '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and + * resourceGroupName eq 'resourceGroupName'.
- *List events for resource*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.
- *List events for a + * subscription in a time range*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z'.
- *List events for a resource provider*: + * $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le + * '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.
- *List events + * for a correlation Id*: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and + * eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq + * 'correlationID'.

**NOTE**: No other syntax is allowed. * @param options The optional parameters * @param callback The callback */ - listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback): void; - listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback, callback?: msRest.ServiceCallback): Promise { + listNext(nextPageLink: string, filter: string, options: Models.ActivityLogsListNextOptionalParams, callback: msRest.ServiceCallback): void; + listNext(nextPageLink: string, filter: string, options?: Models.ActivityLogsListNextOptionalParams | msRest.ServiceCallback, callback?: msRest.ServiceCallback): Promise { return this.client.sendOperationRequest( { nextPageLink, + filter, options }, listNextOperationSpec, @@ -156,6 +198,11 @@ const listNextOperationSpec: msRest.OperationSpec = { urlParameters: [ Parameters.nextPageLink ], + queryParameters: [ + Parameters.apiVersion0, + Parameters.filter0, + Parameters.select + ], headerParameters: [ Parameters.acceptLanguage ], diff --git a/sdk/monitor/arm-monitor/src/operations/alertRuleIncidents.ts b/sdk/monitor/arm-monitor/src/operations/alertRuleIncidents.ts index 77453e3b2b0f..11cad3bd4694 100644 --- a/sdk/monitor/arm-monitor/src/operations/alertRuleIncidents.ts +++ b/sdk/monitor/arm-monitor/src/operations/alertRuleIncidents.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/alertRules.ts b/sdk/monitor/arm-monitor/src/operations/alertRules.ts index 79429b70aaf1..3a3f1670901a 100644 --- a/sdk/monitor/arm-monitor/src/operations/alertRules.ts +++ b/sdk/monitor/arm-monitor/src/operations/alertRules.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -27,7 +26,7 @@ export class AlertRules { } /** - * Creates or updates an alert rule. + * Creates or updates a classic metric alert rule. * @param resourceGroupName The name of the resource group. * @param ruleName The name of the rule. * @param parameters The parameters of the rule to create or update. @@ -63,7 +62,7 @@ export class AlertRules { } /** - * Deletes an alert rule + * Deletes a classic metric alert rule * @param resourceGroupName The name of the resource group. * @param ruleName The name of the rule. * @param [options] The optional parameters @@ -95,7 +94,7 @@ export class AlertRules { } /** - * Gets an alert rule + * Gets a classic metric alert rule * @param resourceGroupName The name of the resource group. * @param ruleName The name of the rule. * @param [options] The optional parameters @@ -127,7 +126,8 @@ export class AlertRules { } /** - * Updates an existing AlertRuleResource. To update other fields use the CreateOrUpdate method. + * Updates an existing classic metric AlertRuleResource. To update other fields use the + * CreateOrUpdate method. * @param resourceGroupName The name of the resource group. * @param ruleName The name of the rule. * @param alertRulesResource Parameters supplied to the operation. @@ -163,7 +163,7 @@ export class AlertRules { } /** - * List the alert rules within a resource group. + * List the classic metric alert rules within a resource group. * @param resourceGroupName The name of the resource group. * @param [options] The optional parameters * @returns Promise @@ -191,7 +191,7 @@ export class AlertRules { } /** - * List the alert rules within a subscription. + * List the classic metric alert rules within a subscription. * @param [options] The optional parameters * @returns Promise */ diff --git a/sdk/monitor/arm-monitor/src/operations/autoscaleSettings.ts b/sdk/monitor/arm-monitor/src/operations/autoscaleSettings.ts index fa3828276d8e..fcaeb8295afd 100644 --- a/sdk/monitor/arm-monitor/src/operations/autoscaleSettings.ts +++ b/sdk/monitor/arm-monitor/src/operations/autoscaleSettings.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -444,6 +443,9 @@ const listByResourceGroupNextOperationSpec: msRest.OperationSpec = { urlParameters: [ Parameters.nextPageLink ], + queryParameters: [ + Parameters.apiVersion0 + ], headerParameters: [ Parameters.acceptLanguage ], @@ -465,6 +467,9 @@ const listBySubscriptionNextOperationSpec: msRest.OperationSpec = { urlParameters: [ Parameters.nextPageLink ], + queryParameters: [ + Parameters.apiVersion0 + ], headerParameters: [ Parameters.acceptLanguage ], diff --git a/sdk/monitor/arm-monitor/src/operations/baselines.ts b/sdk/monitor/arm-monitor/src/operations/baselines.ts index 60e9fb93f39a..d165b623304a 100644 --- a/sdk/monitor/arm-monitor/src/operations/baselines.ts +++ b/sdk/monitor/arm-monitor/src/operations/baselines.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsCategoryOperations.ts b/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsCategoryOperations.ts index 696518269cd8..0869d3d17322 100644 --- a/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsCategoryOperations.ts +++ b/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsCategoryOperations.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsOperations.ts b/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsOperations.ts index 8153aa322d65..1e904323adfe 100644 --- a/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsOperations.ts +++ b/sdk/monitor/arm-monitor/src/operations/diagnosticSettingsOperations.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/eventCategories.ts b/sdk/monitor/arm-monitor/src/operations/eventCategories.ts index 67bd8f4311b4..5d8312b0750b 100644 --- a/sdk/monitor/arm-monitor/src/operations/eventCategories.ts +++ b/sdk/monitor/arm-monitor/src/operations/eventCategories.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/index.ts b/sdk/monitor/arm-monitor/src/operations/index.ts index a7964c5cac32..d4daea884535 100644 --- a/sdk/monitor/arm-monitor/src/operations/index.ts +++ b/sdk/monitor/arm-monitor/src/operations/index.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/logProfiles.ts b/sdk/monitor/arm-monitor/src/operations/logProfiles.ts index 1ae52e5613b7..a214f0ebde99 100644 --- a/sdk/monitor/arm-monitor/src/operations/logProfiles.ts +++ b/sdk/monitor/arm-monitor/src/operations/logProfiles.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metricAlerts.ts b/sdk/monitor/arm-monitor/src/operations/metricAlerts.ts index f7d435bd6048..d59348322d34 100644 --- a/sdk/monitor/arm-monitor/src/operations/metricAlerts.ts +++ b/sdk/monitor/arm-monitor/src/operations/metricAlerts.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metricAlertsStatus.ts b/sdk/monitor/arm-monitor/src/operations/metricAlertsStatus.ts index 018c13a6bff6..79a724bf99a5 100644 --- a/sdk/monitor/arm-monitor/src/operations/metricAlertsStatus.ts +++ b/sdk/monitor/arm-monitor/src/operations/metricAlertsStatus.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metricBaseline.ts b/sdk/monitor/arm-monitor/src/operations/metricBaseline.ts index 0cd73b9d1c3e..90b121240879 100644 --- a/sdk/monitor/arm-monitor/src/operations/metricBaseline.ts +++ b/sdk/monitor/arm-monitor/src/operations/metricBaseline.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metricDefinitions.ts b/sdk/monitor/arm-monitor/src/operations/metricDefinitions.ts index 23a9932d767b..80802f0d8c75 100644 --- a/sdk/monitor/arm-monitor/src/operations/metricDefinitions.ts +++ b/sdk/monitor/arm-monitor/src/operations/metricDefinitions.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metricNamespaces.ts b/sdk/monitor/arm-monitor/src/operations/metricNamespaces.ts index 447750b8340e..8dad0d3d8c97 100644 --- a/sdk/monitor/arm-monitor/src/operations/metricNamespaces.ts +++ b/sdk/monitor/arm-monitor/src/operations/metricNamespaces.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/metrics.ts b/sdk/monitor/arm-monitor/src/operations/metrics.ts index 9f613ea4236f..694bb20ebab7 100644 --- a/sdk/monitor/arm-monitor/src/operations/metrics.ts +++ b/sdk/monitor/arm-monitor/src/operations/metrics.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/operations.ts b/sdk/monitor/arm-monitor/src/operations/operations.ts index a6faf8a59a89..206ca3d8a880 100644 --- a/sdk/monitor/arm-monitor/src/operations/operations.ts +++ b/sdk/monitor/arm-monitor/src/operations/operations.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/scheduledQueryRules.ts b/sdk/monitor/arm-monitor/src/operations/scheduledQueryRules.ts index 2e49d3d94545..3b5d2ed74e01 100644 --- a/sdk/monitor/arm-monitor/src/operations/scheduledQueryRules.ts +++ b/sdk/monitor/arm-monitor/src/operations/scheduledQueryRules.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is diff --git a/sdk/monitor/arm-monitor/src/operations/tenantActivityLogs.ts b/sdk/monitor/arm-monitor/src/operations/tenantActivityLogs.ts index 330e604f77f1..2f8a152a7bdd 100644 --- a/sdk/monitor/arm-monitor/src/operations/tenantActivityLogs.ts +++ b/sdk/monitor/arm-monitor/src/operations/tenantActivityLogs.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is @@ -64,7 +63,7 @@ export class TenantActivityLogs { * @param [options] The optional parameters * @returns Promise */ - listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise; + listNext(nextPageLink: string, options?: Models.TenantActivityLogsListNextOptionalParams): Promise; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback @@ -75,8 +74,8 @@ export class TenantActivityLogs { * @param options The optional parameters * @param callback The callback */ - listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback): void; - listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback, callback?: msRest.ServiceCallback): Promise { + listNext(nextPageLink: string, options: Models.TenantActivityLogsListNextOptionalParams, callback: msRest.ServiceCallback): void; + listNext(nextPageLink: string, options?: Models.TenantActivityLogsListNextOptionalParams | msRest.ServiceCallback, callback?: msRest.ServiceCallback): Promise { return this.client.sendOperationRequest( { nextPageLink, @@ -118,6 +117,11 @@ const listNextOperationSpec: msRest.OperationSpec = { urlParameters: [ Parameters.nextPageLink ], + queryParameters: [ + Parameters.apiVersion0, + Parameters.filter1, + Parameters.select + ], headerParameters: [ Parameters.acceptLanguage ], diff --git a/sdk/monitor/arm-monitor/src/operations/vMInsights.ts b/sdk/monitor/arm-monitor/src/operations/vMInsights.ts index 1b0ecbdbe27e..b2b7040e3d51 100644 --- a/sdk/monitor/arm-monitor/src/operations/vMInsights.ts +++ b/sdk/monitor/arm-monitor/src/operations/vMInsights.ts @@ -1,7 +1,6 @@ /* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is