diff --git a/common/config/rush/common-versions.json b/common/config/rush/common-versions.json index 6db47e061f6c..48d288dca8e9 100644 --- a/common/config/rush/common-versions.json +++ b/common/config/rush/common-versions.json @@ -49,9 +49,6 @@ // "typescript": [ // "~2.4.0" // ] - // Following is required to allow for backward compatibility with Service Bus Track 1 - // TODO: Remove this once Service Bus is updated to use current depenedencies as part of Track 2 - "rhea-promise": ["^0.1.15"], // Following is required to allow for backward compatibility with Event Processor Host Track 1 "@azure/event-hubs": ["^2.1.4"] } diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index e3c15d056d50..d2532245fb07 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -35,27 +35,6 @@ packages: dev: false resolution: integrity: sha512-wP2Jw6uPp8DEDy0n4KNidvwzDjyVV2xnycEIq7nPzj1rHyb/r+t3OPeNT1INZePP2wy5ZqlwyuyOMTi0ePyY1A== - /@azure/amqp-common/1.0.0-preview.10: - dependencies: - '@azure/ms-rest-nodeauth': 0.9.3 - '@types/async-lock': 1.1.1 - '@types/is-buffer': 2.0.0 - async-lock: 1.2.2 - buffer: 5.4.3 - debug: 3.2.6 - events: 3.1.0 - is-buffer: 2.0.4 - jssha: 2.3.1 - process: 0.11.10 - rhea: 1.0.18 - rhea-promise: 0.1.15 - stream-browserify: 2.0.2 - tslib: 1.10.0 - url: 0.11.0 - util: 0.11.1 - dev: false - resolution: - integrity: sha512-1Qm74g99Rrb7xBzl5UFKLA9/DZEfiwmlgc5XX8Alwknkzua4Mf2XPaky3vuXMZ03ClG4Sbhl4U9NleQ83SrEzA== /@azure/amqp-common/1.0.0-preview.9: dependencies: '@azure/ms-rest-nodeauth': 0.9.3 @@ -8058,7 +8037,7 @@ packages: dev: false name: '@rush-temp/abort-controller' resolution: - integrity: sha512-Xla0VK+eEW8lnCzVyAL5++AoKQgNU1zHAUmoHSyMUCMpSG3KaUQiyOpfNyOG29yJ1r9I0z71m30NzRZtHFm39Q== + integrity: sha512-DO1D00rXpn1zUunQUSSF6VF1CU3nTbSMnoJo4y1y7/HoDjwgvq2Lifu64PscEv8Xs/EqejGGQUldCTlkwJ/wfw== tarball: 'file:projects/abort-controller.tgz' version: 0.0.0 'file:projects/ai-text-analytics.tgz': @@ -8118,7 +8097,7 @@ packages: dev: false name: '@rush-temp/ai-text-analytics' resolution: - integrity: sha512-fqA10W69RAm4E1lXTZEX3wiCTIYcMG4BfLFL+VwKLdSIewSmK76a52JegKuKEMc6j05twqBDUyIiwbxGV9nG+g== + integrity: sha512-s4AvJH9H5CinaWgZKeL8P2UwpEL7sa5g4J51gAe/Y1AidxkZpqDLlD2m3aR6Ci/ioWwvrgzMCoz/vLvBEp0Frg== tarball: 'file:projects/ai-text-analytics.tgz' version: 0.0.0 'file:projects/app-configuration.tgz': @@ -8160,7 +8139,7 @@ packages: dev: false name: '@rush-temp/app-configuration' resolution: - integrity: sha512-oEvsSxFsumlUtpdWYLzhq20CKy9MmR34FYKbMQrhUBLHAloc+pznexh4u2/3OSdYcugDKgeicwkL35axbgGYKg== + integrity: sha512-zDI0h0tRBSFYpt6gYADkDF6OIIMgmxlFvtfQ3kg8/87lX14ci06bfDC7AFE7Sjx4qSgLmsWmJRjNSMJgdnMivg== tarball: 'file:projects/app-configuration.tgz' version: 0.0.0 'file:projects/core-amqp.tgz': @@ -8228,7 +8207,7 @@ packages: dev: false name: '@rush-temp/core-amqp' resolution: - integrity: sha512-MhzxdzNAk3nDK+vSqVlrFWn9WzAlnYZKgixZopFUeLbNXKtTIuknEm4sbDQ8n/1svgzMDWN0PlsWnFYBW0WnBg== + integrity: sha512-9Z/u0i3Cu8SPqpRIWOFwraYSyrhspg/wiDBYgVcwSOHK0hA4oyUA+Y/CgqWtLm+luuTLNNJgRjFveAcxQ4OjTA== tarball: 'file:projects/core-amqp.tgz' version: 0.0.0 'file:projects/core-arm.tgz': @@ -8262,7 +8241,7 @@ packages: dev: false name: '@rush-temp/core-arm' resolution: - integrity: sha512-gMo5M4yZopVded6wxND2JEGB6LyYP6FPbQYlPyhPFy36scETuxnOzg9d965CYEaLS/pa1Y8m73NvYPntfsFrAg== + integrity: sha512-0pn2mZyXmj//Y/nBrZacADv0y5cxhrtTmSDh7lJKBkO1mikLkWocQzfkXVQf2zDoZXRSqK5EDICnRx34Iij6og== tarball: 'file:projects/core-arm.tgz' version: 0.0.0 'file:projects/core-asynciterator-polyfill.tgz': @@ -8280,7 +8259,7 @@ packages: dev: false name: '@rush-temp/core-asynciterator-polyfill' resolution: - integrity: sha512-wcvU9xzocDcf6JqxBwlUIbDtU8XGBkq8n5TjQ4QYlRSFOUqjEX64a6XdMQr4dcga+OSoZw/QV/12HYPuUypK9w== + integrity: sha512-jDLggg/4sSiSb9xXQUsivEzh+w65cXOMPe/kPArXFs+LmAHaK1Et7soO3hxgmVW7AZ/5lVp8jcfW3hDXbKIFXQ== tarball: 'file:projects/core-asynciterator-polyfill.tgz' version: 0.0.0 'file:projects/core-auth.tgz': @@ -8321,7 +8300,7 @@ packages: dev: false name: '@rush-temp/core-auth' resolution: - integrity: sha512-SUk7DhjxjZhru6S3LTYJ7ZQjYaTKzrseBnzH632m9cRNiyYKN64ZQy7LlYBuvlFIFUL+6j3unoZlyEThr4SwfA== + integrity: sha512-s/939eY3zDHWsLuxyKMR6PfnRaA8fYeoDeAas83xmrRQwU5Nnj2YMfjWl8RwlUrLk4nJ2Hdi2nSZVp2UzCLyuw== tarball: 'file:projects/core-auth.tgz' version: 0.0.0 'file:projects/core-http.tgz': @@ -8398,7 +8377,7 @@ packages: dev: false name: '@rush-temp/core-http' resolution: - integrity: sha512-Kkoja/RR+gTqQ3X7gjfiPpewtxKfj+tWnUlV95zcjlMQxqzbQ/j6lcH29NHhv52FznxnUhqzUvxYY05cs1cfXQ== + integrity: sha512-Upl8IMRO2gVy5hXFCz3YK0u90oSG2JVuf9fZ8ReWtRYvx9vcAFMvpFMEO0xrZnT7WKzdaT0sBcSs7pe8neHHAQ== tarball: 'file:projects/core-http.tgz' version: 0.0.0 'file:projects/core-lro.tgz': @@ -8454,7 +8433,7 @@ packages: dev: false name: '@rush-temp/core-lro' resolution: - integrity: sha512-N+7SM1Yhnch618EhTBBoxQZRddrh+yqQhVuBJV0knDjtiC+nz+coerWGZ77T9tkTSgw4esZtZDn+MdTfQlKY0A== + integrity: sha512-HzwPk4vzJPaKNDjWArURsZuV7oYXPjVd4ccxHSwTEJ2sSctuSUb3IMXinsNOKjJCHvTYJM6lNkESCuWIyDOTQQ== tarball: 'file:projects/core-lro.tgz' version: 0.0.0 'file:projects/core-paging.tgz': @@ -8472,7 +8451,7 @@ packages: dev: false name: '@rush-temp/core-paging' resolution: - integrity: sha512-HtQeUV6/jtHxcEJSGOLfZj58FrapAsPl4Lirod7Yib/yXMrDIBYkkkI3Wwx5mGap+6ChPvmsBeskFIii1ZKcJg== + integrity: sha512-rRAaeqAsySfmVMMf46j6TljIPw2xVRZBVuyU9wrvQKJb1VzIEBZayG1jm9iTyyqUdFOEMn759//IfYP7KkhJNQ== tarball: 'file:projects/core-paging.tgz' version: 0.0.0 'file:projects/core-tracing.tgz': @@ -8513,7 +8492,7 @@ packages: dev: false name: '@rush-temp/core-tracing' resolution: - integrity: sha512-RWETP32JH6m1gxq4dQKAe572XiKX+bLAlU3/fUxPZPbscLNtphMy/E2DRzyvDCBEQfL+C49MxZIzEoy8ECdKgw== + integrity: sha512-SJ+L9sNBKGjTh1Ye4OWZ1aqXJ534jIKQwi5eDRa6irbh1jSZsNUmSMnBxzkM3+0kfQZ8YP7jm6sjPykaOJ4hUQ== tarball: 'file:projects/core-tracing.tgz' version: 0.0.0 'file:projects/cosmos.tgz': @@ -8575,7 +8554,7 @@ packages: dev: false name: '@rush-temp/cosmos' resolution: - integrity: sha512-DKhpoSSi/f/Aq6de+2s/IpX1C5FQbVfBdK063cXTE1SCamCwzYdf6/SLLbWeEVadUgz4wFgBTIy9Ta3Zz79qUQ== + integrity: sha512-GRoPrAKiHI521c+rxNT791bVFShNn6YefMT78uX5GqvTkxZa1jY3t5B2IdISXe0w1egUKwqImF2etEza6/pRZw== tarball: 'file:projects/cosmos.tgz' version: 0.0.0 'file:projects/event-hubs.tgz': @@ -8655,7 +8634,7 @@ packages: dev: false name: '@rush-temp/event-hubs' resolution: - integrity: sha512-ADxIBYXDACt52yTU4wn0dcR2pyKLNTlly7yIAD0e43929abQYDaznlMDTzGmjFtfPd3I3ndgc9LThNtse2Ks3A== + integrity: sha512-7Hy1SDsby9EVOhWljTSZ6Z0BWd+YQqtrH5lXeIMxTRxVMP/0IxN2a69X/kSYm2Ey5nJ2Xf6I+lGhNRbJt2xTCw== tarball: 'file:projects/event-hubs.tgz' version: 0.0.0 'file:projects/event-processor-host.tgz': @@ -8713,7 +8692,7 @@ packages: dev: false name: '@rush-temp/event-processor-host' resolution: - integrity: sha512-SXJ4EJcxMdnl7GQuy7f7YXS4FLEcmojM48uJKlVQpbdFRSPZczCm8NAA8GGXJmJjVdq+nB388bYk2H724/ZTrA== + integrity: sha512-UKQZiZyDo3uX1TvimdPeny6Yc0s0t9foQLx1sap3CMzASBIocWrMXwYmxHWn3n8sRlOmMtqXNyJIy/1zru3+9A== tarball: 'file:projects/event-processor-host.tgz' version: 0.0.0 'file:projects/eventhubs-checkpointstore-blob.tgz': @@ -8778,7 +8757,7 @@ packages: dev: false name: '@rush-temp/eventhubs-checkpointstore-blob' resolution: - integrity: sha512-gjOffb+0MIjYerROkRE9jsYsEhRK8srYiK+JJbf8Qm4rcmz1cHOnbzO9CecOJ/p0abxOUhWDddaf8v2vPoeftg== + integrity: sha512-lxxp1rmltAR87zw3K+swxDYnmXNHEOvxY7mW7cPSekQKfIIlzg/j83ZFluvO7481/HJR9JOabMcFS/VHxhPrgA== tarball: 'file:projects/eventhubs-checkpointstore-blob.tgz' version: 0.0.0 'file:projects/identity.tgz': @@ -8834,7 +8813,7 @@ packages: dev: false name: '@rush-temp/identity' resolution: - integrity: sha512-mBOEy+pEAVgeJK+b9LM88IdJEnqqOdrEOIMVdprLpYzAILVVQ2dRLsO+bC5d3TfNK7ZttHz/jRmiGmRDanqobA== + integrity: sha512-QOB2CcVr5P9knbZUzUVF3N1RpaJzjzwStfMspqmyDmpIdt4YOyXR5510/JuDBztGJE15Qk7m9dMUdnyVO7EoEg== tarball: 'file:projects/identity.tgz' version: 0.0.0 'file:projects/keyvault-certificates.tgz': @@ -8900,7 +8879,7 @@ packages: dev: false name: '@rush-temp/keyvault-certificates' resolution: - integrity: sha512-HWTB3OFSaGPknGpAlUsMwPtznCjrGmQvyi5nwOPFLOGNklQTZIChUu3xlv7u/mm9woH7GDPIHJgFEf1N9kmTmg== + integrity: sha512-rev0ttXaoWIXgv7V0j0bWSlpW6mzJGO8s/FjprXf13cFaHrGL+mIilvY21TQ/PsYtX4H+B4MHzBBWv2rdCr4bg== tarball: 'file:projects/keyvault-certificates.tgz' version: 0.0.0 'file:projects/keyvault-keys.tgz': @@ -8966,7 +8945,7 @@ packages: dev: false name: '@rush-temp/keyvault-keys' resolution: - integrity: sha512-hOvqlTGoEqwfvhUq7f/GzbLoWibGlncvQwNuVzkS1nm1/L4ECnJY+nePpj/uC4jZ5fAPiz4B6iFtiWN8RxBDRQ== + integrity: sha512-4b5tCgtBSD3JTbMZaxyCAId+4EiRrtCApPIzg3EEZJgc1jXtJoycQbE12D9y9IizuHtHwxOk7fA93o6b61xpsg== tarball: 'file:projects/keyvault-keys.tgz' version: 0.0.0 'file:projects/keyvault-secrets.tgz': @@ -9032,7 +9011,7 @@ packages: dev: false name: '@rush-temp/keyvault-secrets' resolution: - integrity: sha512-76XNhCuQ+WVwljPMLrTJhBuu3mD5uBZ/IJB3WaUMpe+CP0t3puLXXoTQXy07+3mKmUcDqISasbVb1wATZfylyg== + integrity: sha512-aJVju6YZCSpff4Pu6kT84sbKZirJbEblQNqUM0T3485sohXv7kLiiN2mms7mHr7NlYbXT/KUVmBj8ro5X7w0hw== tarball: 'file:projects/keyvault-secrets.tgz' version: 0.0.0 'file:projects/logger.tgz': @@ -9086,12 +9065,12 @@ packages: dev: false name: '@rush-temp/logger' resolution: - integrity: sha512-pEEw8s5yGhWD//xsHeJ68St44jvF7ByD6xgdI9MjUfmv86sdCdGb9Nx9SoPK9E3MS917ttPf36uqIfFwnfWs2Q== + integrity: sha512-GCfPJg0YTmoF//OugUXBNudk+xG5zmVM0BDuBPU4aDRqIXGMuLJU6B4bHcSKar+Pp765IaboHZs4RzZuLOH02g== tarball: 'file:projects/logger.tgz' version: 0.0.0 'file:projects/service-bus.tgz': dependencies: - '@azure/amqp-common': 1.0.0-preview.10 + '@azure/amqp-common': 1.0.0-preview.9 '@azure/eslint-plugin-azure-sdk': 2.0.1_303bc1d883bbfc108111733cb7ab69e3 '@azure/ms-rest-nodeauth': 0.9.3 '@microsoft/api-extractor': 7.7.8 @@ -9154,7 +9133,7 @@ packages: promise: 8.0.3 puppeteer: 2.1.1 rhea: 1.0.18 - rhea-promise: 0.1.15 + rhea-promise: 1.0.0 rimraf: 3.0.1 rollup: 1.31.0 rollup-plugin-shim: 1.0.0 @@ -9167,7 +9146,7 @@ packages: dev: false name: '@rush-temp/service-bus' resolution: - integrity: sha512-GoJsi+/mi4U/jHoL0CEadcHpttm7DzEmnJhZApIEYBA1UqIN8CMZchDwMFSPA0y4ma2oEfZJWCDBPwOU0PRz9w== + integrity: sha512-a+61RsOAF8Y6oWHo65+Sr1RHj8g3rdlqFIxT8k/aUid99zNhyfXj+d3B/H8AlVPqghP4oVkW4d+Y4ss6WlUYJA== tarball: 'file:projects/service-bus.tgz' version: 0.0.0 'file:projects/storage-blob.tgz': @@ -9228,7 +9207,7 @@ packages: dev: false name: '@rush-temp/storage-blob' resolution: - integrity: sha512-C4qCp2+U6+uWu3X5SKvXYGCYmX5UIuH/TjsQBqBwCr4bkNUxvs90E3QLzh8CS35JcTPt7kLtcg4cZml41IWg7g== + integrity: sha512-lEP6M8gBMa0lo09vTP23CkzHXpID+MFTP9CABeoCVbl+GTUcagIfPpgwQnYyUkICzkXz7+nK9V8AWoLfaTn0TA== tarball: 'file:projects/storage-blob.tgz' version: 0.0.0 'file:projects/storage-file-datalake.tgz': @@ -9297,7 +9276,7 @@ packages: dev: false name: '@rush-temp/storage-file-datalake' resolution: - integrity: sha512-q7y9BkD1DaI1D+4ki8/8Qjsd3T3wikezl5jQnNb6yaBJPPgQqkPX+d9d7QzXfhEzcimJWZ1X4IplyZUu3MxJ9g== + integrity: sha512-f/jaSqr2gkQ6Dlz//6fPvFbRxwRCbIkiq3pL1xkTvFF3c5y1pcF3lG1R48ZhnsSwpKuWDl0vfPEiM/4eWttbHQ== tarball: 'file:projects/storage-file-datalake.tgz' version: 0.0.0 'file:projects/storage-file-share.tgz': @@ -9358,7 +9337,7 @@ packages: dev: false name: '@rush-temp/storage-file-share' resolution: - integrity: sha512-x9NFeJIsOWCLb0xAEYcH0SykV8YgLEhEwObxq49k7iej28Q75OarDUfAhW2eIOx0vt1EfhOYj0PBTiOtO4z6OA== + integrity: sha512-DJy4BcoAO/SElZYfGfL5Kdvt6A/Z0QkJ6pxZ7J0WyDFsjXEYroWnjLnNTU8T8akAMYWEVrm5j1b6eCueGUxing== tarball: 'file:projects/storage-file-share.tgz' version: 0.0.0 'file:projects/storage-queue.tgz': @@ -9418,7 +9397,7 @@ packages: dev: false name: '@rush-temp/storage-queue' resolution: - integrity: sha512-Y//E3m5VZRYZm6FlwOAcisq4hJi7z0MTqVh9ofhdg7Hc45qr31DBd8Ci8dn03poqaS3dSIGOTBObpYyfGB9Qgw== + integrity: sha512-c2VKjOl+42FNBg0R1HVYtsfuiHWPANnRTzigDkBVYG9U6QIFAVE2/mWfQLdAQE/fEOjKL5swQSVeEwRLjXXHmQ== tarball: 'file:projects/storage-queue.tgz' version: 0.0.0 'file:projects/template.tgz': @@ -9469,7 +9448,7 @@ packages: dev: false name: '@rush-temp/template' resolution: - integrity: sha512-Vw/0dXj2DcQ1NX0U+d/B2W7slh9HuoExmSU5EL0/BJClWsgIjJykyQ+wmwXafNF5lV/ltMPy7Rv+XbLft7K/tw== + integrity: sha512-eRzyhbFcnQZQgh8mnwyLFrZoP/wGTFoneLug+5s2AVEENNmr6+PQjEJVTg+dTlgfWG5gJP3meWTgHke3jcRt0A== tarball: 'file:projects/template.tgz' version: 0.0.0 'file:projects/test-utils-recorder.tgz': @@ -9524,7 +9503,7 @@ packages: dev: false name: '@rush-temp/test-utils-recorder' resolution: - integrity: sha512-BDMvFHxK4sXDE9cDKdYu+dNxmkpseGf/iGu+r6c4X0YBKYJ/eH9tKbOhXPi9sXjFgQeUkbPc0vRGsj+HS+/gsQ== + integrity: sha512-e8WwVJqQFHP560TcUW/m9GxzGq7LPpfLb++v/zC0vfjK+6aA7QRWTApUzlr+tyKqUG/bhEaNGMC+7KVOJyN2XQ== tarball: 'file:projects/test-utils-recorder.tgz' version: 0.0.0 'file:projects/testhub.tgz': @@ -9545,7 +9524,7 @@ packages: dev: false name: '@rush-temp/testhub' resolution: - integrity: sha512-dW7m2LfMTGWZVxeZCvuHSzjBQBmz1868xK4zIx5AQifXDsBDrrQ3wdPHnarQV4yI0wcyzcI0QnVzRJ42++O4Hg== + integrity: sha512-guDU8PdEdKCVnGxNd1JEkmqukDoc1wodkEqQCWpY1+bX4ZT+ZY520gfVcMeMHYCEO8TAAhScGNke/y7p9qBArA== tarball: 'file:projects/testhub.tgz' version: 0.0.0 registry: '' diff --git a/sdk/servicebus/service-bus/README.md b/sdk/servicebus/service-bus/README.md index d678f47f8cd3..83fc52f04837 100644 --- a/sdk/servicebus/service-bus/README.md +++ b/sdk/servicebus/service-bus/README.md @@ -211,13 +211,13 @@ export DEBUG=azure*,rhea* - If you are **not interested in viewing the message transformation** (which consumes lot of console/disk space) then you can set the `DEBUG` environment variable as follows: ```bash -export DEBUG=azure*,rhea*,-rhea:raw,-rhea:message,-azure:amqp-common:datatransformer +export DEBUG=azure*,rhea*,-rhea:raw,-rhea:message,-azure:core-amqp:datatransformer ``` - If you are interested only in **errors**, then you can set the `DEBUG` environment variable as follows: ```bash -export DEBUG=azure:service-bus:error,azure-amqp-common:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow +export DEBUG=azure:service-bus:error,azure-core-amqp:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow ``` ### Logging to a file diff --git a/sdk/servicebus/service-bus/karma.conf.js b/sdk/servicebus/service-bus/karma.conf.js index 69c0de01ce12..fca58d64e696 100644 --- a/sdk/servicebus/service-bus/karma.conf.js +++ b/sdk/servicebus/service-bus/karma.conf.js @@ -49,9 +49,9 @@ module.exports = function(config) { // https://www.npmjs.com/package/karma-env-preprocessor envPreprocessor: [ "SERVICEBUS_CONNECTION_STRING", - "AAD_CLIENT_ID", - "AAD_CLIENT_SECRET", - "AAD_TENANT_ID" + "AZURE_CLIENT_ID", + "AZURE_CLIENT_SECRET", + "AZURE_TENANT_ID" ], // test results reporter to use diff --git a/sdk/servicebus/service-bus/package.json b/sdk/servicebus/service-bus/package.json index 81170af1f69d..fa2e339f193e 100644 --- a/sdk/servicebus/service-bus/package.json +++ b/sdk/servicebus/service-bus/package.json @@ -2,7 +2,7 @@ "name": "@azure/service-bus", "sdk-type": "client", "author": "Microsoft Corporation", - "version": "1.1.3", + "version": "2.0.0-preview.1", "license": "MIT", "description": "Azure Service Bus SDK for Node.js", "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/servicebus/service-bus", @@ -20,7 +20,6 @@ "module": "dist-esm/src/index.js", "browser": { "./dist/index.js": "./browser/service-bus.js", - "./dist-esm/test/utils/aadUtils.js": "./dist-esm/test/utils/aadUtils.browser.js", "./dist-esm/src/util/crypto.js": "./dist-esm/src/util/crypto.browser.js", "./dist-esm/src/util/parseUrl.js": "./dist-esm/src/util/parseUrl.browser.js", "buffer": "buffer", @@ -78,9 +77,8 @@ ] }, "dependencies": { - "@azure/amqp-common": "1.0.0-preview.10", + "@azure/core-amqp": "^1.0.1", "@azure/core-http": "^1.0.0", - "@azure/ms-rest-nodeauth": "^0.9.2", "@opentelemetry/types": "^0.2.0", "@types/is-buffer": "^2.0.0", "@types/long": "^4.0.0", @@ -89,12 +87,12 @@ "is-buffer": "^2.0.3", "long": "^4.0.0", "process": "^0.11.10", - "rhea": "^1.0.18", - "rhea-promise": "^0.1.15", - "tslib": "^1.10.0" + "tslib": "^1.10.0", + "rhea-promise": "^1.0.0" }, "devDependencies": { "@azure/eslint-plugin-azure-sdk": "^2.0.1", + "@azure/identity": "^1.0.0", "@microsoft/api-extractor": "^7.5.4", "@rollup/plugin-commonjs": "^11.0.1", "@rollup/plugin-inject": "^4.0.0", diff --git a/sdk/servicebus/service-bus/review/service-bus.api.md b/sdk/servicebus/service-bus/review/service-bus.api.md index 8c16f2a87610..b8ced41b2b83 100644 --- a/sdk/servicebus/service-bus/review/service-bus.api.md +++ b/sdk/servicebus/service-bus/review/service-bus.api.md @@ -4,21 +4,17 @@ ```ts -import { AmqpMessage } from '@azure/amqp-common'; -import { ApplicationTokenCredentials } from '@azure/ms-rest-nodeauth'; -import { DataTransformer } from '@azure/amqp-common'; -import { DefaultDataTransformer } from '@azure/amqp-common'; -import { delay } from '@azure/amqp-common'; +import { AmqpMessage } from '@azure/core-amqp'; +import { DataTransformer } from '@azure/core-amqp'; +import { DefaultDataTransformer } from '@azure/core-amqp'; +import { delay } from '@azure/core-amqp'; import { Delivery } from 'rhea-promise'; -import { DeviceTokenCredentials } from '@azure/ms-rest-nodeauth'; import { HttpOperationResponse } from '@azure/core-http'; import Long from 'long'; -import { MessagingError } from '@azure/amqp-common'; -import { MSITokenCredentials } from '@azure/ms-rest-nodeauth'; -import { TokenInfo } from '@azure/amqp-common'; -import { TokenProvider } from '@azure/amqp-common'; -import { TokenType } from '@azure/amqp-common'; -import { UserTokenCredentials } from '@azure/ms-rest-nodeauth'; +import { MessagingError } from '@azure/core-amqp'; +import { RetryOptions } from '@azure/core-amqp'; +import { TokenCredential } from '@azure/core-amqp'; +import { TokenType } from '@azure/core-amqp'; import { WebSocketImpl } from 'rhea-promise'; // @public @@ -192,6 +188,8 @@ export class Receiver { renewMessageLock(lockTokenOrMessage: string | ServiceBusMessage): Promise; } +export { RetryOptions } + // @public export interface RuleDescription { action?: string; @@ -249,10 +247,9 @@ export class Sender { // @public export class ServiceBusClient { + constructor(connectionString: string, options?: ServiceBusClientOptions); + constructor(host: string, credential: TokenCredential, options?: ServiceBusClientOptions); close(): Promise; - static createFromAadTokenCredentials(host: string, credentials: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials, options?: ServiceBusClientOptions): ServiceBusClient; - static createFromConnectionString(connectionString: string, options?: ServiceBusClientOptions): ServiceBusClient; - static createFromTokenProvider(host: string, tokenProvider: TokenProvider, options?: ServiceBusClientOptions): ServiceBusClient; createQueueClient(queueName: string): QueueClient; createSubscriptionClient(topicName: string, subscriptionName: string): SubscriptionClient; createTopicClient(topicName: string): TopicClient; @@ -419,9 +416,7 @@ export interface SubscriptionOptions { userMetadata?: string; } -export { TokenInfo } - -export { TokenProvider } +export { TokenCredential } export { TokenType } diff --git a/sdk/servicebus/service-bus/src/clientEntityContext.ts b/sdk/servicebus/service-bus/src/clientEntityContext.ts index ab2b33815e5b..57d2fb93d8fb 100644 --- a/sdk/servicebus/service-bus/src/clientEntityContext.ts +++ b/sdk/servicebus/service-bus/src/clientEntityContext.ts @@ -13,11 +13,12 @@ import { ConcurrentExpiringMap } from "./util/concurrentExpiringMap"; import { MessageReceiver } from "./core/messageReceiver"; import { MessageSession } from "./session/messageSession"; import { SessionManager } from "./session/sessionManager"; +import { MessagingError } from "@azure/core-amqp"; /** * @interface ClientEntityContext * Provides contextual information like the underlying amqp connection, cbs session, - * management session, tokenProvider, senders, receivers, etc. about the ServiceBus client. + * management session, tokenCredential, senders, receivers, etc. about the ServiceBus client. * @internal */ export interface ClientEntityContextBase { @@ -148,10 +149,11 @@ export namespace ClientEntityContext { (entityContext as ClientEntityContext).getReceiver = (name: string, sessionId?: string) => { if (sessionId != undefined && entityContext.expiredMessageSessions[sessionId]) { - const error = new Error( + const error = new MessagingError( `The session lock has expired on the session with id ${sessionId}.` ); - error.name = "SessionLockLostError"; + error.code = "SessionLockLostError"; + error.retryable = false; log.error( "[%s] Failed to find receiver '%s' as the session with id '%s' is expired", entityContext.namespace.connectionId, diff --git a/sdk/servicebus/service-bus/src/connectionContext.ts b/sdk/servicebus/service-bus/src/connectionContext.ts index 5a572e641371..d50845d01477 100644 --- a/sdk/servicebus/service-bus/src/connectionContext.ts +++ b/sdk/servicebus/service-bus/src/connectionContext.ts @@ -11,8 +11,9 @@ import { CreateConnectionContextBaseParameters, Dictionary, delay, - TokenProvider -} from "@azure/amqp-common"; + TokenCredential, + SharedKeyCredential +} from "@azure/core-amqp"; import { ServiceBusClientOptions } from "./serviceBusClient"; import { ClientEntityContext } from "./clientEntityContext"; import { OnAmqpEvent, EventContext, ConnectionEvents } from "rhea-promise"; @@ -21,7 +22,7 @@ import { OnAmqpEvent, EventContext, ConnectionEvents } from "rhea-promise"; * @internal * @interface ConnectionContext * Provides contextual information like the underlying amqp connection, cbs session, management session, - * tokenProvider, senders, receivers, etc. about the ServiceBus client. + * tokenCredential, senders, receivers, etc. about the ServiceBus client. */ export interface ConnectionContext extends ConnectionContextBase { /** @@ -45,13 +46,13 @@ export namespace ConnectionContext { export function create( config: ConnectionConfig, - tokenProvider: TokenProvider, + tokenCredential: SharedKeyCredential | TokenCredential, options?: ServiceBusClientOptions ): ConnectionContext { if (!options) options = {}; const parameters: CreateConnectionContextBaseParameters = { config: config, - tokenProvider: tokenProvider, + tokenCredential: tokenCredential, dataTransformer: options.dataTransformer, isEntityPathRequired: false, connectionProperties: { diff --git a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts index 71a0d9569bbb..de57886b56f0 100644 --- a/sdk/servicebus/service-bus/src/core/batchingReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/batchingReceiver.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import * as log from "../log"; -import { Constants, translate, MessagingError } from "@azure/amqp-common"; +import { Constants, translate, MessagingError } from "@azure/core-amqp"; import { ReceiverEvents, EventContext, OnAmqpEvent, SessionEvents, AmqpError } from "rhea-promise"; import { ServiceBusMessage, ReceiveMode } from "../serviceBusMessage"; import { @@ -77,7 +77,7 @@ export class BatchingReceiver extends MessageReceiver { throwErrorIfConnectionClosed(this._context.namespace); if (maxWaitTimeInSeconds == null) { - maxWaitTimeInSeconds = Constants.defaultOperationTimeoutInSeconds; + maxWaitTimeInSeconds = Constants.defaultOperationTimeoutInMs / 1000; } const brokeredMessages: ServiceBusMessage[] = []; @@ -95,7 +95,7 @@ export class BatchingReceiver extends MessageReceiver { receiver.session.removeListener(SessionEvents.sessionError, onSessionError); const sessionError = context.session && context.session.error; - let error = new MessagingError("An error occurred while receiving messages."); + let error: Error | MessagingError; if (sessionError) { error = translate(sessionError); log.error( @@ -104,6 +104,8 @@ export class BatchingReceiver extends MessageReceiver { this.name, error ); + } else { + error = new MessagingError("An error occurred while receiving messages."); } if (totalWaitTimer) { clearTimeout(totalWaitTimer); @@ -276,7 +278,7 @@ export class BatchingReceiver extends MessageReceiver { receiver.session.removeListener(SessionEvents.sessionError, onSessionError); const receiverError = context.receiver && context.receiver.error; - let error = new MessagingError("An error occurred while receiving messages."); + let error: Error | MessagingError; if (receiverError) { error = translate(receiverError); log.error( @@ -285,6 +287,8 @@ export class BatchingReceiver extends MessageReceiver { this.name, error ); + } else { + error = new MessagingError("An error occurred while receiving messages."); } if (totalWaitTimer) { clearTimeout(totalWaitTimer); diff --git a/sdk/servicebus/service-bus/src/core/linkEntity.ts b/sdk/servicebus/service-bus/src/core/linkEntity.ts index 26e957a40905..8a40f54b5992 100644 --- a/sdk/servicebus/service-bus/src/core/linkEntity.ts +++ b/sdk/servicebus/service-bus/src/core/linkEntity.ts @@ -1,7 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -import { defaultLock } from "@azure/amqp-common"; +import { + defaultLock, + TokenType, + AccessToken, + Constants, + SharedKeyCredential +} from "@azure/core-amqp"; import { ClientEntityContext } from "../clientEntityContext"; import * as log from "../log"; import { Sender, Receiver } from "rhea-promise"; @@ -81,6 +87,11 @@ export class LinkEntity { * @protected */ protected _tokenRenewalTimer?: NodeJS.Timer; + /** + * @property _tokenTimeout Indicates token timeout + * @protected + */ + protected _tokenTimeout?: number; /** * Creates a new ClientEntity instance. * @constructor @@ -118,7 +129,24 @@ export class LinkEntity { await defaultLock.acquire(this._context.namespace.cbsSession.cbsLock, () => { return this._context.namespace.cbsSession.init(); }); - const tokenObject = await this._context.namespace.tokenProvider.getToken(this.audience); + let tokenObject: AccessToken; + let tokenType: TokenType; + if (this._context.namespace.tokenCredential instanceof SharedKeyCredential) { + tokenObject = this._context.namespace.tokenCredential.getToken(this.audience); + tokenType = TokenType.CbsTokenTypeSas; + // renew sas token in every 45 minutess + this._tokenTimeout = (3600 - 900) * 1000; + } else { + const aadToken = await this._context.namespace.tokenCredential.getToken( + Constants.aadServiceBusScope + ); + if (!aadToken) { + throw new Error(`Failed to get token from the provided "TokenCredential" object`); + } + tokenObject = aadToken; + tokenType = TokenType.CbsTokenTypeJwt; + this._tokenTimeout = tokenObject.expiresOnTimestamp - Date.now() - 2 * 60 * 1000; + } log.link( "[%s] %s: calling negotiateClaim for audience '%s'.", this._context.namespace.connectionId, @@ -134,8 +162,15 @@ export class LinkEntity { this.name, this.address ); + if (!tokenObject) { + throw new Error("Token cannot be null"); + } await defaultLock.acquire(this._context.namespace.negotiateClaimLock, () => { - return this._context.namespace.cbsSession.negotiateClaim(this.audience, tokenObject); + return this._context.namespace.cbsSession.negotiateClaim( + this.audience, + tokenObject, + tokenType + ); }); log.link( "[%s] Negotiated claim for %s '%s' with with address: %s", @@ -155,15 +190,13 @@ export class LinkEntity { * @returns {void} */ protected async _ensureTokenRenewal(): Promise { - const tokenValidTimeInSeconds = this._context.namespace.tokenProvider.tokenValidTimeInSeconds; - const tokenRenewalMarginInSeconds = this._context.namespace.tokenProvider - .tokenRenewalMarginInSeconds; - const nextRenewalTimeout = (tokenValidTimeInSeconds - tokenRenewalMarginInSeconds) * 1000; + if (!this._tokenTimeout) { + return; + } this._tokenRenewalTimer = setTimeout(async () => { try { await this._negotiateClaim(true); } catch (err) { - // TODO: May be add some retries over here before emitting the error. log.error( "[%s] %s '%s' with address %s, an error occurred while renewing the token: %O", this._context.namespace.connectionId, @@ -173,15 +206,15 @@ export class LinkEntity { err ); } - }, nextRenewalTimeout); + }, this._tokenTimeout); log.link( "[%s] %s '%s' with address %s, has next token renewal in %d seconds @(%s).", this._context.namespace.connectionId, this._type, this.name, this.address, - nextRenewalTimeout / 1000, - new Date(Date.now() + nextRenewalTimeout).toString() + this._tokenTimeout / 1000, + new Date(Date.now() + this._tokenTimeout).toString() ); } diff --git a/sdk/servicebus/service-bus/src/core/managementClient.ts b/sdk/servicebus/service-bus/src/core/managementClient.ts index a583608b884b..8ff3b3e6c551 100644 --- a/sdk/servicebus/service-bus/src/core/managementClient.ts +++ b/sdk/servicebus/service-bus/src/core/managementClient.ts @@ -20,8 +20,9 @@ import { RequestResponseLink, ConditionErrorNameMapper, AmqpMessage, - SendRequestOptions -} from "@azure/amqp-common"; + SendRequestOptions, + MessagingError +} from "@azure/core-amqp"; import { ClientEntityContext } from "../clientEntityContext"; import { ReceivedMessageInfo, @@ -240,12 +241,12 @@ export class ManagementClient extends LinkEntity { sropt, rxopt ); - this._mgmtReqResLink.sender.on(SenderEvents.senderError, (context: EventContext) => { + this._mgmtReqResLink!.sender.on(SenderEvents.senderError, (context: EventContext) => { const id = context.connection.options.id; const ehError = translate(context.sender!.error!); log.error("[%s] An error occurred on the $management sender link.. %O", id, ehError); }); - this._mgmtReqResLink.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => { + this._mgmtReqResLink!.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => { const id = context.connection.options.id; const ehError = translate(context.receiver!.error!); log.error("[%s] An error occurred on the $management receiver link.. %O", id, ehError); @@ -253,8 +254,8 @@ export class ManagementClient extends LinkEntity { log.mgmt( "[%s] Created sender '%s' and receiver '%s' links for $management endpoint.", this._context.namespace.connectionId, - this._mgmtReqResLink.sender.name, - this._mgmtReqResLink.receiver.name + this._mgmtReqResLink!.sender.name, + this._mgmtReqResLink!.receiver.name ); await this._ensureTokenRenewal(); } @@ -446,14 +447,14 @@ export class ManagementClient extends LinkEntity { } } } catch (err) { - const error = translate(err); + const error = translate(err) as MessagingError; log.error( "An error occurred while sending the request to peek messages to " + "$management endpoint: %O", error ); // statusCode == 404 then do not throw - if (error.name !== ConditionErrorNameMapper["com.microsoft:message-not-found"]) { + if (error.code !== ConditionErrorNameMapper["com.microsoft:message-not-found"]) { throw error; } } @@ -477,9 +478,7 @@ export class ManagementClient extends LinkEntity { async renewLock(lockToken: string, options?: SendRequestOptions): Promise { throwErrorIfConnectionClosed(this._context.namespace); if (!options) options = {}; - if (options.delayInSeconds == null) options.delayInSeconds = 1; - if (options.timeoutInSeconds == null) options.timeoutInSeconds = 5; - if (options.times == null) options.times = 5; + if (options.timeoutInMs == null) options.timeoutInMs = 5000; try { const messageBody: any = {}; @@ -881,9 +880,7 @@ export class ManagementClient extends LinkEntity { async renewSessionLock(sessionId: string, options?: SendRequestOptions): Promise { throwErrorIfConnectionClosed(this._context.namespace); if (!options) options = {}; - if (options.delayInSeconds == null) options.delayInSeconds = 1; - if (options.timeoutInSeconds == null) options.timeoutInSeconds = 5; - if (options.times == null) options.times = 5; + if (options.timeoutInMs == null) options.timeoutInMs = 5000; try { const messageBody: any = {}; messageBody[Constants.sessionIdMapKey] = sessionId; diff --git a/sdk/servicebus/service-bus/src/core/messageReceiver.ts b/sdk/servicebus/service-bus/src/core/messageReceiver.ts index 43268836ebf6..fd9d84f63756 100644 --- a/sdk/servicebus/service-bus/src/core/messageReceiver.ts +++ b/sdk/servicebus/service-bus/src/core/messageReceiver.ts @@ -10,7 +10,7 @@ import { RetryConfig, ConditionErrorNameMapper, ErrorNameConditionMapper -} from "@azure/amqp-common"; +} from "@azure/core-amqp"; import { Receiver, OnAmqpEvent, @@ -474,11 +474,11 @@ export class MessageReceiver extends LinkEntity { // Do not want renewLock to happen unnecessarily, while abandoning the message. Hence, // doing this here. Otherwise, this should be done in finally. this._clearMessageLockRenewTimer(bMessage.messageId as string); - const error = translate(err); + const error = translate(err) as MessagingError; // Nothing much to do if user's message handler throws. Let us try abandoning the message. if ( !bMessage.delivery.remote_settled && - error.name !== ConditionErrorNameMapper["com.microsoft:message-lock-lost"] && + error.code !== ConditionErrorNameMapper["com.microsoft:message-lock-lost"] && this.receiveMode === ReceiveMode.peekLock && this.isOpen() // only try to abandon the messages if the connection is still open ) { @@ -547,7 +547,7 @@ export class MessageReceiver extends LinkEntity { const receiver = this._receiver || context.receiver!; const receiverError = context.receiver && context.receiver.error; if (receiverError) { - const sbError = translate(receiverError); + const sbError = translate(receiverError) as MessagingError; log.error( "[%s] An error occurred for Receiver '%s': %O.", connectionId, @@ -587,7 +587,7 @@ export class MessageReceiver extends LinkEntity { const receiver = this._receiver || context.receiver!; const sessionError = context.session && context.session.error; if (sessionError) { - const sbError = translate(sessionError); + const sbError = translate(sessionError) as MessagingError; log.error( "[%s] An error occurred on the session for Receiver '%s': %O.", connectionId, @@ -875,7 +875,7 @@ export class MessageReceiver extends LinkEntity { // We should attempt to reopen only when the receiver(sdk) did not initiate the close let shouldReopen = false; if (receiverError && !wasCloseInitiated) { - const translatedError = translate(receiverError); + const translatedError = translate(receiverError) as MessagingError; if (translatedError.retryable) { shouldReopen = true; log.error( @@ -948,9 +948,11 @@ export class MessageReceiver extends LinkEntity { }), connectionId: connectionId, operationType: RetryOperationType.receiverLink, - times: Constants.defaultConnectionRetryAttempts, - connectionHost: this._context.namespace.config.host, - delayInSeconds: 15 + retryOptions: { + maxRetries: Constants.defaultMaxRetriesForConnection, + retryDelayInMs: 15000 + }, + connectionHost: this._context.namespace.config.host }; if (!this.wasCloseInitiated) { await retry(config); @@ -1031,7 +1033,7 @@ export class MessageReceiver extends LinkEntity { "Hence rejecting the promise with timeout error.", this._context.namespace.connectionId, delivery.id, - Constants.defaultOperationTimeoutInSeconds * 1000 + Constants.defaultOperationTimeoutInMs ); const e: AmqpError = { @@ -1041,7 +1043,7 @@ export class MessageReceiver extends LinkEntity { "message may or may not be successful" }; return reject(translate(e)); - }, Constants.defaultOperationTimeoutInSeconds * 1000); + }, Constants.defaultOperationTimeoutInMs); this._deliveryDispositionMap.set(delivery.id, { resolve: resolve, reject: reject, diff --git a/sdk/servicebus/service-bus/src/core/messageSender.ts b/sdk/servicebus/service-bus/src/core/messageSender.ts index 57b428288f21..1c18ee964681 100644 --- a/sdk/servicebus/service-bus/src/core/messageSender.ts +++ b/sdk/servicebus/service-bus/src/core/messageSender.ts @@ -23,9 +23,9 @@ import { RetryConfig, RetryOperationType, Constants, - randomNumberFromInterval, - delay -} from "@azure/amqp-common"; + delay, + MessagingError +} from "@azure/core-amqp"; import { SendableMessageInfo, toAmqpMessage, @@ -374,10 +374,7 @@ export class MessageSender extends LinkEntity { this._sender!.on(SenderEvents.rejected, onRejected); this._sender!.on(SenderEvents.modified, onModified); this._sender!.on(SenderEvents.released, onReleased); - waitTimer = setTimeout( - actionAfterTimeout, - Constants.defaultOperationTimeoutInSeconds * 1000 - ); + waitTimer = setTimeout(actionAfterTimeout, Constants.defaultOperationTimeoutInMs); try { const delivery = this._sender!.send( encodedMessage, @@ -408,13 +405,14 @@ export class MessageSender extends LinkEntity { } }); - const jitterInSeconds = randomNumberFromInterval(1, 4); const config: RetryConfig = { operation: sendEventPromise, connectionId: this._context.namespace.connectionId!, operationType: RetryOperationType.sendMessage, - times: Constants.defaultRetryAttempts, - delayInSeconds: Constants.defaultDelayBetweenOperationRetriesInSeconds + jitterInSeconds + retryOptions: { + maxRetries: Constants.defaultMaxRetries, + retryDelayInMs: Constants.defaultDelayBetweenOperationRetriesInMs + } }; return retry(config); @@ -499,7 +497,7 @@ export class MessageSender extends LinkEntity { // We should attempt to reopen only when the sender(sdk) did not initiate the close let shouldReopen = false; if (senderError && !wasCloseInitiated) { - const translatedError = translate(senderError); + const translatedError = translate(senderError) as MessagingError; if (translatedError.retryable) { shouldReopen = true; log.error( @@ -555,9 +553,11 @@ export class MessageSender extends LinkEntity { operation: () => this._init(options), connectionId: this._context.namespace.connectionId!, operationType: RetryOperationType.senderLink, - times: Constants.defaultConnectionRetryAttempts, - connectionHost: this._context.namespace.config.host, - delayInSeconds: 15 + retryOptions: { + maxRetries: Constants.defaultMaxRetriesForConnection, + retryDelayInMs: 15000 + }, + connectionHost: this._context.namespace.config.host }; return retry(config); }); diff --git a/sdk/servicebus/service-bus/src/index.ts b/sdk/servicebus/service-bus/src/index.ts index 38f261e98982..623de70f31e4 100644 --- a/sdk/servicebus/service-bus/src/index.ts +++ b/sdk/servicebus/service-bus/src/index.ts @@ -6,14 +6,14 @@ export { ServiceBusClient, ServiceBusClientOptions } from "./serviceBusClient"; export { - TokenInfo, TokenType, - TokenProvider, DefaultDataTransformer, + TokenCredential, DataTransformer, delay, - MessagingError -} from "@azure/amqp-common"; + MessagingError, + RetryOptions +} from "@azure/core-amqp"; export { QueueClient } from "./queueClient"; export { TopicClient } from "./topicClient"; diff --git a/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts b/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts index 6607e256458c..d098e616b425 100644 --- a/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts +++ b/sdk/servicebus/service-bus/src/serviceBusAtomManagementClient.ts @@ -16,7 +16,7 @@ import { RestError } from "@azure/core-http"; -import { SasTokenProvider, parseConnectionString } from "@azure/amqp-common"; +import { parseConnectionString, SharedKeyCredential } from "@azure/core-amqp"; import { AtomXmlSerializer, executeAtomXmlOperation } from "./util/atomXmlHelper"; @@ -350,7 +350,7 @@ export class ServiceBusAtomManagementClient extends ServiceClient { /** * SAS token provider used to generate tokens as required for the various operations. */ - private sasTokenProvider: SasTokenProvider; + private sasTokenProvider: SharedKeyCredential; /** * Initializes a new instance of the ServiceBusManagementClient class. @@ -387,8 +387,7 @@ export class ServiceBusAtomManagementClient extends ServiceClient { this.endpoint = (connectionString.match("Endpoint=sb://(.*)/;") || "")[1]; this.endpointWithProtocol = connectionStringObj.Endpoint; - this.sasTokenProvider = new SasTokenProvider( - connectionStringObj.Endpoint, + this.sasTokenProvider = new SharedKeyCredential( connectionStringObj.SharedAccessKeyName, connectionStringObj.SharedAccessKey ); diff --git a/sdk/servicebus/service-bus/src/serviceBusClient.ts b/sdk/servicebus/service-bus/src/serviceBusClient.ts index 126daf43d001..cb43d24ea26d 100644 --- a/sdk/servicebus/service-bus/src/serviceBusClient.ts +++ b/sdk/servicebus/service-bus/src/serviceBusClient.ts @@ -3,13 +3,6 @@ import * as log from "./log"; -import { - ApplicationTokenCredentials, - DeviceTokenCredentials, - UserTokenCredentials, - MSITokenCredentials -} from "@azure/ms-rest-nodeauth"; - import { WebSocketImpl } from "rhea-promise"; import { ConnectionContext } from "./connectionContext"; import { QueueClient } from "./queueClient"; @@ -17,12 +10,11 @@ import { TopicClient } from "./topicClient"; import { ConnectionConfig, DataTransformer, - TokenProvider, - AadTokenProvider, - SasTokenProvider -} from "@azure/amqp-common"; + TokenCredential, + SharedKeyCredential, + isTokenCredential +} from "@azure/core-amqp"; import { SubscriptionClient } from "./subscriptionClient"; -import { isNode } from "./util/utils"; /** * Describes the options that can be provided while creating the ServiceBusClient. @@ -65,25 +57,68 @@ export class ServiceBusClient { */ private _context: ConnectionContext; + /** + * Creates a ServiceBusClient for the Service Bus Namespace represented in the given connection + * string. + * @param connectionString - Connection string of the form + * 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' + * @param options Options to control ways to interact with the + * Service Bus Namespace. + * @returns ServiceBusClient + */ + constructor(connectionString: string, options?: ServiceBusClientOptions); + /** * Instantiates a ServiceBusClient to interact with a Service Bus Namespace. * * @constructor - * @param {ConnectionConfig} config - The connection configuration needed to connect to the - * Service Bus Namespace. - * @param {TokenProvider} [tokenProvider] - The token provider that provides the token for - * authentication. - * @param {ServiceBusClientOptions} - Options to control ways to interact with the Service Bus + * @param host - The host name for the Service Bus namespace. This is likely to be similar to + * .servicebus.windows.net + * @param credential - credential that implements the TokenCredential interface. + * @param options - Options to control ways to interact with the Service Bus * Namespace. */ - private constructor( - config: ConnectionConfig, - tokenProvider: TokenProvider, + constructor(host: string, credential: TokenCredential, options?: ServiceBusClientOptions); + + constructor( + hostOrConnectionString: string, + credentialOrServiceBusClientOptions?: TokenCredential | ServiceBusClientOptions, options?: ServiceBusClientOptions ) { - if (!options) options = {}; + let config; + let credential; + + if (!isTokenCredential(credentialOrServiceBusClientOptions)) { + // connectionString and options based constructor was invoked + config = ConnectionConfig.create(hostOrConnectionString); + + options = credentialOrServiceBusClientOptions as ServiceBusClientOptions; + config.webSocket = options && options.webSocket; + config.webSocketEndpointPath = "$servicebus/websocket"; + config.webSocketConstructorOptions = options && options.webSocketConstructorOptions; + + // Since connectionstring was passed, create a SharedKeyCredential + credential = new SharedKeyCredential(config.sharedAccessKeyName, config.sharedAccessKey); + + ConnectionConfig.validate(config); + } else { + // host, credential and options based constructor was invoked + credential = credentialOrServiceBusClientOptions as TokenCredential; + + hostOrConnectionString = String(hostOrConnectionString); + if (!hostOrConnectionString.endsWith("/")) { + hostOrConnectionString += "/"; + } + const connectionString = `Endpoint=sb://${hostOrConnectionString};SharedAccessKeyName=defaultKeyName;SharedAccessKey=defaultKeyValue;`; + config = ConnectionConfig.create(connectionString); + } + + if (!options) { + options = {}; + } + this.name = config.endpoint; - this._context = ConnectionContext.create(config, tokenProvider, options); + this._context = ConnectionContext.create(config, credential, options); } /** @@ -161,102 +196,4 @@ export class ServiceBusClient { throw errObj; } } - - /** - * Creates a ServiceBusClient for the Service Bus Namespace represented in the given connection - * string. - * @param {string} connectionString - Connection string of the form - * 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' - * @param {ServiceBusClientOptions} [options] Options to control ways to interact with the - * Service Bus Namespace. - * @returns {ServiceBusClient} - */ - static createFromConnectionString( - connectionString: string, - options?: ServiceBusClientOptions - ): ServiceBusClient { - const config = ConnectionConfig.create(connectionString); - - config.webSocket = options && options.webSocket; - config.webSocketEndpointPath = "$servicebus/websocket"; - config.webSocketConstructorOptions = options && options.webSocketConstructorOptions; - - ConnectionConfig.validate(config); - const tokenProvider = new SasTokenProvider( - config.endpoint, - config.sharedAccessKeyName, - config.sharedAccessKey - ); - return new ServiceBusClient(config, tokenProvider, options); - } - - /** - * Creates a ServiceBusClient for the Service Bus Namespace represented by the given host using - * the given TokenProvider. - * @param {string} host - Fully qualified domain name for Servicebus. Most likely, - * `.servicebus.windows.net`. - * @param {TokenProvider} tokenProvider - Your custom implementation of the {@link https://github.com/Azure/amqp-common-js/blob/master/lib/auth/token.ts Token Provider} - * interface. - * @param {ServiceBusClientOptions} options - Options to control ways to interact with the - * Service Bus Namespace. - * @returns {ServiceBusClient} - */ - static createFromTokenProvider( - host: string, - tokenProvider: TokenProvider, - options?: ServiceBusClientOptions - ): ServiceBusClient { - host = String(host); - if (!tokenProvider) { - throw new TypeError('Missing parameter "tokenProvider"'); - } - if (!host.endsWith("/")) host += "/"; - const connectionString = - `Endpoint=sb://${host};SharedAccessKeyName=defaultKeyName;` + - `SharedAccessKey=defaultKeyValue`; - const config = ConnectionConfig.create(connectionString); - - config.webSocket = options && options.webSocket; - config.webSocketEndpointPath = "$servicebus/websocket"; - config.webSocketConstructorOptions = options && options.webSocketConstructorOptions; - - ConnectionConfig.validate(config); - return new ServiceBusClient(config, tokenProvider, options); - } - - /** - * Creates a ServiceBusClient for the Service Bus Namespace represented by the given host using - * the TokenCredentials generated using the `@azure/ms-rest-nodeauth` library. - * @param {string} host - Fully qualified domain name for ServiceBus. - * Most likely, {yournamespace}.servicebus.windows.net - * @param {ServiceClientCredentials} credentials - The Token credentials generated by using the - * `@azure/ms-rest-nodeauth` library. It can be one of the following: - * - ApplicationTokenCredentials - * - UserTokenCredentials - * - DeviceTokenCredentials - * - MSITokenCredentials - * Token audience (or resource in case of MSI based credentials) to use when creating the credentials is https://servicebus.azure.net/ - * @param {ServiceBusClientOptions} options - Options to control ways to interact with the - * Service Bus Namespace. - * @returns {ServiceBusClient} - * @throws Error if `createFromAadTokenCredentials` is accessed in browser context, as AAD support is not present in browser. - */ - static createFromAadTokenCredentials( - host: string, - credentials: - | ApplicationTokenCredentials - | UserTokenCredentials - | DeviceTokenCredentials - | MSITokenCredentials, - options?: ServiceBusClientOptions - ): ServiceBusClient { - if (!isNode) { - throw new Error( - "`createFromAadTokenCredentials` cannot be used to create ServiceBusClient as AAD support is not present in browser." - ); - } - host = String(host); - const tokenProvider = new AadTokenProvider(credentials); - return ServiceBusClient.createFromTokenProvider(host, tokenProvider, options); - } } diff --git a/sdk/servicebus/service-bus/src/serviceBusMessage.ts b/sdk/servicebus/service-bus/src/serviceBusMessage.ts index 8cc04e65314b..7228caea6fe7 100644 --- a/sdk/servicebus/service-bus/src/serviceBusMessage.ts +++ b/sdk/servicebus/service-bus/src/serviceBusMessage.ts @@ -9,7 +9,7 @@ import { MessageAnnotations, DeliveryAnnotations } from "rhea-promise"; -import { Constants, AmqpMessage, translate, ErrorNameConditionMapper } from "@azure/amqp-common"; +import { Constants, AmqpMessage, translate, ErrorNameConditionMapper } from "@azure/core-amqp"; import * as log from "./log"; import { ClientEntityContext } from "./clientEntityContext"; import { reorderLockToken } from "../src/util/utils"; diff --git a/sdk/servicebus/service-bus/src/session/messageSession.ts b/sdk/servicebus/service-bus/src/session/messageSession.ts index 82ebd69c5079..3a6b637eb50d 100644 --- a/sdk/servicebus/service-bus/src/session/messageSession.ts +++ b/sdk/servicebus/service-bus/src/session/messageSession.ts @@ -7,7 +7,7 @@ import { ErrorNameConditionMapper, MessagingError, Func -} from "@azure/amqp-common"; +} from "@azure/core-amqp"; import { Receiver, OnAmqpEvent, @@ -280,9 +280,7 @@ export class MessageSession extends LinkEntity { this.sessionLockedUntilUtc = await this._context.managementClient!.renewSessionLock( this.sessionId!, { - delayInSeconds: 0, - timeoutInSeconds: 10, - times: 4 + timeoutInMs: 10000 } ); log.receiver( @@ -551,8 +549,8 @@ export class MessageSession extends LinkEntity { const connectionId = this._context.namespace.connectionId; const receiverError = context.receiver && context.receiver.error; if (receiverError) { - const sbError = translate(receiverError); - if (sbError.name === "SessionLockLostError") { + const sbError = translate(receiverError) as MessagingError; + if (sbError.code === "SessionLockLostError") { this._context.expiredMessageSessions[this.sessionId!] = true; sbError.message = `The session lock has expired on the session with id ${this.sessionId}.`; } @@ -587,8 +585,8 @@ export class MessageSession extends LinkEntity { const receiver = this._receiver || context.receiver!; let isClosedDueToExpiry = false; if (receiverError) { - const sbError = translate(receiverError); - if (sbError.name === "SessionLockLostError") { + const sbError = translate(receiverError) as MessagingError; + if (sbError.code === "SessionLockLostError") { isClosedDueToExpiry = true; } log.error( @@ -929,7 +927,7 @@ export class MessageSession extends LinkEntity { maxWaitTimeInSeconds?: number ): Promise { if (maxWaitTimeInSeconds == null) { - maxWaitTimeInSeconds = Constants.defaultOperationTimeoutInSeconds; + maxWaitTimeInSeconds = Constants.defaultOperationTimeoutInMs / 1000; } const brokeredMessages: ServiceBusMessage[] = []; @@ -1150,7 +1148,7 @@ export class MessageSession extends LinkEntity { "Hence rejecting the promise with timeout error", this._context.namespace.connectionId, delivery.id, - Constants.defaultOperationTimeoutInSeconds * 1000 + Constants.defaultOperationTimeoutInMs ); const e: AmqpError = { @@ -1160,7 +1158,7 @@ export class MessageSession extends LinkEntity { "message may or may not be successful" }; return reject(translate(e)); - }, Constants.defaultOperationTimeoutInSeconds * 1000); + }, Constants.defaultOperationTimeoutInMs); this._deliveryDispositionMap.set(delivery.id, { resolve: resolve, reject: reject, diff --git a/sdk/servicebus/service-bus/src/session/sessionManager.ts b/sdk/servicebus/service-bus/src/session/sessionManager.ts index 5530c306aa6b..bd255627bcc5 100644 --- a/sdk/servicebus/service-bus/src/session/sessionManager.ts +++ b/sdk/servicebus/service-bus/src/session/sessionManager.ts @@ -7,7 +7,7 @@ import { ClientEntityContext } from "../clientEntityContext"; import { getProcessorCount } from "../util/utils"; import * as log from "../log"; import { Semaphore } from "../util/semaphore"; -import { delay, ConditionErrorNameMapper, Constants } from "@azure/amqp-common"; +import { delay, ConditionErrorNameMapper, Constants, MessagingError } from "@azure/core-amqp"; /** * @internal @@ -151,7 +151,10 @@ export class SessionManager { error ); await closeMessageSession(messageSession); - if (error.name !== ConditionErrorNameMapper["com.microsoft:message-wait-timeout"]) { + if ( + (error as MessagingError).code !== + ConditionErrorNameMapper["com.microsoft:message-wait-timeout"] + ) { // notify the user about the error. onError(error); } @@ -178,9 +181,9 @@ export class SessionManager { // the Promise is rejected. The "microsoft.timeout" error occurs when timeout happens on // the server side and ServiceBus sends a detach frame due to which the Promise is rejected. if ( - err.name === ConditionErrorNameMapper["amqp:operation-timeout"] || - err.name === ConditionErrorNameMapper["com.microsoft:timeout"] || - err.name === ConditionErrorNameMapper["com.microsoft:session-cannot-be-locked"] + err.code === "OperationTimeoutError" || + err.code === ConditionErrorNameMapper["com.microsoft:timeout"] || + err.code === ConditionErrorNameMapper["com.microsoft:session-cannot-be-locked"] ) { // No point in delaying if cancel has been requested. if (!this._isCancelRequested) { @@ -239,7 +242,7 @@ export class SessionManager { // We are explicitly configuring the messageSession to timeout in 60 seconds (if not provided // by the user) when no new messages are received. if (!options.newMessageWaitTimeoutInSeconds) { - options.newMessageWaitTimeoutInSeconds = Constants.defaultOperationTimeoutInSeconds; + options.newMessageWaitTimeoutInSeconds = Constants.defaultOperationTimeoutInMs / 1000; } this._maxConcurrentSessionsSemaphore = new Semaphore(this.maxConcurrenSessions); this._maxPendingAcceptSessionsSemaphore = new Semaphore( diff --git a/sdk/servicebus/service-bus/src/util/concurrentExpiringMap.ts b/sdk/servicebus/service-bus/src/util/concurrentExpiringMap.ts index 0afd31e4d086..3dc898f6d2a6 100644 --- a/sdk/servicebus/service-bus/src/util/concurrentExpiringMap.ts +++ b/sdk/servicebus/service-bus/src/util/concurrentExpiringMap.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { generate_uuid } from "rhea-promise"; -import { delay, AsyncLock } from "@azure/amqp-common"; +import { delay, AsyncLock } from "@azure/core-amqp"; import * as log from "../log"; /** diff --git a/sdk/servicebus/service-bus/src/util/constants.ts b/sdk/servicebus/service-bus/src/util/constants.ts index dc1ca18a3f1e..408d5d885493 100644 --- a/sdk/servicebus/service-bus/src/util/constants.ts +++ b/sdk/servicebus/service-bus/src/util/constants.ts @@ -3,7 +3,7 @@ export const packageJsonInfo = { name: "@azure/service-bus", - version: "1.1.3" + version: "2.0.0-preview.1" }; export const messageDispositionTimeout = 20000; diff --git a/sdk/servicebus/service-bus/test/README.md b/sdk/servicebus/service-bus/test/README.md index 38c936b47697..5b42d8f8a4ac 100644 --- a/sdk/servicebus/service-bus/test/README.md +++ b/sdk/servicebus/service-bus/test/README.md @@ -35,9 +35,9 @@ Go through the following setup in order to correctly setup the AAD credentials f Populate the following variables along with the above mentioned environment variables in the `.env`. ``` -AAD_CLIENT_ID="" -AAD_CLIENT_SECRET="" -AAD_TENANT_ID="" +AZURE_CLIENT_ID="" +AZURE_CLIENT_SECRET="" +AZURE_TENANT_ID="" ``` ## Run all tests diff --git a/sdk/servicebus/service-bus/test/atomManagement.spec.ts b/sdk/servicebus/service-bus/test/atomManagement.spec.ts index 0183dec1df88..076be79732c7 100644 --- a/sdk/servicebus/service-bus/test/atomManagement.spec.ts +++ b/sdk/servicebus/service-bus/test/atomManagement.spec.ts @@ -20,7 +20,7 @@ const env = getEnvVars(); import { EntityNames } from "./utils/testUtils"; -import { parseConnectionString } from "@azure/amqp-common"; +import { parseConnectionString } from "@azure/core-amqp"; import { recreateQueue, recreateTopic, recreateSubscription } from "./utils/managementUtils"; const serviceBusAtomManagementClient: ServiceBusAtomManagementClient = new ServiceBusAtomManagementClient( diff --git a/sdk/servicebus/service-bus/test/batchReceiver.spec.ts b/sdk/servicebus/service-bus/test/batchReceiver.spec.ts index 6c14f8983570..07b01068b3c4 100644 --- a/sdk/servicebus/service-bus/test/batchReceiver.spec.ts +++ b/sdk/servicebus/service-bus/test/batchReceiver.spec.ts @@ -687,7 +687,7 @@ describe("Batch Receiver - Settle deadlettered message", function(): void { const deadLetterMsg = await deadLetterMessage(testMessage); await deadLetterMsg.deadLetter().catch((err) => { - should.equal(err.name, "InvalidOperationError", "ErrorName is different than expected"); + should.equal(err.code, "InvalidOperationError", "Error code is different than expected"); errorWasThrown = true; }); diff --git a/sdk/servicebus/service-bus/test/perf/service-bus/receive.ts b/sdk/servicebus/service-bus/test/perf/service-bus/receive.ts index 5a84d14a5955..d9e4f0c189a4 100644 --- a/sdk/servicebus/service-bus/test/perf/service-bus/receive.ts +++ b/sdk/servicebus/service-bus/test/perf/service-bus/receive.ts @@ -41,7 +41,7 @@ async function RunTest( maxConcurrentCalls: number, messages: number ): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(entityPath); const receiver = client.createReceiver(ReceiveMode.receiveAndDelete); diff --git a/sdk/servicebus/service-bus/test/perf/service-bus/send.ts b/sdk/servicebus/service-bus/test/perf/service-bus/send.ts index 40970568082a..2ec9d571b7d0 100644 --- a/sdk/servicebus/service-bus/test/perf/service-bus/send.ts +++ b/sdk/servicebus/service-bus/test/perf/service-bus/send.ts @@ -42,7 +42,7 @@ async function RunTest( maxInflight: number, messages: number ): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(entityPath); const sender = client.createSender(); diff --git a/sdk/servicebus/service-bus/test/renewLock.spec.ts b/sdk/servicebus/service-bus/test/renewLock.spec.ts index 980acdab015e..45e3e88e5e22 100644 --- a/sdk/servicebus/service-bus/test/renewLock.spec.ts +++ b/sdk/servicebus/service-bus/test/renewLock.spec.ts @@ -315,7 +315,7 @@ async function testBatchReceiverManualLockRenewalErrorOnLockExpiry( let errorWasThrown: boolean = false; await msgs[0].complete().catch((err) => { - should.equal(err.name, "MessageLockLostError", "ErrorName is different than expected"); + should.equal(err.code, "MessageLockLostError", "Error code is different than expected"); errorWasThrown = true; }); @@ -433,7 +433,7 @@ async function testAutoLockRenewalConfigBehavior( let errorWasThrown: boolean = false; await brokeredMessage.complete().catch((err) => { - should.equal(err.name, "MessageLockLostError", "ErrorName is different than expected"); + should.equal(err.code, "MessageLockLostError", "Error code is different than expected"); errorWasThrown = true; }); diff --git a/sdk/servicebus/service-bus/test/renewLockSessions.spec.ts b/sdk/servicebus/service-bus/test/renewLockSessions.spec.ts index 8ed067c41db3..d2c707a4d180 100644 --- a/sdk/servicebus/service-bus/test/renewLockSessions.spec.ts +++ b/sdk/servicebus/service-bus/test/renewLockSessions.spec.ts @@ -23,7 +23,8 @@ import { getSenderReceiverClients, TestClientType, TestMessage, - getServiceBusClient + getServiceBusClient, + isMessagingError } from "./utils/testUtils"; let sbClient: ServiceBusClient; @@ -328,7 +329,7 @@ async function testBatchReceiverManualLockRenewalErrorOnLockExpiry( let errorWasThrown: boolean = false; await msgs[0].complete().catch((err) => { - should.equal(err.name, "SessionLockLostError", "ErrorName is different than expected"); + should.equal(err.code, "SessionLockLostError", "Error code is different than expected"); errorWasThrown = true; }); @@ -461,7 +462,7 @@ async function testAutoLockRenewalConfigBehavior( } }, (err: MessagingError | Error) => { - if (err.name === "SessionLockLostError") { + if (isMessagingError(err) && err.code === "SessionLockLostError") { sessionLockLostErrorThrown = true; } else { onError(err); @@ -482,7 +483,7 @@ async function testAutoLockRenewalConfigBehavior( let errorWasThrown: boolean = false; await messagesReceived[0].complete().catch((err) => { - should.equal(err.name, "SessionLockLostError", "ErrorName is different than expected"); + should.equal(err.code, "SessionLockLostError", "Error code is different than expected"); errorWasThrown = true; }); diff --git a/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts b/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts index 970bb04dc02b..1878c31d2b7d 100644 --- a/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts +++ b/sdk/servicebus/service-bus/test/serviceBusClient.spec.ts @@ -14,7 +14,8 @@ import { SessionReceiver, SubscriptionClient, TopicClient, - ServiceBusMessage + ServiceBusMessage, + MessagingError } from "../src"; import { getClientClosedErrorMsg, @@ -28,16 +29,21 @@ import { getSenderReceiverClients, purge, TestMessage, - getServiceBusClient + getServiceBusClient, + isMessagingError } from "./utils/testUtils"; import { ClientType } from "../src/client"; import { DispositionType } from "../src/serviceBusMessage"; -import { getEnvVars, isNode } from "./utils/envVarUtils"; -import { getTokenCredentialsFromAAD } from "./utils/aadUtils"; const should = chai.should(); chai.use(chaiAsPromised); +import { EnvVarNames, getEnvVars, isNode } from "../test/utils/envVarUtils"; +import * as dotenv from "dotenv"; +dotenv.config(); + +import { EnvironmentCredential } from "@azure/identity"; + describe("Create ServiceBusClient and Queue/Topic/Subscription Clients #RunInBrowser", function(): void { let sbClient: ServiceBusClient; @@ -48,7 +54,7 @@ describe("Create ServiceBusClient and Queue/Topic/Subscription Clients #RunInBro }); it("Creates an Namespace from a connection string", function(): void { - sbClient = ServiceBusClient.createFromConnectionString( + sbClient = new ServiceBusClient( "Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c;EntityPath=d" ); sbClient.should.be.an.instanceof(ServiceBusClient); @@ -56,7 +62,7 @@ describe("Create ServiceBusClient and Queue/Topic/Subscription Clients #RunInBro }); it("Creates clients after coercing name to string", function(): void { - sbClient = ServiceBusClient.createFromConnectionString( + sbClient = new ServiceBusClient( "Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c;EntityPath=d" ); const queueClient = sbClient.createQueueClient(1 as any); @@ -68,29 +74,13 @@ describe("Create ServiceBusClient and Queue/Topic/Subscription Clients #RunInBro const subscriptionClient = sbClient.createSubscriptionClient(1 as any, 2 as any); should.equal(subscriptionClient.entityPath, "1/Subscriptions/2"); }); - - it("Missing tokenProvider in createFromTokenProvider", function(): void { - let caughtError: Error | undefined; - try { - sbClient = ServiceBusClient.createFromTokenProvider("somestring", undefined as any); - } catch (error) { - caughtError = error; - } - should.equal(caughtError && caughtError.name, "TypeError"); - should.equal(caughtError && caughtError.message, `Missing parameter "tokenProvider"`); - }); - - it("Coerces input to string for host in createFromTokenProvider", function(): void { - sbClient = ServiceBusClient.createFromTokenProvider(123 as any, {} as any); - should.equal(sbClient.name, "sb://123/", "Name of the namespace is different than expected"); - }); }); describe("Errors with non existing Namespace #RunInBrowser", function(): void { let sbClient: ServiceBusClient; let errorWasThrown: boolean; beforeEach(() => { - sbClient = ServiceBusClient.createFromConnectionString( + sbClient = new ServiceBusClient( "Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c;EntityPath=d" ); errorWasThrown = false; @@ -99,9 +89,14 @@ describe("Errors with non existing Namespace #RunInBrowser", function(): void { return sbClient.close(); }); - const testError = (err: Error): void => { - should.equal(err.name, "ServiceCommunicationError", "ErrorName is different than expected"); - errorWasThrown = true; + const testError = (err: Error | MessagingError): void => { + const expectedErrCode = isNode ? "ENOTFOUND" : "ServiceCommunicationError"; + if (!isMessagingError(err)) { + should.equal(true, false, "Error expected to be instance of MessagingError"); + } else { + should.equal(err.code, expectedErrCode, "Error code is different than expected"); + errorWasThrown = true; + } }; it("throws error when sending data via a queueClient to a non existing namespace", async function(): Promise< @@ -151,7 +146,7 @@ describe("Errors with non existing Namespace #RunInBrowser", function(): void { should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error when receving batch data via a queueClient from a non existing namespace", async function(): Promise< + it("throws error when receiving batch data via a queueClient from a non existing namespace", async function(): Promise< void > { const client = sbClient.createQueueClient("some-name"); @@ -161,7 +156,7 @@ describe("Errors with non existing Namespace #RunInBrowser", function(): void { should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error when receving batch data via a subscriptionClient from a non existing namespace", async function(): Promise< + it("throws error when receiving batch data via a subscriptionClient from a non existing namespace", async function(): Promise< void > { const client = sbClient.createSubscriptionClient("some-topic-name", "some-subscription-name"); @@ -171,7 +166,7 @@ describe("Errors with non existing Namespace #RunInBrowser", function(): void { should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error when receving streaming data via a queueClient from a non existing namespace", async function(): Promise< + it("throws error when receiving streaming data via a queueClient from a non existing namespace", async function(): Promise< void > { const client = sbClient.createQueueClient("some-name"); @@ -199,15 +194,23 @@ describe("Errors with non existing Queue/Topic/Subscription", async function(): return sbClient.close(); }); - const testError = (err: Error, entityPath: string): void => { - should.equal(err.name, "MessagingEntityNotFoundError", "ErrorName is different than expected"); - should.equal( - err.message.startsWith( - `The messaging entity '${sbClient.name}${entityPath}' could not be found.` - ), - true - ); - errorWasThrown = true; + const testError = (err: Error | MessagingError, entityPath: string): void => { + if (!isMessagingError(err)) { + should.equal(true, false, "Error expected to be instance of MessagingError"); + } else { + should.equal( + err.code, + "MessagingEntityNotFoundError", + "Error code is different than expected" + ); + should.equal( + err.message.startsWith( + `The messaging entity '${sbClient.name}${entityPath}' could not be found.` + ), + true + ); + errorWasThrown = true; + } }; it("throws error when sending data to a non existing queue #RunInBrowser", async function(): Promise< @@ -278,7 +281,7 @@ describe("Errors with non existing Queue/Topic/Subscription", async function(): should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error when receving streaming data from a non existing queue #RunInBrowser", async function(): Promise< + it("throws error when receiving streaming data from a non existing queue #RunInBrowser", async function(): Promise< void > { const client = sbClient.createQueueClient("some-name"); @@ -293,7 +296,7 @@ describe("Errors with non existing Queue/Topic/Subscription", async function(): should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error when receving streaming data from a non existing subscription", async function(): Promise< + it("throws error when receiving streaming data from a non existing subscription", async function(): Promise< void > { const client = sbClient.createSubscriptionClient("some-topic-name", "some-subscription-name"); @@ -311,7 +314,7 @@ describe("Errors with non existing Queue/Topic/Subscription", async function(): }); }); -describe("Test createFromAadTokenCredentials", function(): void { +describe("Test ServiceBusClient creation #RunInBrowser", function(): void { let sbClient: ServiceBusClient; let errorWasThrown: boolean = false; @@ -320,69 +323,91 @@ describe("Test createFromAadTokenCredentials", function(): void { "Endpoint=sb://((.*).servicebus.windows.net)" ) || "")[1]; - async function testCreateFromAadTokenCredentials(host: string, tokenCreds: any): Promise { - const testMessages = TestMessage.getSample(); - sbClient = ServiceBusClient.createFromAadTokenCredentials(host, tokenCreds); - sbClient.should.be.an.instanceof(ServiceBusClient); - const clients = await getSenderReceiverClients( - sbClient, - TestClientType.UnpartitionedQueue, - TestClientType.UnpartitionedQueue + /** + * Utility to create EnvironmentCredential using `@azure/identity` + */ + function getDefaultTokenCredential() { + should.exist( + env[EnvVarNames.AZURE_CLIENT_ID], + "define AZURE_CLIENT_ID in your environment before running integration tests." ); - - const sender = clients.senderClient.createSender(); - const receiver = await clients.receiverClient.createReceiver(ReceiveMode.peekLock); - await sender.send(testMessages); - const msgs = await receiver.receiveMessages(1); - - should.equal(Array.isArray(msgs), true, "`ReceivedMessages` is not an array"); - should.equal(msgs[0].body, testMessages.body, "MessageBody is different than expected"); - should.equal(msgs.length, 1, "Unexpected number of messages"); + should.exist( + env[EnvVarNames.AZURE_TENANT_ID], + "define AZURE_TENANT_ID in your environment before running integration tests." + ); + should.exist( + env[EnvVarNames.AZURE_CLIENT_SECRET], + "define AZURE_CLIENT_SECRET in your environment before running integration tests." + ); + should.exist( + env[EnvVarNames.SERVICEBUS_CONNECTION_STRING], + "define EVENTHUB_CONNECTION_STRING in your environment before running integration tests." + ); + return new EnvironmentCredential(); } - it("throws error when using `CreateFromAadTokenCredentials` in browser #RunInBrowser", async function(): Promise< - void - > { - // We use the `!isNode` check here to ensure this test is run only in browser only - // as by default all tests run in Node - if (!isNode) { - const credentials: any = {}; - await testCreateFromAadTokenCredentials(serviceBusEndpoint, credentials).catch((err) => { - errorWasThrown = true; - should.equal( - err.message, - "`createFromAadTokenCredentials` cannot be used to create ServiceBusClient as AAD support is not present in browser." - ); - }); - should.equal(errorWasThrown, true, "Error thrown flag must be true"); + it("throws error for invalid tokenCredentials", async function(): Promise { + try { + new ServiceBusClient(serviceBusEndpoint, [] as any); + } catch (err) { + errorWasThrown = true; + should.equal( + err.message, + "Connection string malformed: each part of the connection string must have an `=` assignment.", + // "'credentials' is a required parameter and must be an implementation of TokenCredential when using host based constructor overload.", + "ErrorMessage is different than expected" + ); } + should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("throws error for invalid tokenCredentials", async function(): Promise { - await testCreateFromAadTokenCredentials(serviceBusEndpoint, "").catch((err) => { + it("throws error for undefined tokenCredentials", async function(): Promise { + try { + new ServiceBusClient(serviceBusEndpoint, undefined as any); + } catch (err) { errorWasThrown = true; should.equal( err.message, - "'credentials' is a required parameter and must be an instance of ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials.", + "Connection string malformed: each part of the connection string must have an `=` assignment.", + // "'credentials' is a required parameter and must be an implementation of TokenCredential when using host based constructor overload.", "ErrorMessage is different than expected" ); - }); + } should.equal(errorWasThrown, true, "Error thrown flag must be true"); }); - it("Coerces input to string for host in createFromAadTokenCredentials", async function(): Promise< - void - > { - const tokenCreds = await getTokenCredentialsFromAAD(); - sbClient = ServiceBusClient.createFromAadTokenCredentials(123 as any, tokenCreds); - should.equal(sbClient.name, "sb://123/", "Name of the namespace is different than expected"); - }); + if (isNode) { + it("Coerces input to string for host in credential based constructor", async function(): Promise< + void + > { + const tokenCreds = getDefaultTokenCredential(); + sbClient = new ServiceBusClient(123 as any, tokenCreds); + should.equal(sbClient.name, "sb://123/", "Name of the namespace is different than expected"); + }); - it("sends a message to the ServiceBus entity", async function(): Promise { - const tokenCreds = await getTokenCredentialsFromAAD(); - await testCreateFromAadTokenCredentials(serviceBusEndpoint, tokenCreds); - await sbClient.close(); - }); + it("sends a message to the ServiceBus entity", async function(): Promise { + const tokenCreds = getDefaultTokenCredential(); + const sbClient = new ServiceBusClient(serviceBusEndpoint, tokenCreds); + + sbClient.should.be.an.instanceof(ServiceBusClient); + const clients = await getSenderReceiverClients( + sbClient, + TestClientType.UnpartitionedQueue, + TestClientType.UnpartitionedQueue + ); + + const sender = clients.senderClient.createSender(); + const receiver = await clients.receiverClient.createReceiver(ReceiveMode.peekLock); + const testMessages = TestMessage.getSample(); + await sender.send(testMessages); + const msgs = await receiver.receiveMessages(1); + + should.equal(Array.isArray(msgs), true, "`ReceivedMessages` is not an array"); + should.equal(msgs[0].body, testMessages.body, "MessageBody is different than expected"); + should.equal(msgs.length, 1, "Unexpected number of messages"); + await sbClient.close(); + }); + } }); describe("Errors after close()", function(): void { diff --git a/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts b/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts index 6b7c391f1500..e9ae6709ada0 100644 --- a/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts +++ b/sdk/servicebus/service-bus/test/streamingReceiver.spec.ts @@ -25,10 +25,12 @@ import { TestMessage, getServiceBusClient } from "./utils/testUtils"; -import { SasTokenProvider, TokenInfo, parseConnectionString } from "@azure/amqp-common"; -import { getEnvVars, EnvVarNames } from "./utils/envVarUtils"; import { StreamingReceiver } from "../src/core/streamingReceiver"; +import { AccessToken, parseConnectionString, TokenCredential } from "@azure/core-amqp"; +import { getEnvVars, EnvVarNames } from "./utils/envVarUtils"; +import { EnvironmentCredential } from "@azure/identity"; + const should = chai.should(); chai.use(chaiAsPromised); @@ -867,34 +869,26 @@ describe("Streaming - Failed init should not cache recevier", function(): void { await afterEachTest(); }); - class TestTokenProvider extends SasTokenProvider { + class TestTokenCredential extends EnvironmentCredential implements TokenCredential { private firstCall = true; static errorMessage = "This is a faulty token provider."; - constructor(connectionObject: { - Endpoint: string; - SharedAccessKeyName: string; - SharedAccessKey: string; - }) { - super( - connectionObject.Endpoint, - connectionObject.SharedAccessKeyName, - connectionObject.SharedAccessKey - ); + constructor() { + super(); } - async getToken(audience: string): Promise { + async getToken(audience: string): Promise { if (this.firstCall) { this.firstCall = false; - throw new Error(TestTokenProvider.errorMessage); + throw new Error(TestTokenCredential.errorMessage); } return super.getToken(audience); } } - it("UnPartitioned Queue: Receiver is not cached when not initialized #RunInBrowser", async function(): Promise< + it("UnPartitioned Queue: Receiver is not cached when not initialized", async function(): Promise< void > { - const env = getEnvVars(); + const env: any = getEnvVars(); // Send a message using service bus client created with connection string sbClient = getServiceBusClient(); @@ -913,11 +907,8 @@ describe("Streaming - Failed init should not cache recevier", function(): void { SharedAccessKeyName: string; SharedAccessKey: string; } = parseConnectionString(env[EnvVarNames.SERVICEBUS_CONNECTION_STRING]); - const tokenProvider = new TestTokenProvider(connectionObject); - sbClient = ServiceBusClient.createFromTokenProvider( - connectionObject.Endpoint.substr(5), - tokenProvider - ); + const tokenProvider = new TestTokenCredential(); + sbClient = new ServiceBusClient(connectionObject.Endpoint.substr(5), tokenProvider); clients = await getSenderReceiverClients( sbClient, TestClientType.UnpartitionedQueue, @@ -940,7 +931,7 @@ describe("Streaming - Failed init should not cache recevier", function(): void { should.equal(errCheck, true, "Expected error to be thrown, but no error found."); should.equal( actualError!.message, - TestTokenProvider.errorMessage, + TestTokenCredential.errorMessage, "Expected error from token provider, but unexpected error found." ); should.equal( diff --git a/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsMultipleQueues.ts b/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsMultipleQueues.ts index 5dbaba859eb9..435a6465047e 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsMultipleQueues.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsMultipleQueues.ts @@ -34,7 +34,7 @@ async function main(): Promise { } async function sendReceiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const clients = []; const senders = []; diff --git a/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsSingleQueue.ts b/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsSingleQueue.ts index 7edccdf52d95..ef8040ec2258 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsSingleQueue.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_fixedNumberOfClientsSingleQueue.ts @@ -36,7 +36,7 @@ async function main(): Promise { } async function sendReceiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const clients = []; const senders = []; diff --git a/sdk/servicebus/service-bus/test/stress/stress_messageAutolockRenewal.ts b/sdk/servicebus/service-bus/test/stress/stress_messageAutolockRenewal.ts index cf9f8e92f5e9..c6b725562d0c 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_messageAutolockRenewal.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_messageAutolockRenewal.ts @@ -35,7 +35,7 @@ async function main(): Promise { } async function sendMessage(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -54,7 +54,7 @@ async function sendMessage(): Promise { } async function receiveMessage(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_messageLockRenewalBatchingThenStreaming.ts b/sdk/servicebus/service-bus/test/stress/stress_messageLockRenewalBatchingThenStreaming.ts index 19fc13f35160..a3c4dd6a8846 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_messageLockRenewalBatchingThenStreaming.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_messageLockRenewalBatchingThenStreaming.ts @@ -38,7 +38,7 @@ async function main(): Promise { } async function sendMessage(messageId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -57,7 +57,7 @@ async function sendMessage(messageId: string): Promise { } async function receiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_messageManualLockRenewal.ts b/sdk/servicebus/service-bus/test/stress/stress_messageManualLockRenewal.ts index 17ec3a740af7..98445d93007f 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_messageManualLockRenewal.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_messageManualLockRenewal.ts @@ -36,7 +36,7 @@ async function main(): Promise { } async function sendMessage(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -55,7 +55,7 @@ async function sendMessage(): Promise { } async function receiveMessage(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_messageRandomDisposition.ts b/sdk/servicebus/service-bus/test/stress/stress_messageRandomDisposition.ts index 0b27840d8287..3ab6f9bbd0ba 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_messageRandomDisposition.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_messageRandomDisposition.ts @@ -47,7 +47,7 @@ async function main(): Promise { } async function sendMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -70,7 +70,7 @@ async function sendMessages(): Promise { } async function receiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_messageRandomDispositionOnSession.ts b/sdk/servicebus/service-bus/test/stress/stress_messageRandomDispositionOnSession.ts index a9b5a3a0e4f2..f99dc0c5c6c1 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_messageRandomDispositionOnSession.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_messageRandomDispositionOnSession.ts @@ -48,7 +48,7 @@ async function main(): Promise { } async function sendMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -72,7 +72,7 @@ async function sendMessages(): Promise { } async function receiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_sessionAutolockRenewal.ts b/sdk/servicebus/service-bus/test/stress/stress_sessionAutolockRenewal.ts index 83cb471f4827..20c90d6dface 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_sessionAutolockRenewal.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_sessionAutolockRenewal.ts @@ -35,7 +35,7 @@ async function main(): Promise { } async function sendMessage(sessionId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -55,7 +55,7 @@ async function sendMessage(sessionId: string): Promise { } async function receiveMessage(sessionId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_sessionManualLockRenewal.ts b/sdk/servicebus/service-bus/test/stress/stress_sessionManualLockRenewal.ts index 3c3b6bbab7ca..80266a534a68 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_sessionManualLockRenewal.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_sessionManualLockRenewal.ts @@ -37,7 +37,7 @@ async function main(): Promise { } async function sendMessage(sessionId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -57,7 +57,7 @@ async function sendMessage(sessionId: string): Promise { } async function receiveMessage(sessionId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_sessionState.ts b/sdk/servicebus/service-bus/test/stress/stress_sessionState.ts index 2162870adb14..f89821a9a643 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_sessionState.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_sessionState.ts @@ -25,7 +25,7 @@ async function main(): Promise { } async function setGetSessionState(sessionId: string): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/stress/stress_singleClient.ts b/sdk/servicebus/service-bus/test/stress/stress_singleClient.ts index cc787921bcfc..3633158c372d 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_singleClient.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_singleClient.ts @@ -35,7 +35,7 @@ async function main(): Promise { } async function sendReceiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); try { while (!isJobDone) { diff --git a/sdk/servicebus/service-bus/test/stress/stress_singleMessageComplete.ts b/sdk/servicebus/service-bus/test/stress/stress_singleMessageComplete.ts index 7d8782bcfeb5..0c887303018c 100644 --- a/sdk/servicebus/service-bus/test/stress/stress_singleMessageComplete.ts +++ b/sdk/servicebus/service-bus/test/stress/stress_singleMessageComplete.ts @@ -40,7 +40,7 @@ async function main(): Promise { } async function sendMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { const sender = client.createSender(); @@ -63,7 +63,7 @@ async function sendMessages(): Promise { } async function receiveMessages(): Promise { - const ns = ServiceBusClient.createFromConnectionString(connectionString); + const ns = new ServiceBusClient(connectionString); const client = ns.createQueueClient(queueName); try { diff --git a/sdk/servicebus/service-bus/test/topicFilters.spec.ts b/sdk/servicebus/service-bus/test/topicFilters.spec.ts index c3107e2f99c3..270040eb4b64 100644 --- a/sdk/servicebus/service-bus/test/topicFilters.spec.ts +++ b/sdk/servicebus/service-bus/test/topicFilters.spec.ts @@ -239,9 +239,9 @@ describe("addRule() #RunInBrowser", function(): void { "ErrorMessage is different than expected" ); should.equal( - error.name, + error.code, "MessagingEntityAlreadyExistsError", - "ErrorName is different than expected" + "Error code is different than expected" ); } should.equal(errorWasThrown, true, "Error thrown flag must be true"); @@ -270,9 +270,9 @@ describe("removeRule()", function(): void { "ErrorMessage is different than expected" ); should.equal( - error.name, + error.code, "MessagingEntityNotFoundError", - "ErrorName is different than expected" + "Error code is different than expected" ); errorWasThrown = true; } diff --git a/sdk/servicebus/service-bus/test/utils/aadUtils.browser.ts b/sdk/servicebus/service-bus/test/utils/aadUtils.browser.ts deleted file mode 100644 index 861973d77b9c..000000000000 --- a/sdk/servicebus/service-bus/test/utils/aadUtils.browser.ts +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -export async function getTokenCredentialsFromAAD() {} diff --git a/sdk/servicebus/service-bus/test/utils/aadUtils.ts b/sdk/servicebus/service-bus/test/utils/aadUtils.ts deleted file mode 100644 index 2588c21d5c6a..000000000000 --- a/sdk/servicebus/service-bus/test/utils/aadUtils.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -import { EnvVarNames, getEnvVars } from "./envVarUtils"; - -import { loginWithServicePrincipalSecret } from "@azure/ms-rest-nodeauth"; - -const aadServiceBusAudience = "https://servicebus.azure.net/"; - -export async function getTokenCredentialsFromAAD() { - const env = getEnvVars(); - const tokenCreds = await loginWithServicePrincipalSecret( - env[EnvVarNames.AAD_CLIENT_ID], - env[EnvVarNames.AAD_CLIENT_SECRET], - env[EnvVarNames.AAD_TENANT_ID], - { - tokenAudience: aadServiceBusAudience - } - ); - return tokenCreds; -} diff --git a/sdk/servicebus/service-bus/test/utils/envVarUtils.ts b/sdk/servicebus/service-bus/test/utils/envVarUtils.ts index b2997f4c1d77..4cd82ea5da83 100644 --- a/sdk/servicebus/service-bus/test/utils/envVarUtils.ts +++ b/sdk/servicebus/service-bus/test/utils/envVarUtils.ts @@ -9,9 +9,9 @@ export const isNode = */ export enum EnvVarNames { SERVICEBUS_CONNECTION_STRING = "SERVICEBUS_CONNECTION_STRING", - AAD_CLIENT_ID = "AAD_CLIENT_ID", - AAD_CLIENT_SECRET = "AAD_CLIENT_SECRET", - AAD_TENANT_ID = "AAD_TENANT_ID" + AZURE_CLIENT_ID = "AZURE_CLIENT_ID", + AZURE_CLIENT_SECRET = "AZURE_CLIENT_SECRET", + AZURE_TENANT_ID = "AZURE_TENANT_ID" } /** @@ -42,9 +42,9 @@ export function getEnvVars(): { [key in EnvVarNames]: any } { // Throw error if required environment variables are missing. [ EnvVarNames.SERVICEBUS_CONNECTION_STRING, - EnvVarNames.AAD_CLIENT_ID, - EnvVarNames.AAD_CLIENT_SECRET, - EnvVarNames.AAD_TENANT_ID + EnvVarNames.AZURE_CLIENT_ID, + EnvVarNames.AZURE_CLIENT_SECRET, + EnvVarNames.AZURE_TENANT_ID ].forEach(function(name: string) { if (!getEnvVarValue(name)) { throw new Error(`Define ${name} in your environment before running integration tests.`); @@ -55,9 +55,9 @@ export function getEnvVars(): { [key in EnvVarNames]: any } { [EnvVarNames.SERVICEBUS_CONNECTION_STRING]: getEnvVarValue( EnvVarNames.SERVICEBUS_CONNECTION_STRING ), - [EnvVarNames.AAD_CLIENT_ID]: getEnvVarValue(EnvVarNames.AAD_CLIENT_ID), - [EnvVarNames.AAD_CLIENT_SECRET]: getEnvVarValue(EnvVarNames.AAD_CLIENT_SECRET), - [EnvVarNames.AAD_TENANT_ID]: getEnvVarValue(EnvVarNames.AAD_TENANT_ID) + [EnvVarNames.AZURE_CLIENT_ID]: getEnvVarValue(EnvVarNames.AZURE_CLIENT_ID), + [EnvVarNames.AZURE_CLIENT_SECRET]: getEnvVarValue(EnvVarNames.AZURE_CLIENT_SECRET), + [EnvVarNames.AZURE_TENANT_ID]: getEnvVarValue(EnvVarNames.AZURE_TENANT_ID) }; return envVars; diff --git a/sdk/servicebus/service-bus/test/utils/testUtils.ts b/sdk/servicebus/service-bus/test/utils/testUtils.ts index 40d456a4221d..8335e8db455b 100644 --- a/sdk/servicebus/service-bus/test/utils/testUtils.ts +++ b/sdk/servicebus/service-bus/test/utils/testUtils.ts @@ -10,7 +10,8 @@ import { SubscriptionClient, delay, ReceiveMode, - ServiceBusMessage + ServiceBusMessage, + MessagingError } from "../../src"; import { EnvVarNames, getEnvVars } from "./envVarUtils"; import { recreateQueue, recreateSubscription, recreateTopic } from "./managementUtils"; @@ -470,7 +471,7 @@ export function getNamespace(serviceBusConnectionString: string): string { export function getServiceBusClient(): ServiceBusClient { const env = getEnvVars(); - return ServiceBusClient.createFromConnectionString(env[EnvVarNames.SERVICEBUS_CONNECTION_STRING]); + return new ServiceBusClient(env[EnvVarNames.SERVICEBUS_CONNECTION_STRING]); } /** @@ -503,3 +504,11 @@ export enum EntityNames { MANAGEMENT_NEW_ENTITY_1 = "management-new-entity-1", MANAGEMENT_NEW_ENTITY_2 = "management-new-entity-2" } + +/** + * Utility to check if given error is instance of `MessagingError` + * @param err + */ +export function isMessagingError(err: any): err is MessagingError { + return err.name === "MessagingError"; +} diff --git a/sdk/servicebus/service-bus/tests.yml b/sdk/servicebus/service-bus/tests.yml index ffe676f9caf9..25cd48df8794 100644 --- a/sdk/servicebus/service-bus/tests.yml +++ b/sdk/servicebus/service-bus/tests.yml @@ -24,7 +24,8 @@ jobs: OSVmImage: "windows-2019" TestType: "browser" EnvVars: - AAD_CLIENT_ID: $(aad-azure-sdk-test-client-id) - AAD_TENANT_ID: $(aad-azure-sdk-test-tenant-id) - AAD_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) - SERVICEBUS_CONNECTION_STRING: $(SERVICEBUS_CONNECTION_STRING) + AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id) + AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id) + AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) + AZURE_SUBSCRIPTION_ID: $(test-subscription-id) + SERVICEBUS_CONNECTION_STRING: $(service-bus-test-connection-string)