diff --git a/sdk/communication/communication-alpha-ids/CHANGELOG.md b/sdk/communication/communication-alpha-ids/CHANGELOG.md index d616e0ab9a4c..df1107ed7277 100644 --- a/sdk/communication/communication-alpha-ids/CHANGELOG.md +++ b/sdk/communication/communication-alpha-ids/CHANGELOG.md @@ -1,5 +1,17 @@ # Release History +## 1.0.0-beta.2 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0-beta.1 (Unreleased) ### Features Added diff --git a/sdk/communication/communication-alpha-ids/package.json b/sdk/communication/communication-alpha-ids/package.json index febdf7bc1e39..0962c370fa4f 100644 --- a/sdk/communication/communication-alpha-ids/package.json +++ b/sdk/communication/communication-alpha-ids/package.json @@ -1,6 +1,6 @@ { "name": "@azure-tools/communication-alpha-ids", - "version": "1.0.0-beta.1", + "version": "1.0.0-beta.2", "description": "SDK for Azure Communication Services which facilitates Alpha IDs administration.", "sdk-type": "client", "main": "dist/index.js", diff --git a/sdk/communication/communication-alpha-ids/src/alphaIdsClient.ts b/sdk/communication/communication-alpha-ids/src/alphaIdsClient.ts index 6aeb866ab51b..8c00140068d7 100644 --- a/sdk/communication/communication-alpha-ids/src/alphaIdsClient.ts +++ b/sdk/communication/communication-alpha-ids/src/alphaIdsClient.ts @@ -6,12 +6,13 @@ import { GetConfigurationOptions, UpsertConfigurationOptions, } from "./models"; -import { tracingClient, logger } from "./utils"; import { isKeyCredential, parseClientArguments } from "@azure/communication-common"; import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; import { CommonClientOptions, InternalClientPipelineOptions } from "@azure/core-client"; import { AlphaIDsClient as AlphaIDsGeneratedClient } from "./generated/src"; import { createCommunicationAuthPolicy } from "@azure/communication-common"; +import { logger } from "./utils"; +import { tracingClient } from "./generated/src/tracing"; /** * Client options used to configure the AlphaIdsClient API requests. */ diff --git a/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClient.ts b/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClient.ts index da50959000ad..60d6749895f1 100644 --- a/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClient.ts +++ b/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClient.ts @@ -6,20 +6,112 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import * as coreRestPipeline from "@azure/core-rest-pipeline"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { AlphaIdsImpl } from "./operations"; import { AlphaIds } from "./operationsInterfaces"; -import { AlphaIDsClientContext } from "./alphaIDsClientContext"; import { AlphaIDsClientOptionalParams } from "./models"; -export class AlphaIDsClient extends AlphaIDsClientContext { +export class AlphaIDsClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the AlphaIDsClient class. * @param endpoint The communication resource, for example https://resourcename.communication.azure.com * @param options The parameter options */ constructor(endpoint: string, options?: AlphaIDsClientOptionalParams) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: AlphaIDsClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-alpha-ids/1.0.0-beta.2`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + + if (options?.pipeline && options.pipeline.getOrderedPolicies().length > 0) { + const pipelinePolicies: coreRestPipeline.PipelinePolicy[] = options.pipeline.getOrderedPolicies(); + const bearerTokenAuthenticationPolicyFound = pipelinePolicies.some( + (pipelinePolicy) => + pipelinePolicy.name === + coreRestPipeline.bearerTokenAuthenticationPolicyName + ); + if (!bearerTokenAuthenticationPolicyFound) { + this.pipeline.removePolicy({ + name: coreRestPipeline.bearerTokenAuthenticationPolicyName + }); + this.pipeline.addPolicy( + coreRestPipeline.bearerTokenAuthenticationPolicy({ + scopes: `${optionsWithDefaults.baseUri}/.default`, + challengeCallbacks: { + authorizeRequestOnChallenge: + coreClient.authorizeRequestOnClaimChallenge + } + }) + ); + } + } + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2022-09-26-preview"; this.alphaIds = new AlphaIdsImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } alphaIds: AlphaIds; diff --git a/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClientContext.ts b/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClientContext.ts deleted file mode 100644 index 96fdc7a169f7..000000000000 --- a/sdk/communication/communication-alpha-ids/src/generated/src/alphaIDsClientContext.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { AlphaIDsClientOptionalParams } from "./models"; - -export class AlphaIDsClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the AlphaIDsClientContext class. - * @param endpoint The communication resource, for example https://resourcename.communication.azure.com - * @param options The parameter options - */ - constructor(endpoint: string, options?: AlphaIDsClientOptionalParams) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: AlphaIDsClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-communication-alpha-ids/1.0.0-beta.1`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2022-09-26-preview"; - } -} diff --git a/sdk/communication/communication-alpha-ids/src/generated/src/index.ts b/sdk/communication/communication-alpha-ids/src/generated/src/index.ts index d98a312bbd10..17d5a55472c5 100644 --- a/sdk/communication/communication-alpha-ids/src/generated/src/index.ts +++ b/sdk/communication/communication-alpha-ids/src/generated/src/index.ts @@ -8,5 +8,4 @@ export * from "./models"; export { AlphaIDsClient } from "./alphaIDsClient"; -export { AlphaIDsClientContext } from "./alphaIDsClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-alpha-ids/src/generated/src/operations/alphaIds.ts b/sdk/communication/communication-alpha-ids/src/generated/src/operations/alphaIds.ts index c7bf8f8c49b9..6530ba32edb0 100644 --- a/sdk/communication/communication-alpha-ids/src/generated/src/operations/alphaIds.ts +++ b/sdk/communication/communication-alpha-ids/src/generated/src/operations/alphaIds.ts @@ -6,11 +6,12 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { AlphaIds } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { AlphaIDsClientContext } from "../alphaIDsClientContext"; +import { AlphaIDsClient } from "../alphaIDsClient"; import { AlphaIdsGetConfigurationOptionalParams, AlphaIdsGetConfigurationResponse, @@ -20,13 +21,13 @@ import { /** Class containing AlphaIds operations. */ export class AlphaIdsImpl implements AlphaIds { - private readonly client: AlphaIDsClientContext; + private readonly client: AlphaIDsClient; /** * Initialize a new instance of the class AlphaIds class. * @param client Reference to the service client */ - constructor(client: AlphaIDsClientContext) { + constructor(client: AlphaIDsClient) { this.client = client; } @@ -34,12 +35,18 @@ export class AlphaIdsImpl implements AlphaIds { * Get the Alpha IDs configuration that's applied for the current resource. * @param options The options parameters. */ - getConfiguration( + async getConfiguration( options?: AlphaIdsGetConfigurationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - getConfigurationOperationSpec + return tracingClient.withSpan( + "AlphaIDsClient.getConfiguration", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + getConfigurationOperationSpec + ) as Promise; + } ); } @@ -48,13 +55,19 @@ export class AlphaIdsImpl implements AlphaIds { * @param enabled Indicates whether the use of Alpha IDs is supported for a specific resource. * @param options The options parameters. */ - upsertConfiguration( + async upsertConfiguration( enabled: boolean, options?: AlphaIdsUpsertConfigurationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { enabled, options }, - upsertConfigurationOperationSpec + return tracingClient.withSpan( + "AlphaIDsClient.upsertConfiguration", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { enabled, options }, + upsertConfigurationOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-alpha-ids/src/generated/src/tracing.ts b/sdk/communication/communication-alpha-ids/src/generated/src/tracing.ts new file mode 100644 index 000000000000..34ff4b44c7a2 --- /dev/null +++ b/sdk/communication/communication-alpha-ids/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-alpha-ids", + packageVersion: "1.0.0-beta.2" +}); diff --git a/sdk/communication/communication-alpha-ids/src/utils/constants.ts b/sdk/communication/communication-alpha-ids/src/utils/constants.ts index 47dc16dd0f7c..328eef7797c9 100644 --- a/sdk/communication/communication-alpha-ids/src/utils/constants.ts +++ b/sdk/communication/communication-alpha-ids/src/utils/constants.ts @@ -1,4 +1,4 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -export const SDK_VERSION: string = "1.0.0-beta.1"; +export const SDK_VERSION: string = "1.0.0-beta.2"; diff --git a/sdk/communication/communication-alpha-ids/src/utils/index.ts b/sdk/communication/communication-alpha-ids/src/utils/index.ts index 962243d5a042..22603daf6de5 100644 --- a/sdk/communication/communication-alpha-ids/src/utils/index.ts +++ b/sdk/communication/communication-alpha-ids/src/utils/index.ts @@ -3,4 +3,3 @@ export * from "./constants"; export * from "./logger"; -export * from "./tracing"; diff --git a/sdk/communication/communication-alpha-ids/src/utils/tracing.ts b/sdk/communication/communication-alpha-ids/src/utils/tracing.ts deleted file mode 100644 index 0516f3286dcd..000000000000 --- a/sdk/communication/communication-alpha-ids/src/utils/tracing.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createTracingClient } from "@azure/core-tracing"; -import { SDK_VERSION } from "./constants"; - -/** - * @internal - */ -export const tracingClient = createTracingClient({ - packageName: "Azure.Communication", - namespace: "Microsoft.Communication", - packageVersion: SDK_VERSION, -}); diff --git a/sdk/communication/communication-alpha-ids/swagger/README.md b/sdk/communication/communication-alpha-ids/swagger/README.md index 00799ab8d4f0..c334f91fc4e7 100644 --- a/sdk/communication/communication-alpha-ids/swagger/README.md +++ b/sdk/communication/communication-alpha-ids/swagger/README.md @@ -7,20 +7,25 @@ ```yaml package-name: "@azure/communication-alpha-ids" description: Alpha IDs administration client -package-version: 1.0.0-beta.1 -generate-metadata: false +package-version: 1.0.0-beta.2 license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated input-file: ./alphaids.json model-date-time-as-string: false optional-response-headers: true payload-flattening-threshold: 10 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" add-credentials: false -azure-arm: false skip-enum-validation: true title: Alpha IDs Client +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` ## Customizations diff --git a/sdk/communication/communication-chat/CHANGELOG.md b/sdk/communication/communication-chat/CHANGELOG.md index 5b8268011dc3..147537aa7a65 100644 --- a/sdk/communication/communication-chat/CHANGELOG.md +++ b/sdk/communication/communication-chat/CHANGELOG.md @@ -1,5 +1,17 @@ # Release History +## 1.2.3 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.2.2 (Unreleased) ### Features Added diff --git a/sdk/communication/communication-chat/package.json b/sdk/communication/communication-chat/package.json index 393a94667935..e87ba32809d5 100644 --- a/sdk/communication/communication-chat/package.json +++ b/sdk/communication/communication-chat/package.json @@ -1,6 +1,6 @@ { "name": "@azure/communication-chat", - "version": "1.2.2", + "version": "1.2.3", "description": "Azure client library for Azure Communication Chat services", "sdk-type": "client", "main": "dist/index.js", @@ -69,7 +69,7 @@ "@azure/core-client": "^1.3.0", "@azure/core-paging": "^1.1.1", "@azure/core-rest-pipeline": "^1.3.0", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0", diff --git a/sdk/communication/communication-chat/src/chatClient.ts b/sdk/communication/communication-chat/src/chatClient.ts index f6bce14a546c..01a0242f9003 100644 --- a/sdk/communication/communication-chat/src/chatClient.ts +++ b/sdk/communication/communication-chat/src/chatClient.ts @@ -36,12 +36,11 @@ import { CreateChatThreadRequest } from "./models/requests"; import { EventEmitter } from "events"; import { InternalPipelineOptions } from "@azure/core-rest-pipeline"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; -import { SpanStatusCode } from "@azure/core-tracing"; import { createCommunicationTokenCredentialPolicy } from "./credential/communicationTokenCredentialPolicy"; -import { createSpan } from "./tracing"; import { generateUuid } from "./models/uuid"; import { getSignalingClient } from "./signaling/signalingClient"; import { logger } from "./models/logger"; +import { tracingClient } from "./generated/src/tracing"; /** * The client to do chat operations @@ -111,32 +110,26 @@ export class ChatClient { request: CreateChatThreadRequest, options: CreateChatThreadOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatClient-CreateChatThread", options); - - try { - // We generate an UUID if the user does not provide an idempotencyToken value - updatedOptions.idempotencyToken = updatedOptions.idempotencyToken ?? generateUuid(); - const updatedRestModelOptions = mapToCreateChatThreadOptionsRestModel(updatedOptions); - - const result = await this.client.chat.createChatThread( - { - topic: request.topic, - participants: options.participants?.map((participant) => - mapToChatParticipantRestModel(participant) - ), - }, - updatedRestModelOptions - ); - return mapToCreateChatThreadResultSdkModel(result); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatClient-CreateChatThread", + options, + async (updatedOptions) => { + // We generate an UUID if the user does not provide an idempotencyToken value + updatedOptions.idempotencyToken = updatedOptions.idempotencyToken ?? generateUuid(); + const updatedRestModelOptions = mapToCreateChatThreadOptionsRestModel(updatedOptions); + + const result = await this.client.chat.createChatThread( + { + topic: request.topic, + participants: options.participants?.map((participant) => + mapToChatParticipantRestModel(participant) + ), + }, + updatedRestModelOptions + ); + return mapToCreateChatThreadResultSdkModel(result); + } + ); } private async *listChatThreadsPage( @@ -180,7 +173,7 @@ export class ChatClient { public listChatThreads( options: ListChatThreadsOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ChatClient-ListChatThreads", options); + const { span, updatedOptions } = tracingClient.startSpan("ChatClient-ListChatThreads", options); try { const iter = this.listChatThreadsAll(updatedOptions); return { @@ -196,8 +189,8 @@ export class ChatClient { }; } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + error: e, + status: "error", }); throw e; } finally { @@ -214,19 +207,13 @@ export class ChatClient { threadId: string, options: DeleteChatThreadOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatClient-DeleteChatThread", options); - - try { - await this.client.chat.deleteChatThread(threadId, updatedOptions); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatClient-DeleteChatThread", + options, + async (updatedOptions) => { + await this.client.chat.deleteChatThread(threadId, updatedOptions); + } + ); } /** diff --git a/sdk/communication/communication-chat/src/chatThreadClient.ts b/sdk/communication/communication-chat/src/chatThreadClient.ts index 82b267c8f70d..c57950a04f45 100644 --- a/sdk/communication/communication-chat/src/chatThreadClient.ts +++ b/sdk/communication/communication-chat/src/chatThreadClient.ts @@ -8,8 +8,6 @@ import { serializeCommunicationIdentifier, } from "@azure/communication-common"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; -import { SpanStatusCode } from "@azure/core-tracing"; -import { createSpan } from "./tracing"; import { AddParticipantsRequest, SendMessageRequest, @@ -49,8 +47,10 @@ import { UpdateTopicOptions, } from "./models/options"; import { ChatApiClient } from "./generated/src"; -import { createCommunicationTokenCredentialPolicy } from "./credential/communicationTokenCredentialPolicy"; import { InternalPipelineOptions } from "@azure/core-rest-pipeline"; +import { createCommunicationTokenCredentialPolicy } from "./credential/communicationTokenCredentialPolicy"; +import { tracingClient } from "./generated/src/tracing"; + const minimumTypingIntervalInMilliSeconds: number = 8000; /** @@ -99,24 +99,14 @@ export class ChatThreadClient { * Returns the chat thread. * @param options - Operation options. */ - public async getProperties(options: GetPropertiesOptions = {}): Promise { - const { span, updatedOptions } = createSpan("ChatClient-GetProperties", options); - - try { + public getProperties(options: GetPropertiesOptions = {}): Promise { + return tracingClient.withSpan("ChatClient-GetProperties", options, async (updatedOptions) => { const result = await this.client.chatThread.getChatThreadProperties( this.threadId, updatedOptions ); return mapToChatThreadPropertiesSdkModel(result); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + }); } /** @@ -124,24 +114,18 @@ export class ChatThreadClient { * @param topic - The topic needs to be updated to. * @param options - Operation options. */ - public async updateTopic(topic: string, options: UpdateTopicOptions = {}): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-UpdateTopic", options); - - try { - await this.client.chatThread.updateChatThreadProperties( - this.threadId, - { topic: topic }, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + public updateTopic(topic: string, options: UpdateTopicOptions = {}): Promise { + return tracingClient.withSpan( + "ChatThreadClient-UpdateTopic", + options, + async (updatedOptions) => { + await this.client.chatThread.updateChatThreadProperties( + this.threadId, + { topic: topic }, + updatedOptions + ); + } + ); } /** @@ -150,31 +134,25 @@ export class ChatThreadClient { * @param request - Request for sending a message. * @param options - Operation options. */ - public async sendMessage( + public sendMessage( request: SendMessageRequest, options: SendMessageOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-SendMessage", options); - - try { - // reset typing notification clock - this.timeOfLastTypingRequest = undefined; - - const result = await this.client.chatThread.sendChatMessage( - this.threadId, - { ...request, ...options }, - updatedOptions - ); - return result; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatThreadClient-SendMessage", + options, + async (updatedOptions) => { + // reset typing notification clock + this.timeOfLastTypingRequest = undefined; + + const result = await this.client.chatThread.sendChatMessage( + this.threadId, + { ...request, ...options }, + updatedOptions + ); + return result; + } + ); } /** @@ -183,28 +161,19 @@ export class ChatThreadClient { * @param messageId - The message id of the message. * @param options - Operation options. */ - public async getMessage( - messageId: string, - options: GetMessageOptions = {} - ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-GetMessage", options); - - try { - const result = await this.client.chatThread.getChatMessage( - this.threadId, - messageId, - updatedOptions - ); - return mapToChatMessageSdkModel(result); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + public getMessage(messageId: string, options: GetMessageOptions = {}): Promise { + return tracingClient.withSpan( + "ChatThreadClient-GetMessage", + options, + async (updatedOptions) => { + const result = await this.client.chatThread.getChatMessage( + this.threadId, + messageId, + updatedOptions + ); + return mapToChatMessageSdkModel(result); + } + ); } private async *listMessagesPage( @@ -249,7 +218,10 @@ export class ChatThreadClient { * @param options - Get messages options. */ public listMessages(options: ListMessagesOptions = {}): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ChatThreadClient-ListMessages", options); + const { span, updatedOptions } = tracingClient.startSpan( + "ChatThreadClient-ListMessages", + options + ); try { const iter = this.listMessagesAll(updatedOptions); @@ -266,8 +238,8 @@ export class ChatThreadClient { }; } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { @@ -280,20 +252,14 @@ export class ChatThreadClient { * @param messageId - The message id of the message. * @param options - Operation options. */ - public async deleteMessage(messageId: string, options: DeleteMessageOptions = {}): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-DeleteMessage", options); - - try { - await this.client.chatThread.deleteChatMessage(this.threadId, messageId, updatedOptions); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + public deleteMessage(messageId: string, options: DeleteMessageOptions = {}): Promise { + return tracingClient.withSpan( + "ChatThreadClient-DeleteMessage", + options, + async (updatedOptions) => { + await this.client.chatThread.deleteChatMessage(this.threadId, messageId, updatedOptions); + } + ); } /** @@ -302,24 +268,18 @@ export class ChatThreadClient { * @param options - Operation options. */ public async updateMessage(messageId: string, options: UpdateMessageOptions = {}): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-UpdateMessage", options); - - try { - await this.client.chatThread.updateChatMessage( - this.threadId, - messageId, - options, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatThreadClient-UpdateMessage", + options, + async (updatedOptions) => { + await this.client.chatThread.updateChatMessage( + this.threadId, + messageId, + options, + updatedOptions + ); + } + ); } /** @@ -331,24 +291,18 @@ export class ChatThreadClient { request: AddParticipantsRequest, options: AddParticipantsOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-AddParticipants", options); - - try { - const result = await this.client.chatThread.addChatParticipants( - this.threadId, - mapToAddChatParticipantsRequestRestModel(request), - updatedOptions - ); - return result; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatThreadClient-AddParticipants", + options, + async (updatedOptions) => { + const result = await this.client.chatThread.addChatParticipants( + this.threadId, + mapToAddChatParticipantsRequestRestModel(request), + updatedOptions + ); + return result; + } + ); } private async *listParticipantsPage( @@ -397,7 +351,10 @@ export class ChatThreadClient { public listParticipants( options: ListParticipantsOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ChatThreadClient-ListParticipants", options); + const { span, updatedOptions } = tracingClient.startSpan( + "ChatThreadClient-ListParticipants", + options + ); try { const iter = this.listParticipantsAll(updatedOptions); @@ -414,8 +371,8 @@ export class ChatThreadClient { }; } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { @@ -432,23 +389,17 @@ export class ChatThreadClient { participant: CommunicationIdentifier, options: RemoveParticipantOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-RemoveParticipant", options); - - try { - await this.client.chatThread.removeChatParticipant( - this.threadId, - serializeCommunicationIdentifier(participant), - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatThreadClient-RemoveParticipant", + options, + async (updatedOptions) => { + await this.client.chatThread.removeChatParticipant( + this.threadId, + serializeCommunicationIdentifier(participant), + updatedOptions + ); + } + ); } /** @@ -460,38 +411,31 @@ export class ChatThreadClient { public async sendTypingNotification( options: SendTypingNotificationOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-SendTypingNotification", options); - - try { - const dateNow = new Date(); - const { senderDisplayName, ...restOptions } = updatedOptions; - - if (this.canPostTypingNotification(dateNow)) { - this.timeOfLastTypingRequest = dateNow; - - await this.client.chatThread.sendTypingNotification(this.threadId, { - sendTypingNotificationRequest: { senderDisplayName: senderDisplayName }, - ...restOptions, - }); - return true; + return tracingClient.withSpan( + "ChatThreadClient-SendTypingNotification", + options, + async (updatedOptions) => { + const dateNow = new Date(); + const { senderDisplayName, ...restOptions } = updatedOptions; + + if (this.canPostTypingNotification(dateNow)) { + this.timeOfLastTypingRequest = dateNow; + + await this.client.chatThread.sendTypingNotification(this.threadId, { + sendTypingNotificationRequest: { senderDisplayName: senderDisplayName }, + ...restOptions, + }); + return true; + } + + logger.info(`Typing Notification NOT Send. [thread_id=${this.threadId}]`); + return false; } - - logger.info(`Typing Notification NOT Send. [thread_id=${this.threadId}]`); - return false; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + ); } /** * Sends a read receipt to the thread identified by threadId. - * @param messageId - The message id of the message that user latest read. * @param request - Request for sending a read receipt * @param options - Operation options. */ @@ -499,19 +443,13 @@ export class ChatThreadClient { request: SendReadReceiptRequest, options: SendReadReceiptOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ChatThreadClient-SendReadReceipt", options); - - try { - await this.client.chatThread.sendChatReadReceipt(this.threadId, request, updatedOptions); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ChatThreadClient-SendReadReceipt", + options, + async (updatedOptions) => { + await this.client.chatThread.sendChatReadReceipt(this.threadId, request, updatedOptions); + } + ); } private async *listReadReceiptsPage( @@ -560,7 +498,10 @@ export class ChatThreadClient { public listReadReceipts( options: ListReadReceiptsOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ChatThreadClient-ListChatReadReceipts", options); + const { span, updatedOptions } = tracingClient.startSpan( + "ChatThreadClient-ListChatReadReceipts", + options + ); try { const iter = this.listReadReceiptsAll(updatedOptions); @@ -577,8 +518,8 @@ export class ChatThreadClient { }; } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { diff --git a/sdk/communication/communication-chat/src/generated/src/chatApiClient.ts b/sdk/communication/communication-chat/src/generated/src/chatApiClient.ts index 1f3bf765f741..b9fbd3505ded 100644 --- a/sdk/communication/communication-chat/src/generated/src/chatApiClient.ts +++ b/sdk/communication/communication-chat/src/generated/src/chatApiClient.ts @@ -7,6 +7,11 @@ */ import * as coreClient from "@azure/core-client"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { ChatThreadImpl, ChatImpl } from "./operations"; import { ChatThread, Chat } from "./operationsInterfaces"; import { ChatApiClientOptionalParams } from "./models"; @@ -33,7 +38,7 @@ export class ChatApiClient extends coreClient.ServiceClient { requestContentType: "application/json; charset=utf-8" }; - const packageDetails = `azsdk-js-communication-chat/1.2.0`; + const packageDetails = `azsdk-js-communication-chat/1.2.3`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` @@ -55,6 +60,35 @@ export class ChatApiClient extends coreClient.ServiceClient { this.apiVersion = options.apiVersion || "2021-09-07"; this.chatThread = new ChatThreadImpl(this); this.chat = new ChatImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } chatThread: ChatThread; diff --git a/sdk/communication/communication-chat/src/generated/src/chatApiClientContext.ts b/sdk/communication/communication-chat/src/generated/src/chatApiClientContext.ts deleted file mode 100644 index 7b0039756256..000000000000 --- a/sdk/communication/communication-chat/src/generated/src/chatApiClientContext.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { ChatApiClientOptionalParams } from "./models"; - -export class ChatApiClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the ChatApiClientContext class. - * @param endpoint The endpoint of the Azure Communication resource. - * @param options The parameter options - */ - constructor(endpoint: string, options?: ChatApiClientOptionalParams) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: ChatApiClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-azure-communication-chat/1.2.2`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2021-09-07"; - } -} diff --git a/sdk/communication/communication-chat/src/generated/src/models/index.ts b/sdk/communication/communication-chat/src/generated/src/models/index.ts index 315c076f6edb..c89015c5df9f 100644 --- a/sdk/communication/communication-chat/src/generated/src/models/index.ts +++ b/sdk/communication/communication-chat/src/generated/src/models/index.ts @@ -282,8 +282,11 @@ export interface SendTypingNotificationRequest { /** Known values of {@link CommunicationCloudEnvironmentModel} that the service accepts. */ export enum KnownCommunicationCloudEnvironmentModel { + /** Public */ Public = "public", + /** Dod */ Dod = "dod", + /** Gcch */ Gcch = "gcch" } @@ -331,7 +334,7 @@ export type ChatThreadSendChatMessageResponse = SendChatMessageResult; /** Optional parameters. */ export interface ChatThreadListChatMessagesOptionalParams extends coreClient.OperationOptions { - /** The maximum number of messages to be returned per page. The limit can be found from https://docs.microsoft.com/en-us/azure/communication-services/concepts/service-limits.*/ + /** The maximum number of messages to be returned per page. */ maxPageSize?: number; /** The earliest point in time to get messages up to. The timestamp should be in RFC3339 format: `yyyy-MM-ddTHH:mm:ssZ`. */ startTime?: Date; @@ -411,7 +414,7 @@ export type ChatThreadListChatReadReceiptsNextResponse = ChatMessageReadReceipts /** Optional parameters. */ export interface ChatThreadListChatMessagesNextOptionalParams extends coreClient.OperationOptions { - /** The maximum number of messages to be returned per page. The limit can be found from https://docs.microsoft.com/en-us/azure/communication-services/concepts/service-limits.*/ + /** The maximum number of messages to be returned per page. */ maxPageSize?: number; /** The earliest point in time to get messages up to. The timestamp should be in RFC3339 format: `yyyy-MM-ddTHH:mm:ssZ`. */ startTime?: Date; diff --git a/sdk/communication/communication-chat/src/generated/src/operations/chat.ts b/sdk/communication/communication-chat/src/generated/src/operations/chat.ts index 18ab9eb003a0..510ccadfbf66 100644 --- a/sdk/communication/communication-chat/src/generated/src/operations/chat.ts +++ b/sdk/communication/communication-chat/src/generated/src/operations/chat.ts @@ -6,6 +6,7 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { Chat } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; @@ -39,13 +40,19 @@ export class ChatImpl implements Chat { * @param createChatThreadRequest Request payload for creating a chat thread. * @param options The options parameters. */ - createChatThread( + async createChatThread( createChatThreadRequest: CreateChatThreadRequest, options?: ChatCreateChatThreadOptionalParams ): Promise { - return this.client.sendOperationRequest( - { createChatThreadRequest, options }, - createChatThreadOperationSpec + return tracingClient.withSpan( + "ChatApiClient.createChatThread", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { createChatThreadRequest, options }, + createChatThreadOperationSpec + ) as Promise; + } ); } @@ -53,12 +60,18 @@ export class ChatImpl implements Chat { * Gets the list of chat threads of a user. * @param options The options parameters. */ - listChatThreads( + async listChatThreads( options?: ChatListChatThreadsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - listChatThreadsOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatThreads", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + listChatThreadsOperationSpec + ) as Promise; + } ); } @@ -67,13 +80,19 @@ export class ChatImpl implements Chat { * @param chatThreadId Id of the thread to be deleted. * @param options The options parameters. */ - deleteChatThread( + async deleteChatThread( chatThreadId: string, options?: ChatDeleteChatThreadOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - deleteChatThreadOperationSpec + return tracingClient.withSpan( + "ChatApiClient.deleteChatThread", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + deleteChatThreadOperationSpec + ) as Promise; + } ); } @@ -82,13 +101,19 @@ export class ChatImpl implements Chat { * @param nextLink The nextLink from the previous successful call to the ListChatThreads method. * @param options The options parameters. */ - listChatThreadsNext( + async listChatThreadsNext( nextLink: string, options?: ChatListChatThreadsNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { nextLink, options }, - listChatThreadsNextOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatThreadsNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { nextLink, options }, + listChatThreadsNextOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-chat/src/generated/src/operations/chatThread.ts b/sdk/communication/communication-chat/src/generated/src/operations/chatThread.ts index 123ab9aafb4a..315bfd6d6a5d 100644 --- a/sdk/communication/communication-chat/src/generated/src/operations/chatThread.ts +++ b/sdk/communication/communication-chat/src/generated/src/operations/chatThread.ts @@ -6,6 +6,7 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { ChatThread } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; @@ -63,13 +64,19 @@ export class ChatThreadImpl implements ChatThread { * @param chatThreadId Thread id to get the chat message read receipts for. * @param options The options parameters. */ - listChatReadReceipts( + async listChatReadReceipts( chatThreadId: string, options?: ChatThreadListChatReadReceiptsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - listChatReadReceiptsOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatReadReceipts", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + listChatReadReceiptsOperationSpec + ) as Promise; + } ); } @@ -79,14 +86,20 @@ export class ChatThreadImpl implements ChatThread { * @param sendReadReceiptRequest Read receipt details. * @param options The options parameters. */ - sendChatReadReceipt( + async sendChatReadReceipt( chatThreadId: string, sendReadReceiptRequest: SendReadReceiptRequest, options?: ChatThreadSendChatReadReceiptOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, sendReadReceiptRequest, options }, - sendChatReadReceiptOperationSpec + return tracingClient.withSpan( + "ChatApiClient.sendChatReadReceipt", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, sendReadReceiptRequest, options }, + sendChatReadReceiptOperationSpec + ) as Promise; + } ); } @@ -96,14 +109,20 @@ export class ChatThreadImpl implements ChatThread { * @param sendChatMessageRequest Details of the message to send. * @param options The options parameters. */ - sendChatMessage( + async sendChatMessage( chatThreadId: string, sendChatMessageRequest: SendChatMessageRequest, options?: ChatThreadSendChatMessageOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, sendChatMessageRequest, options }, - sendChatMessageOperationSpec + return tracingClient.withSpan( + "ChatApiClient.sendChatMessage", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, sendChatMessageRequest, options }, + sendChatMessageOperationSpec + ) as Promise; + } ); } @@ -112,13 +131,19 @@ export class ChatThreadImpl implements ChatThread { * @param chatThreadId The thread id of the message. * @param options The options parameters. */ - listChatMessages( + async listChatMessages( chatThreadId: string, options?: ChatThreadListChatMessagesOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - listChatMessagesOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatMessages", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + listChatMessagesOperationSpec + ) as Promise; + } ); } @@ -128,14 +153,20 @@ export class ChatThreadImpl implements ChatThread { * @param chatMessageId The message id. * @param options The options parameters. */ - getChatMessage( + async getChatMessage( chatThreadId: string, chatMessageId: string, options?: ChatThreadGetChatMessageOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, chatMessageId, options }, - getChatMessageOperationSpec + return tracingClient.withSpan( + "ChatApiClient.getChatMessage", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, chatMessageId, options }, + getChatMessageOperationSpec + ) as Promise; + } ); } @@ -146,15 +177,21 @@ export class ChatThreadImpl implements ChatThread { * @param updateChatMessageRequest Details of the request to update the message. * @param options The options parameters. */ - updateChatMessage( + async updateChatMessage( chatThreadId: string, chatMessageId: string, updateChatMessageRequest: UpdateChatMessageRequest, options?: ChatThreadUpdateChatMessageOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, chatMessageId, updateChatMessageRequest, options }, - updateChatMessageOperationSpec + return tracingClient.withSpan( + "ChatApiClient.updateChatMessage", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, chatMessageId, updateChatMessageRequest, options }, + updateChatMessageOperationSpec + ) as Promise; + } ); } @@ -164,14 +201,20 @@ export class ChatThreadImpl implements ChatThread { * @param chatMessageId The message id. * @param options The options parameters. */ - deleteChatMessage( + async deleteChatMessage( chatThreadId: string, chatMessageId: string, options?: ChatThreadDeleteChatMessageOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, chatMessageId, options }, - deleteChatMessageOperationSpec + return tracingClient.withSpan( + "ChatApiClient.deleteChatMessage", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, chatMessageId, options }, + deleteChatMessageOperationSpec + ) as Promise; + } ); } @@ -180,13 +223,19 @@ export class ChatThreadImpl implements ChatThread { * @param chatThreadId Thread id to get participants for. * @param options The options parameters. */ - listChatParticipants( + async listChatParticipants( chatThreadId: string, options?: ChatThreadListChatParticipantsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - listChatParticipantsOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatParticipants", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + listChatParticipantsOperationSpec + ) as Promise; + } ); } @@ -196,14 +245,20 @@ export class ChatThreadImpl implements ChatThread { * @param participantCommunicationIdentifier Id of the thread participant to remove from the thread. * @param options The options parameters. */ - removeChatParticipant( + async removeChatParticipant( chatThreadId: string, participantCommunicationIdentifier: CommunicationIdentifierModel, options?: ChatThreadRemoveChatParticipantOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, participantCommunicationIdentifier, options }, - removeChatParticipantOperationSpec + return tracingClient.withSpan( + "ChatApiClient.removeChatParticipant", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, participantCommunicationIdentifier, options }, + removeChatParticipantOperationSpec + ) as Promise; + } ); } @@ -213,14 +268,20 @@ export class ChatThreadImpl implements ChatThread { * @param addChatParticipantsRequest Thread participants to be added to the thread. * @param options The options parameters. */ - addChatParticipants( + async addChatParticipants( chatThreadId: string, addChatParticipantsRequest: AddChatParticipantsRequest, options?: ChatThreadAddChatParticipantsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, addChatParticipantsRequest, options }, - addChatParticipantsOperationSpec + return tracingClient.withSpan( + "ChatApiClient.addChatParticipants", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, addChatParticipantsRequest, options }, + addChatParticipantsOperationSpec + ) as Promise; + } ); } @@ -230,14 +291,20 @@ export class ChatThreadImpl implements ChatThread { * @param updateChatThreadRequest Request payload for updating a chat thread. * @param options The options parameters. */ - updateChatThreadProperties( + async updateChatThreadProperties( chatThreadId: string, updateChatThreadRequest: UpdateChatThreadRequest, options?: ChatThreadUpdateChatThreadPropertiesOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, updateChatThreadRequest, options }, - updateChatThreadPropertiesOperationSpec + return tracingClient.withSpan( + "ChatApiClient.updateChatThreadProperties", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, updateChatThreadRequest, options }, + updateChatThreadPropertiesOperationSpec + ) as Promise; + } ); } @@ -246,13 +313,19 @@ export class ChatThreadImpl implements ChatThread { * @param chatThreadId Id of the thread. * @param options The options parameters. */ - getChatThreadProperties( + async getChatThreadProperties( chatThreadId: string, options?: ChatThreadGetChatThreadPropertiesOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - getChatThreadPropertiesOperationSpec + return tracingClient.withSpan( + "ChatApiClient.getChatThreadProperties", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + getChatThreadPropertiesOperationSpec + ) as Promise; + } ); } @@ -261,13 +334,19 @@ export class ChatThreadImpl implements ChatThread { * @param chatThreadId Id of the thread. * @param options The options parameters. */ - sendTypingNotification( + async sendTypingNotification( chatThreadId: string, options?: ChatThreadSendTypingNotificationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, options }, - sendTypingNotificationOperationSpec + return tracingClient.withSpan( + "ChatApiClient.sendTypingNotification", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, options }, + sendTypingNotificationOperationSpec + ) as Promise; + } ); } @@ -277,14 +356,20 @@ export class ChatThreadImpl implements ChatThread { * @param nextLink The nextLink from the previous successful call to the ListChatReadReceipts method. * @param options The options parameters. */ - listChatReadReceiptsNext( + async listChatReadReceiptsNext( chatThreadId: string, nextLink: string, options?: ChatThreadListChatReadReceiptsNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, nextLink, options }, - listChatReadReceiptsNextOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatReadReceiptsNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, nextLink, options }, + listChatReadReceiptsNextOperationSpec + ) as Promise; + } ); } @@ -294,14 +379,20 @@ export class ChatThreadImpl implements ChatThread { * @param nextLink The nextLink from the previous successful call to the ListChatMessages method. * @param options The options parameters. */ - listChatMessagesNext( + async listChatMessagesNext( chatThreadId: string, nextLink: string, options?: ChatThreadListChatMessagesNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, nextLink, options }, - listChatMessagesNextOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatMessagesNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, nextLink, options }, + listChatMessagesNextOperationSpec + ) as Promise; + } ); } @@ -311,14 +402,20 @@ export class ChatThreadImpl implements ChatThread { * @param nextLink The nextLink from the previous successful call to the ListChatParticipants method. * @param options The options parameters. */ - listChatParticipantsNext( + async listChatParticipantsNext( chatThreadId: string, nextLink: string, options?: ChatThreadListChatParticipantsNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { chatThreadId, nextLink, options }, - listChatParticipantsNextOperationSpec + return tracingClient.withSpan( + "ChatApiClient.listChatParticipantsNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { chatThreadId, nextLink, options }, + listChatParticipantsNextOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-chat/src/generated/src/tracing.ts b/sdk/communication/communication-chat/src/generated/src/tracing.ts new file mode 100644 index 000000000000..a7f5defee311 --- /dev/null +++ b/sdk/communication/communication-chat/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Azure.Communication", + packageName: "@azure/communication-chat", + packageVersion: "1.2.3" +}); diff --git a/sdk/communication/communication-chat/src/tracing.ts b/sdk/communication/communication-chat/src/tracing.ts deleted file mode 100644 index a5dc8130b8cd..000000000000 --- a/sdk/communication/communication-chat/src/tracing.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-chat/swagger/README.md b/sdk/communication/communication-chat/swagger/README.md index 08460e22a8af..5c88fdd22405 100644 --- a/sdk/communication/communication-chat/swagger/README.md +++ b/sdk/communication/communication-chat/swagger/README.md @@ -8,18 +8,24 @@ package-name: "@azure/communication-chat" title: ChatApiClient description: Chat Client -generate-metadata: false license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated tag: package-chat-2021-09-07 require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/communication/data-plane/Chat/readme.md model-date-time-as-string: false optional-response-headers: true -typescript: true -azure-arm: false add-credentials: false disable-async-iterators: true -package-version: 1.2.2 +package-version: 1.2.3 +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Azure.Communication" + packagePrefix: "Microsoft.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` ### Rename CommunicationError to ChatError diff --git a/sdk/communication/communication-common/CHANGELOG.md b/sdk/communication/communication-common/CHANGELOG.md index d97687f8bcc4..f9113a860603 100644 --- a/sdk/communication/communication-common/CHANGELOG.md +++ b/sdk/communication/communication-common/CHANGELOG.md @@ -10,6 +10,8 @@ ### Other Changes +- Updated to `@azure/core-tracing` 1.0. + ## 2.1.0 (2022-08-02) ### Features Added diff --git a/sdk/communication/communication-common/package.json b/sdk/communication/communication-common/package.json index 434ac7dc8d47..4fa39148d991 100644 --- a/sdk/communication/communication-common/package.json +++ b/sdk/communication/communication-common/package.json @@ -65,7 +65,7 @@ "@azure/abort-controller": "^1.0.0", "@azure/core-auth": "^1.3.0", "@azure/core-rest-pipeline": "^1.3.2", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/core-util": "^1.0.0", "events": "^3.0.0", "jwt-decode": "^3.1.2", diff --git a/sdk/communication/communication-identity/CHANGELOG.md b/sdk/communication/communication-identity/CHANGELOG.md index dd49ffdc3ebb..8a5de954ce64 100644 --- a/sdk/communication/communication-identity/CHANGELOG.md +++ b/sdk/communication/communication-identity/CHANGELOG.md @@ -10,6 +10,8 @@ ### Other Changes +- Updated to `@azure/core-tracing` 1.0. + ## 1.1.0 (2022-07-21) ### Features Added diff --git a/sdk/communication/communication-identity/package.json b/sdk/communication/communication-identity/package.json index 102b113b8ce3..d2eaab0902c1 100644 --- a/sdk/communication/communication-identity/package.json +++ b/sdk/communication/communication-identity/package.json @@ -94,7 +94,7 @@ "@azure/core-rest-pipeline": "^1.3.0", "@azure/core-lro": "^2.2.0", "@azure/core-paging": "^1.1.1", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0" diff --git a/sdk/communication/communication-identity/src/common/tracing.ts b/sdk/communication/communication-identity/src/common/tracing.ts deleted file mode 100644 index a5dc8130b8cd..000000000000 --- a/sdk/communication/communication-identity/src/common/tracing.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-identity/src/communicationIdentityClient.ts b/sdk/communication/communication-identity/src/communicationIdentityClient.ts index 0a602dd3f603..9416ca1ae87f 100644 --- a/sdk/communication/communication-identity/src/communicationIdentityClient.ts +++ b/sdk/communication/communication-identity/src/communicationIdentityClient.ts @@ -17,9 +17,8 @@ import { import { InternalClientPipelineOptions, OperationOptions } from "@azure/core-client"; import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; import { IdentityRestClient } from "./generated/src/identityRestClient"; -import { SpanStatusCode } from "@azure/core-tracing"; -import { createSpan } from "./common/tracing"; import { logger } from "./common/logger"; +import { tracingClient } from "./generated/src/tracing"; const isCommunicationIdentityClientOptions = ( options: any @@ -101,27 +100,18 @@ export class CommunicationIdentityClient { * @param scopes - Scopes to include in the token. * @param options - Additional options for the request. */ - public async getToken( + public getToken( user: CommunicationUserIdentifier, scopes: TokenScope[], options: OperationOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("CommunicationIdentity-issueToken", options); - try { - return await this.client.communicationIdentityOperations.issueAccessToken( + return tracingClient.withSpan("CommunicationIdentity-issueToken", options, (updatedOptions) => { + return this.client.communicationIdentityOperations.issueAccessToken( user.communicationUserId, scopes, updatedOptions ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + }); } /** @@ -130,25 +120,20 @@ export class CommunicationIdentityClient { * @param user - The user whose tokens are being revoked. * @param options - Additional options for the request. */ - public async revokeTokens( + public revokeTokens( user: CommunicationUserIdentifier, options: OperationOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("CommunicationIdentity-revokeTokens", options); - try { - await this.client.communicationIdentityOperations.revokeAccessTokens( - user.communicationUserId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "CommunicationIdentity-revokeTokens", + options, + async (updatedOptions) => { + await this.client.communicationIdentityOperations.revokeAccessTokens( + user.communicationUserId, + updatedOptions + ); + } + ); } /** @@ -156,22 +141,17 @@ export class CommunicationIdentityClient { * * @param options - Additional options for the request. */ - public async createUser(options: OperationOptions = {}): Promise { - const { span, updatedOptions } = createSpan("CommunicationIdentity-createUser", options); - try { - const result = await this.client.communicationIdentityOperations.create(updatedOptions); - return { - communicationUserId: result.identity.id, - }; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + public createUser(options: OperationOptions = {}): Promise { + return tracingClient.withSpan( + "CommunicationIdentity-createUser", + options, + async (updatedOptions) => { + const result = await this.client.communicationIdentityOperations.create(updatedOptions); + return { + communicationUserId: result.identity.id, + }; + } + ); } /** @@ -180,32 +160,24 @@ export class CommunicationIdentityClient { * @param scopes - Scopes to include in the token. * @param options - Additional options for the request. */ - public async createUserAndToken( + public createUserAndToken( scopes: TokenScope[], options: OperationOptions = {} ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "CommunicationIdentity-createUserAndToken", - options + options, + async (updatedOptions) => { + const { identity, accessToken } = await this.client.communicationIdentityOperations.create({ + createTokenWithScopes: scopes, + ...updatedOptions, + }); + return { + ...accessToken!, + user: { communicationUserId: identity.id }, + }; + } ); - try { - const { identity, accessToken } = await this.client.communicationIdentityOperations.create({ - createTokenWithScopes: scopes, - ...updatedOptions, - }); - return { - ...accessToken!, - user: { communicationUserId: identity.id }, - }; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } /** @@ -214,25 +186,20 @@ export class CommunicationIdentityClient { * @param user - The user being deleted. * @param options - Additional options for the request. */ - public async deleteUser( + public deleteUser( user: CommunicationUserIdentifier, options: OperationOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("CommunicationIdentity-deleteUser", options); - try { - await this.client.communicationIdentityOperations.delete( - user.communicationUserId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "CommunicationIdentity-deleteUser", + options, + async (updatedOptions) => { + await this.client.communicationIdentityOperations.delete( + user.communicationUserId, + updatedOptions + ); + } + ); } /** @@ -240,29 +207,21 @@ export class CommunicationIdentityClient { * * @param options - Options used to exchange an Azure AD access token of a Teams user for a new Communication Identity access token. */ - public async getTokenForTeamsUser( + public getTokenForTeamsUser( options: GetTokenForTeamsUserOptions ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "CommunicationIdentity-getTokenForTeamsUser", - options + options, + (updatedOptions) => { + const { teamsUserAadToken, clientId, userObjectId } = updatedOptions; + return this.client.communicationIdentityOperations.exchangeTeamsUserAccessToken( + teamsUserAadToken, + clientId, + userObjectId, + updatedOptions + ); + } ); - const { teamsUserAadToken, clientId, userObjectId } = options; - try { - return await this.client.communicationIdentityOperations.exchangeTeamsUserAccessToken( - teamsUserAadToken, - clientId, - userObjectId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } } diff --git a/sdk/communication/communication-identity/src/generated/src/identityRestClient.ts b/sdk/communication/communication-identity/src/generated/src/identityRestClient.ts index a2fdf3314b68..9232113cbda1 100644 --- a/sdk/communication/communication-identity/src/generated/src/identityRestClient.ts +++ b/sdk/communication/communication-identity/src/generated/src/identityRestClient.ts @@ -6,22 +6,90 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { CommunicationIdentityOperationsImpl } from "./operations"; import { CommunicationIdentityOperations } from "./operationsInterfaces"; -import { IdentityRestClientContext } from "./identityRestClientContext"; import { IdentityRestClientOptionalParams } from "./models"; -export class IdentityRestClient extends IdentityRestClientContext { +export class IdentityRestClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the IdentityRestClient class. * @param endpoint The communication resource, for example https://my-resource.communication.azure.com * @param options The parameter options */ constructor(endpoint: string, options?: IdentityRestClientOptionalParams) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: IdentityRestClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-identity/1.1.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2022-06-01"; this.communicationIdentityOperations = new CommunicationIdentityOperationsImpl( this ); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } communicationIdentityOperations: CommunicationIdentityOperations; diff --git a/sdk/communication/communication-identity/src/generated/src/identityRestClientContext.ts b/sdk/communication/communication-identity/src/generated/src/identityRestClientContext.ts deleted file mode 100644 index 9bf155f50a7d..000000000000 --- a/sdk/communication/communication-identity/src/generated/src/identityRestClientContext.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { IdentityRestClientOptionalParams } from "./models"; - -export class IdentityRestClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the IdentityRestClientContext class. - * @param endpoint The communication resource, for example https://my-resource.communication.azure.com - * @param options The parameter options - */ - constructor(endpoint: string, options?: IdentityRestClientOptionalParams) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: IdentityRestClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-communication-identity/1.1.1`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2022-06-01"; - } -} diff --git a/sdk/communication/communication-identity/src/generated/src/index.ts b/sdk/communication/communication-identity/src/generated/src/index.ts index 316c9f819d4a..47655697cd93 100644 --- a/sdk/communication/communication-identity/src/generated/src/index.ts +++ b/sdk/communication/communication-identity/src/generated/src/index.ts @@ -8,5 +8,4 @@ export * from "./models"; export { IdentityRestClient } from "./identityRestClient"; -export { IdentityRestClientContext } from "./identityRestClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-identity/src/generated/src/models/index.ts b/sdk/communication/communication-identity/src/generated/src/models/index.ts index b30a55fbc9d3..4344a16c9448 100644 --- a/sdk/communication/communication-identity/src/generated/src/models/index.ts +++ b/sdk/communication/communication-identity/src/generated/src/models/index.ts @@ -80,7 +80,9 @@ export interface CommunicationIdentityAccessTokenRequest { /** Known values of {@link CommunicationIdentityTokenScope} that the service accepts. */ export enum KnownCommunicationIdentityTokenScope { + /** Chat */ Chat = "chat", + /** Voip */ Voip = "voip" } diff --git a/sdk/communication/communication-identity/src/generated/src/operations/communicationIdentityOperations.ts b/sdk/communication/communication-identity/src/generated/src/operations/communicationIdentityOperations.ts index b1284d37b189..6ab69dc544c9 100644 --- a/sdk/communication/communication-identity/src/generated/src/operations/communicationIdentityOperations.ts +++ b/sdk/communication/communication-identity/src/generated/src/operations/communicationIdentityOperations.ts @@ -6,11 +6,12 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { CommunicationIdentityOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { IdentityRestClientContext } from "../identityRestClientContext"; +import { IdentityRestClient } from "../identityRestClient"; import { CommunicationIdentityCreateOptionalParams, CommunicationIdentityCreateResponse, @@ -26,13 +27,13 @@ import { /** Class containing CommunicationIdentityOperations operations. */ export class CommunicationIdentityOperationsImpl implements CommunicationIdentityOperations { - private readonly client: IdentityRestClientContext; + private readonly client: IdentityRestClient; /** * Initialize a new instance of the class CommunicationIdentityOperations class. * @param client Reference to the service client */ - constructor(client: IdentityRestClientContext) { + constructor(client: IdentityRestClient) { this.client = client; } @@ -40,10 +41,19 @@ export class CommunicationIdentityOperationsImpl * Create a new identity, and optionally, an access token. * @param options The options parameters. */ - create( + async create( options?: CommunicationIdentityCreateOptionalParams ): Promise { - return this.client.sendOperationRequest({ options }, createOperationSpec); + return tracingClient.withSpan( + "IdentityRestClient.create", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + createOperationSpec + ) as Promise; + } + ); } /** @@ -51,13 +61,19 @@ export class CommunicationIdentityOperationsImpl * @param id Identifier of the identity to be deleted. * @param options The options parameters. */ - delete( + async delete( id: string, options?: CommunicationIdentityDeleteOptionalParams ): Promise { - return this.client.sendOperationRequest( - { id, options }, - deleteOperationSpec + return tracingClient.withSpan( + "IdentityRestClient.delete", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { id, options }, + deleteOperationSpec + ) as Promise; + } ); } @@ -66,13 +82,19 @@ export class CommunicationIdentityOperationsImpl * @param id Identifier of the identity. * @param options The options parameters. */ - revokeAccessTokens( + async revokeAccessTokens( id: string, options?: CommunicationIdentityRevokeAccessTokensOptionalParams ): Promise { - return this.client.sendOperationRequest( - { id, options }, - revokeAccessTokensOperationSpec + return tracingClient.withSpan( + "IdentityRestClient.revokeAccessTokens", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { id, options }, + revokeAccessTokensOperationSpec + ) as Promise; + } ); } @@ -87,15 +109,21 @@ export class CommunicationIdentityOperationsImpl * Azure AD access token. * @param options The options parameters. */ - exchangeTeamsUserAccessToken( + async exchangeTeamsUserAccessToken( token: string, appId: string, userId: string, options?: CommunicationIdentityExchangeTeamsUserAccessTokenOptionalParams ): Promise { - return this.client.sendOperationRequest( - { token, appId, userId, options }, - exchangeTeamsUserAccessTokenOperationSpec + return tracingClient.withSpan( + "IdentityRestClient.exchangeTeamsUserAccessToken", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { token, appId, userId, options }, + exchangeTeamsUserAccessTokenOperationSpec + ) as Promise; + } ); } @@ -105,14 +133,20 @@ export class CommunicationIdentityOperationsImpl * @param scopes List of scopes attached to the token. * @param options The options parameters. */ - issueAccessToken( + async issueAccessToken( id: string, scopes: CommunicationIdentityTokenScope[], options?: CommunicationIdentityIssueAccessTokenOptionalParams ): Promise { - return this.client.sendOperationRequest( - { id, scopes, options }, - issueAccessTokenOperationSpec + return tracingClient.withSpan( + "IdentityRestClient.issueAccessToken", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { id, scopes, options }, + issueAccessTokenOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-identity/src/generated/src/tracing.ts b/sdk/communication/communication-identity/src/generated/src/tracing.ts new file mode 100644 index 000000000000..e664bcc24238 --- /dev/null +++ b/sdk/communication/communication-identity/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-identity", + packageVersion: "1.1.2" +}); diff --git a/sdk/communication/communication-identity/swagger/README.md b/sdk/communication/communication-identity/swagger/README.md index 70d6cade777b..e951fc8c5123 100644 --- a/sdk/communication/communication-identity/swagger/README.md +++ b/sdk/communication/communication-identity/swagger/README.md @@ -9,7 +9,6 @@ package-name: "@azure/communication-identity" override-client-name: IdentityRestClient description: Communication identity client package-version: 1.1.1 -generate-metadata: false license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated tag: package-2022-06 @@ -17,9 +16,16 @@ require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/5b0818f553 model-date-time-as-string: false optional-response-headers: true payload-flattening-threshold: 10 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" add-credentials: false -azure-arm: false v3: true + +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` diff --git a/sdk/communication/communication-network-traversal/CHANGELOG.md b/sdk/communication/communication-network-traversal/CHANGELOG.md index 5ea2b7632285..7abf85c0a3e5 100644 --- a/sdk/communication/communication-network-traversal/CHANGELOG.md +++ b/sdk/communication/communication-network-traversal/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 1.1.0-beta.3 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + ## 1.1.0-beta.2 (2022-04-25) ### Features Added diff --git a/sdk/communication/communication-network-traversal/package.json b/sdk/communication/communication-network-traversal/package.json index 5d8d42b8e084..074b8ec07967 100644 --- a/sdk/communication/communication-network-traversal/package.json +++ b/sdk/communication/communication-network-traversal/package.json @@ -1,6 +1,6 @@ { "name": "@azure/communication-network-traversal", - "version": "1.1.0-beta.2", + "version": "1.1.0-beta.3", "description": "SDK for Azure Communication service which facilitates user token administration.", "sdk-type": "client", "main": "dist/index.js", @@ -92,7 +92,7 @@ "@azure/core-auth": "^1.3.0", "@azure/core-client": "^1.3.0", "@azure/core-rest-pipeline": "^1.3.0", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0" diff --git a/sdk/communication/communication-network-traversal/review/communication-network-traversal.api.md b/sdk/communication/communication-network-traversal/review/communication-network-traversal.api.md index 053b76467aab..1b030f9839e1 100644 --- a/sdk/communication/communication-network-traversal/review/communication-network-traversal.api.md +++ b/sdk/communication/communication-network-traversal/review/communication-network-traversal.api.md @@ -46,9 +46,7 @@ export interface GetRelayConfigurationOptions extends OperationOptions { // @public export enum KnownRouteType { - // (undocumented) Any = "any", - // (undocumented) Nearest = "nearest" } diff --git a/sdk/communication/communication-network-traversal/src/common/tracing.ts b/sdk/communication/communication-network-traversal/src/common/tracing.ts deleted file mode 100644 index a5dc8130b8cd..000000000000 --- a/sdk/communication/communication-network-traversal/src/common/tracing.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-network-traversal/src/communicationRelayClient.ts b/sdk/communication/communication-network-traversal/src/communicationRelayClient.ts index e90fd724b172..f2f0a1221157 100644 --- a/sdk/communication/communication-network-traversal/src/communicationRelayClient.ts +++ b/sdk/communication/communication-network-traversal/src/communicationRelayClient.ts @@ -13,9 +13,8 @@ import { } from "@azure/communication-common"; import { InternalClientPipelineOptions } from "@azure/core-client"; import { NetworkRelayRestClient } from "./generated/src/networkRelayRestClient"; -import { SpanStatusCode } from "@azure/core-tracing"; -import { createSpan } from "./common/tracing"; import { logger } from "./common/logger"; +import { tracingClient } from "./generated/src/tracing"; const isCommunicationRelayClientOptions = ( options: any @@ -64,9 +63,10 @@ export class CommunicationRelayClient { /** * Initializes a new instance of the CommunicationRelayClient class. - * @param connectionString - Connection string to connect to an Azure Communication Service resource. + * @param connectionStringOrEndpoint - Connection string to connect to an Azure Communication Service resource. * Example: "endpoint=https://contoso.eastus.communications.azure.net/;accesskey=secret"; - * @param options - Optional. Options to configure the HTTP pipeline. + * @param credentialOrOptions - TokenCredential that is used to authenticate requests to the service or options to configure the HTTP pipeline. + * @param maybeOptions - Optional. Options to configure the HTTP pipeline. */ public constructor( connectionStringOrEndpoint: string, @@ -104,19 +104,16 @@ export class CommunicationRelayClient { * * @param options - Additional options for the request. */ - public async getRelayConfiguration( + public getRelayConfiguration( options?: GetRelayConfigurationOptions ): Promise; /** * Gets a TURN credential for a user * - * @param user - The user for whom to issue a token - * @param routeType - The specified routeType for the relay request - * @param ttl - The specified time to live for the relay credential in seconds * @param options - Additional options for the request. */ - public async getRelayConfiguration( + public getRelayConfiguration( options: GetRelayConfigurationOptions = {} ): Promise { const requestOptions: CommunicationNetworkTraversalIssueRelayConfigurationOptionalParams = @@ -128,23 +125,12 @@ export class CommunicationRelayClient { requestOptions.ttl = options.ttl; } - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "CommunicationNetworkTraversal_IssueRelayConfiguration", - requestOptions + requestOptions, + (updatedOptions) => { + return this.client.communicationNetworkTraversal.issueRelayConfiguration(updatedOptions); + } ); - - try { - return await this.client.communicationNetworkTraversal.issueRelayConfiguration( - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } } diff --git a/sdk/communication/communication-network-traversal/src/generated/src/index.ts b/sdk/communication/communication-network-traversal/src/generated/src/index.ts index 3485de9f8d0e..6154e4414169 100644 --- a/sdk/communication/communication-network-traversal/src/generated/src/index.ts +++ b/sdk/communication/communication-network-traversal/src/generated/src/index.ts @@ -8,5 +8,4 @@ export * from "./models"; export { NetworkRelayRestClient } from "./networkRelayRestClient"; -export { NetworkRelayRestClientContext } from "./networkRelayRestClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-network-traversal/src/generated/src/models/index.ts b/sdk/communication/communication-network-traversal/src/generated/src/models/index.ts index 5f5a0f5fbe67..0047066a8f9a 100644 --- a/sdk/communication/communication-network-traversal/src/generated/src/models/index.ts +++ b/sdk/communication/communication-network-traversal/src/generated/src/models/index.ts @@ -69,7 +69,9 @@ export interface CommunicationError { /** Known values of {@link RouteType} that the service accepts. */ export enum KnownRouteType { + /** Any */ Any = "any", + /** Nearest */ Nearest = "nearest" } diff --git a/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClient.ts b/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClient.ts index 0de92cb22908..4fe7f6ac9749 100644 --- a/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClient.ts +++ b/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClient.ts @@ -6,12 +6,20 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { CommunicationNetworkTraversalImpl } from "./operations"; import { CommunicationNetworkTraversal } from "./operationsInterfaces"; -import { NetworkRelayRestClientContext } from "./networkRelayRestClientContext"; import { NetworkRelayRestClientOptionalParams } from "./models"; -export class NetworkRelayRestClient extends NetworkRelayRestClientContext { +export class NetworkRelayRestClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the NetworkRelayRestClient class. * @param endpoint The communication resource, for example https://my-resource.communication.azure.com @@ -21,10 +29,70 @@ export class NetworkRelayRestClient extends NetworkRelayRestClientContext { endpoint: string, options?: NetworkRelayRestClientOptionalParams ) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: NetworkRelayRestClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-network-traversal/1.1.0-beta.3`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2022-03-01-preview"; this.communicationNetworkTraversal = new CommunicationNetworkTraversalImpl( this ); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } communicationNetworkTraversal: CommunicationNetworkTraversal; diff --git a/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClientContext.ts b/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClientContext.ts deleted file mode 100644 index a940a6f32eb7..000000000000 --- a/sdk/communication/communication-network-traversal/src/generated/src/networkRelayRestClientContext.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { NetworkRelayRestClientOptionalParams } from "./models"; - -export class NetworkRelayRestClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the NetworkRelayRestClientContext class. - * @param endpoint The communication resource, for example https://my-resource.communication.azure.com - * @param options The parameter options - */ - constructor( - endpoint: string, - options?: NetworkRelayRestClientOptionalParams - ) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: NetworkRelayRestClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-communication-network-traversal/1.1.0-beta.2`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2022-03-01-preview"; - } -} diff --git a/sdk/communication/communication-network-traversal/src/generated/src/operations/communicationNetworkTraversal.ts b/sdk/communication/communication-network-traversal/src/generated/src/operations/communicationNetworkTraversal.ts index 88f0b4a9959a..64a8fa95fd5a 100644 --- a/sdk/communication/communication-network-traversal/src/generated/src/operations/communicationNetworkTraversal.ts +++ b/sdk/communication/communication-network-traversal/src/generated/src/operations/communicationNetworkTraversal.ts @@ -6,11 +6,12 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { CommunicationNetworkTraversal } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { NetworkRelayRestClientContext } from "../networkRelayRestClientContext"; +import { NetworkRelayRestClient } from "../networkRelayRestClient"; import { CommunicationNetworkTraversalIssueRelayConfigurationOptionalParams, CommunicationNetworkTraversalIssueRelayConfigurationResponse @@ -19,13 +20,13 @@ import { /** Class containing CommunicationNetworkTraversal operations. */ export class CommunicationNetworkTraversalImpl implements CommunicationNetworkTraversal { - private readonly client: NetworkRelayRestClientContext; + private readonly client: NetworkRelayRestClient; /** * Initialize a new instance of the class CommunicationNetworkTraversal class. * @param client Reference to the service client */ - constructor(client: NetworkRelayRestClientContext) { + constructor(client: NetworkRelayRestClient) { this.client = client; } @@ -33,12 +34,20 @@ export class CommunicationNetworkTraversalImpl * Issue a configuration for an STUN/TURN server. * @param options The options parameters. */ - issueRelayConfiguration( + async issueRelayConfiguration( options?: CommunicationNetworkTraversalIssueRelayConfigurationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - issueRelayConfigurationOperationSpec + return tracingClient.withSpan( + "NetworkRelayRestClient.issueRelayConfiguration", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + issueRelayConfigurationOperationSpec + ) as Promise< + CommunicationNetworkTraversalIssueRelayConfigurationResponse + >; + } ); } } diff --git a/sdk/communication/communication-network-traversal/src/generated/src/tracing.ts b/sdk/communication/communication-network-traversal/src/generated/src/tracing.ts new file mode 100644 index 000000000000..8f55711394c9 --- /dev/null +++ b/sdk/communication/communication-network-traversal/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-network-traversal", + packageVersion: "1.1.0-beta.3" +}); diff --git a/sdk/communication/communication-network-traversal/swagger/README.md b/sdk/communication/communication-network-traversal/swagger/README.md index 47c9c6e4799b..f7b235df7022 100644 --- a/sdk/communication/communication-network-traversal/swagger/README.md +++ b/sdk/communication/communication-network-traversal/swagger/README.md @@ -8,8 +8,7 @@ package-name: "@azure/communication-network-traversal" override-client-name: NetworkRelayRestClient description: Communication Network Traversal Client -package-version: 1.1.0-beta.2 -generate-metadata: false +package-version: 1.1.0-beta.3 license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated tag: package-2022-03-01-preview @@ -18,9 +17,15 @@ require: model-date-time-as-string: false optional-response-headers: true payload-flattening-threshold: 10 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" add-credentials: false -azure-arm: false v3: true +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` diff --git a/sdk/communication/communication-phone-numbers/CHANGELOG.md b/sdk/communication/communication-phone-numbers/CHANGELOG.md index 3f5ad1547dc3..96e753de9454 100644 --- a/sdk/communication/communication-phone-numbers/CHANGELOG.md +++ b/sdk/communication/communication-phone-numbers/CHANGELOG.md @@ -1,5 +1,16 @@ # Release History +## 1.2.0-beta.5 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + +### Breaking Changes + +### Bugs Fixed + + ## 1.2.0-beta.4 (Unreleased) ### Features Added diff --git a/sdk/communication/communication-phone-numbers/package.json b/sdk/communication/communication-phone-numbers/package.json index 4625d0859117..9f5b8707d11c 100644 --- a/sdk/communication/communication-phone-numbers/package.json +++ b/sdk/communication/communication-phone-numbers/package.json @@ -1,6 +1,6 @@ { "name": "@azure/communication-phone-numbers", - "version": "1.2.0-beta.4", + "version": "1.2.0-beta.5", "description": "SDK for Azure Communication service which facilitates phone number management.", "sdk-type": "client", "main": "dist/index.js", @@ -67,7 +67,7 @@ "@azure/core-rest-pipeline": "^1.3.0", "@azure/core-lro": "^2.2.4", "@azure/core-paging": "^1.1.1", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0" diff --git a/sdk/communication/communication-phone-numbers/src/generated/src/index.ts b/sdk/communication/communication-phone-numbers/src/generated/src/index.ts index 7b989b9cd2e3..9d55ca478efa 100644 --- a/sdk/communication/communication-phone-numbers/src/generated/src/index.ts +++ b/sdk/communication/communication-phone-numbers/src/generated/src/index.ts @@ -9,5 +9,4 @@ /// export * from "./models"; export { PhoneNumbersClient } from "./phoneNumbersClient"; -export { PhoneNumbersClientContext } from "./phoneNumbersClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-phone-numbers/src/generated/src/operations/phoneNumbers.ts b/sdk/communication/communication-phone-numbers/src/generated/src/operations/phoneNumbers.ts index 927bbd597b73..8c31d22b2465 100644 --- a/sdk/communication/communication-phone-numbers/src/generated/src/operations/phoneNumbers.ts +++ b/sdk/communication/communication-phone-numbers/src/generated/src/operations/phoneNumbers.ts @@ -6,12 +6,13 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PhoneNumbers } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { PhoneNumbersClientContext } from "../phoneNumbersClientContext"; +import { PhoneNumbersClient } from "../phoneNumbersClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { @@ -43,13 +44,13 @@ import { /// /** Class containing PhoneNumbers operations. */ export class PhoneNumbersImpl implements PhoneNumbers { - private readonly client: PhoneNumbersClientContext; + private readonly client: PhoneNumbersClient; /** * Initialize a new instance of the class PhoneNumbers class. * @param client Reference to the service client */ - constructor(client: PhoneNumbersClientContext) { + constructor(client: PhoneNumbersClient) { this.client = client; } @@ -120,7 +121,15 @@ export class PhoneNumbersImpl implements PhoneNumbers { args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise => { - return this.client.sendOperationRequest(args, spec); + return tracingClient.withSpan( + "PhoneNumbersClient.beginSearchAvailablePhoneNumbers", + options ?? {}, + async () => { + return this.client.sendOperationRequest(args, spec) as Promise< + PhoneNumbersSearchAvailablePhoneNumbersResponse + >; + } + ); }; const sendOperation = async ( args: coreClient.OperationArguments, @@ -160,11 +169,13 @@ export class PhoneNumbersImpl implements PhoneNumbers { { countryCode, phoneNumberType, assignmentType, capabilities, options }, searchAvailablePhoneNumbersOperationSpec ); - return new LroEngine(lro, { + const poller = new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); + await poller.poll(); + return poller; } /** @@ -198,13 +209,19 @@ export class PhoneNumbersImpl implements PhoneNumbers { * @param searchId The search Id. * @param options The options parameters. */ - getSearchResult( + async getSearchResult( searchId: string, options?: PhoneNumbersGetSearchResultOptionalParams ): Promise { - return this.client.sendOperationRequest( - { searchId, options }, - getSearchResultOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient.getSearchResult", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { searchId, options }, + getSearchResultOperationSpec + ) as Promise; + } ); } @@ -224,7 +241,15 @@ export class PhoneNumbersImpl implements PhoneNumbers { args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise => { - return this.client.sendOperationRequest(args, spec); + return tracingClient.withSpan( + "PhoneNumbersClient.beginPurchasePhoneNumbers", + options ?? {}, + async () => { + return this.client.sendOperationRequest(args, spec) as Promise< + PhoneNumbersPurchasePhoneNumbersResponse + >; + } + ); }; const sendOperation = async ( args: coreClient.OperationArguments, @@ -264,10 +289,12 @@ export class PhoneNumbersImpl implements PhoneNumbers { { options }, purchasePhoneNumbersOperationSpec ); - return new LroEngine(lro, { + const poller = new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); + await poller.poll(); + return poller; } /** @@ -286,13 +313,19 @@ export class PhoneNumbersImpl implements PhoneNumbers { * @param operationId The id of the operation * @param options The options parameters. */ - getOperation( + async getOperation( operationId: string, options?: PhoneNumbersGetOperationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { operationId, options }, - getOperationOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient.getOperation", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { operationId, options }, + getOperationOperationSpec + ) as Promise; + } ); } @@ -301,13 +334,19 @@ export class PhoneNumbersImpl implements PhoneNumbers { * @param operationId The id of the operation * @param options The options parameters. */ - cancelOperation( + async cancelOperation( operationId: string, options?: PhoneNumbersCancelOperationOptionalParams ): Promise { - return this.client.sendOperationRequest( - { operationId, options }, - cancelOperationOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient.cancelOperation", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { operationId, options }, + cancelOperationOperationSpec + ) as Promise; + } ); } @@ -330,7 +369,15 @@ export class PhoneNumbersImpl implements PhoneNumbers { args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise => { - return this.client.sendOperationRequest(args, spec); + return tracingClient.withSpan( + "PhoneNumbersClient.beginUpdateCapabilities", + options ?? {}, + async () => { + return this.client.sendOperationRequest(args, spec) as Promise< + PhoneNumbersUpdateCapabilitiesResponse + >; + } + ); }; const sendOperation = async ( args: coreClient.OperationArguments, @@ -370,11 +417,13 @@ export class PhoneNumbersImpl implements PhoneNumbers { { phoneNumber, options }, updateCapabilitiesOperationSpec ); - return new LroEngine(lro, { + const poller = new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); + await poller.poll(); + return poller; } /** @@ -397,13 +446,19 @@ export class PhoneNumbersImpl implements PhoneNumbers { * +11234567890. * @param options The options parameters. */ - getByNumber( + async getByNumber( phoneNumber: string, options?: PhoneNumbersGetByNumberOptionalParams ): Promise { - return this.client.sendOperationRequest( - { phoneNumber, options }, - getByNumberOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient.getByNumber", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { phoneNumber, options }, + getByNumberOperationSpec + ) as Promise; + } ); } @@ -425,7 +480,15 @@ export class PhoneNumbersImpl implements PhoneNumbers { args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise => { - return this.client.sendOperationRequest(args, spec); + return tracingClient.withSpan( + "PhoneNumbersClient.beginReleasePhoneNumber", + options ?? {}, + async () => { + return this.client.sendOperationRequest(args, spec) as Promise< + PhoneNumbersReleasePhoneNumberResponse + >; + } + ); }; const sendOperation = async ( args: coreClient.OperationArguments, @@ -465,10 +528,12 @@ export class PhoneNumbersImpl implements PhoneNumbers { { phoneNumber, options }, releasePhoneNumberOperationSpec ); - return new LroEngine(lro, { + const poller = new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); + await poller.poll(); + return poller; } /** @@ -488,12 +553,18 @@ export class PhoneNumbersImpl implements PhoneNumbers { * Gets the list of all purchased phone numbers. * @param options The options parameters. */ - private _listPhoneNumbers( + private async _listPhoneNumbers( options?: PhoneNumbersListPhoneNumbersOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - listPhoneNumbersOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient._listPhoneNumbers", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + listPhoneNumbersOperationSpec + ) as Promise; + } ); } @@ -502,13 +573,19 @@ export class PhoneNumbersImpl implements PhoneNumbers { * @param nextLink The nextLink from the previous successful call to the ListPhoneNumbers method. * @param options The options parameters. */ - private _listPhoneNumbersNext( + private async _listPhoneNumbersNext( nextLink: string, options?: PhoneNumbersListPhoneNumbersNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { nextLink, options }, - listPhoneNumbersNextOperationSpec + return tracingClient.withSpan( + "PhoneNumbersClient._listPhoneNumbersNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { nextLink, options }, + listPhoneNumbersNextOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClient.ts b/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClient.ts index 724510ad5481..5c82a133ce8e 100644 --- a/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClient.ts +++ b/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClient.ts @@ -6,20 +6,88 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { PhoneNumbersImpl } from "./operations"; import { PhoneNumbers } from "./operationsInterfaces"; -import { PhoneNumbersClientContext } from "./phoneNumbersClientContext"; import { PhoneNumbersClientOptionalParams } from "./models"; -export class PhoneNumbersClient extends PhoneNumbersClientContext { +export class PhoneNumbersClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the PhoneNumbersClient class. * @param endpoint The communication resource, for example https://resourcename.communication.azure.com * @param options The parameter options */ constructor(endpoint: string, options?: PhoneNumbersClientOptionalParams) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: PhoneNumbersClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-phone-numbers/1.2.0-beta.5`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2022-06-01-preview"; this.phoneNumbers = new PhoneNumbersImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } phoneNumbers: PhoneNumbers; diff --git a/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClientContext.ts b/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClientContext.ts deleted file mode 100644 index 4949d6856cd9..000000000000 --- a/sdk/communication/communication-phone-numbers/src/generated/src/phoneNumbersClientContext.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { PhoneNumbersClientOptionalParams } from "./models"; - -export class PhoneNumbersClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the PhoneNumbersClientContext class. - * @param endpoint The communication resource, for example https://resourcename.communication.azure.com - * @param options The parameter options - */ - constructor(endpoint: string, options?: PhoneNumbersClientOptionalParams) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: PhoneNumbersClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-communication-phone-numbers/1.2.0-beta.4`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2022-06-01-preview"; - } -} diff --git a/sdk/communication/communication-phone-numbers/src/generated/src/tracing.ts b/sdk/communication/communication-phone-numbers/src/generated/src/tracing.ts new file mode 100644 index 000000000000..a9dfd287094e --- /dev/null +++ b/sdk/communication/communication-phone-numbers/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-phone-numbers", + packageVersion: "1.2.0-beta.5" +}); diff --git a/sdk/communication/communication-phone-numbers/src/phoneNumbersClient.ts b/sdk/communication/communication-phone-numbers/src/phoneNumbersClient.ts index 169cc69f0abf..b46a6f39379e 100644 --- a/sdk/communication/communication-phone-numbers/src/phoneNumbersClient.ts +++ b/sdk/communication/communication-phone-numbers/src/phoneNumbersClient.ts @@ -11,8 +11,6 @@ import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-a import { InternalPipelineOptions } from "@azure/core-rest-pipeline"; import { PollOperationState, PollerLike } from "@azure/core-lro"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; -import { SpanStatusCode } from "@azure/core-tracing"; -import { createSpan, logger } from "./utils"; import { PhoneNumbersClient as PhoneNumbersGeneratedClient } from "./generated/src"; import { PhoneNumberCapabilitiesRequest, @@ -34,6 +32,8 @@ import { } from "./lroModels"; import { createPhoneNumbersPagingPolicy } from "./utils/customPipelinePolicies"; import { CommonClientOptions } from "@azure/core-client"; +import { logger } from "./utils"; +import { tracingClient } from "./generated/src/tracing"; /** * Client options used to configure the PhoneNumbersClient API requests. @@ -114,25 +114,17 @@ export class PhoneNumbersClient { * @param phoneNumber - The E.164 formatted phone number being fetched. The leading plus can be either + or encoded as %2B. * @param options - Additional request options. */ - public async getPurchasedPhoneNumber( + public getPurchasedPhoneNumber( phoneNumber: string, options: GetPurchasedPhoneNumberOptions = {} ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "PhoneNumbersClient-getPurchasedPhoneNumber", - options + options, + (updatedOptions) => { + return this.client.phoneNumbers.getByNumber(phoneNumber, updatedOptions); + } ); - try { - return await this.client.phoneNumbers.getByNumber(phoneNumber, updatedOptions); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } /** @@ -151,13 +143,23 @@ export class PhoneNumbersClient { public listPurchasedPhoneNumbers( options: ListPurchasedPhoneNumbersOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan( + const { span, updatedOptions } = tracingClient.startSpan( "PhoneNumbersClient-listPurchasedPhoneNumbers", options ); - const iter = this.client.phoneNumbers.listPhoneNumbers(updatedOptions); - span.end(); - return iter; + + try { + return this.client.phoneNumbers.listPhoneNumbers(updatedOptions); + } catch (e: any) { + span.setStatus({ + status: "error", + error: e, + }); + + throw e; + } finally { + span.end(); + } } /** @@ -180,26 +182,17 @@ export class PhoneNumbersClient { * @param phoneNumber - The E.164 formatted phone number being released. The leading plus can be either + or encoded as %2B. * @param options - Additional request options. */ - public async beginReleasePhoneNumber( + public beginReleasePhoneNumber( phoneNumber: string, options: BeginReleasePhoneNumberOptions = {} ): Promise, ReleasePhoneNumberResult>> { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "PhoneNumbersClient-beginReleasePhoneNumber", - options + options, + (updatedOptions) => { + return this.client.phoneNumbers.beginReleasePhoneNumber(phoneNumber, updatedOptions); + } ); - - try { - return await this.client.phoneNumbers.beginReleasePhoneNumber(phoneNumber, updatedOptions); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } /** @@ -224,36 +217,27 @@ export class PhoneNumbersClient { * @param search - Request properties to constraint the search scope. * @param options - Additional request options. */ - public async beginSearchAvailablePhoneNumbers( + public beginSearchAvailablePhoneNumbers( search: SearchAvailablePhoneNumbersRequest, options: BeginSearchAvailablePhoneNumbersOptions = {} ): Promise, PhoneNumberSearchResult>> { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "PhoneNumbersClient-beginSearchAvailablePhoneNumbers", - options + options, + (updatedOptions) => { + const { countryCode, phoneNumberType, assignmentType, capabilities, ...rest } = search; + return this.client.phoneNumbers.beginSearchAvailablePhoneNumbers( + countryCode, + phoneNumberType, + assignmentType, + capabilities, + { + ...updatedOptions, + ...rest, + } + ); + } ); - - try { - const { countryCode, phoneNumberType, assignmentType, capabilities, ...rest } = search; - return this.client.phoneNumbers.beginSearchAvailablePhoneNumbers( - countryCode, - phoneNumberType, - assignmentType, - capabilities, - { - ...updatedOptions, - ...rest, - } - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } /** @@ -277,28 +261,19 @@ export class PhoneNumbersClient { * @param searchId - The id of the search to purchase. Returned from `beginSearchAvailablePhoneNumbers` * @param options - Additional request options. */ - public async beginPurchasePhoneNumbers( + public beginPurchasePhoneNumbers( searchId: string, options: BeginPurchasePhoneNumbersOptions = {} ): Promise< PollerLike, PurchasePhoneNumbersResult> > { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "PhoneNumbersClient-beginPurchasePhoneNumbers", - options + options, + (updatedOptions) => { + return this.client.phoneNumbers.beginPurchasePhoneNumbers({ ...updatedOptions, searchId }); + } ); - - try { - return this.client.phoneNumbers.beginPurchasePhoneNumbers({ ...updatedOptions, searchId }); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } /** @@ -323,29 +298,20 @@ export class PhoneNumbersClient { * @param request - The updated properties which will be applied to the phone number. * @param options - Additional request options. */ - public async beginUpdatePhoneNumberCapabilities( + public beginUpdatePhoneNumberCapabilities( phoneNumber: string, request: PhoneNumberCapabilitiesRequest, options: BeginUpdatePhoneNumberCapabilitiesOptions = {} ): Promise, PurchasedPhoneNumber>> { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "PhoneNumbersClient-beginUpdatePhoneNumberCapabilities", - options + options, + (updatedOptions) => { + return this.client.phoneNumbers.beginUpdateCapabilities(phoneNumber, { + ...updatedOptions, + ...request, + }); + } ); - - try { - return this.client.phoneNumbers.beginUpdateCapabilities(phoneNumber, { - ...updatedOptions, - ...request, - }); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } } diff --git a/sdk/communication/communication-phone-numbers/src/utils/constants.ts b/sdk/communication/communication-phone-numbers/src/utils/constants.ts index 0d7af2cb53d7..0a58714e6054 100644 --- a/sdk/communication/communication-phone-numbers/src/utils/constants.ts +++ b/sdk/communication/communication-phone-numbers/src/utils/constants.ts @@ -1,4 +1,4 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -export const SDK_VERSION: string = "1.2.0-beta.4"; +export const SDK_VERSION: string = "1.2.0-beta.5"; diff --git a/sdk/communication/communication-phone-numbers/src/utils/index.ts b/sdk/communication/communication-phone-numbers/src/utils/index.ts index 962243d5a042..22603daf6de5 100644 --- a/sdk/communication/communication-phone-numbers/src/utils/index.ts +++ b/sdk/communication/communication-phone-numbers/src/utils/index.ts @@ -3,4 +3,3 @@ export * from "./constants"; export * from "./logger"; -export * from "./tracing"; diff --git a/sdk/communication/communication-phone-numbers/src/utils/tracing.ts b/sdk/communication/communication-phone-numbers/src/utils/tracing.ts deleted file mode 100644 index 95110af9b921..000000000000 --- a/sdk/communication/communication-phone-numbers/src/utils/tracing.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - * @param name - The name of the operation being performed. - * @param tracingOptions - The options for the underlying http request. - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-phone-numbers/swagger/README.md b/sdk/communication/communication-phone-numbers/swagger/README.md index 7c429e949f24..b2f7d954d669 100644 --- a/sdk/communication/communication-phone-numbers/swagger/README.md +++ b/sdk/communication/communication-phone-numbers/swagger/README.md @@ -7,8 +7,7 @@ ```yaml package-name: "@azure/communication-phone-numbers" description: Phone number configuration client -package-version: 1.2.0-beta.4 -generate-metadata: false +package-version: 1.2.0-beta.5 license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated tag: package-phonenumber-2022-06-01-preview @@ -16,13 +15,19 @@ require: https://github.com/Azure/azure-rest-api-specs/blob/6de2e5bf9286b2dddea9 model-date-time-as-string: false optional-response-headers: true payload-flattening-threshold: 10 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" add-credentials: false -azure-arm: false skip-enum-validation: true title: Phone Numbers Client v3: true +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` ## Customizations diff --git a/sdk/communication/communication-short-codes/CHANGELOG.md b/sdk/communication/communication-short-codes/CHANGELOG.md index 22e84386ddb2..e93f67f115e0 100644 --- a/sdk/communication/communication-short-codes/CHANGELOG.md +++ b/sdk/communication/communication-short-codes/CHANGELOG.md @@ -1,5 +1,17 @@ # Release History +## 1.0.0-beta.5 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 1.0.0-beta.4 (Unreleased) ### Features Added diff --git a/sdk/communication/communication-short-codes/package.json b/sdk/communication/communication-short-codes/package.json index 9d812a0a4ae2..25b63f37503a 100644 --- a/sdk/communication/communication-short-codes/package.json +++ b/sdk/communication/communication-short-codes/package.json @@ -1,6 +1,6 @@ { "name": "@azure-tools/communication-short-codes", - "version": "1.0.0-beta.4", + "version": "1.0.0-beta.5", "description": "SDK for Azure Communication Services which facilitates short code management.", "sdk-type": "client", "main": "dist/index.js", @@ -66,7 +66,7 @@ "@azure/core-lro": "^2.2.0", "@azure/core-paging": "^1.1.1", "@azure/core-rest-pipeline": "^1.3.2", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0" diff --git a/sdk/communication/communication-short-codes/src/generated/src/index.ts b/sdk/communication/communication-short-codes/src/generated/src/index.ts index 79a111145fba..a37b548b3af6 100644 --- a/sdk/communication/communication-short-codes/src/generated/src/index.ts +++ b/sdk/communication/communication-short-codes/src/generated/src/index.ts @@ -9,5 +9,4 @@ /// export * from "./models"; export { ShortCodesClient } from "./shortCodesClient"; -export { ShortCodesClientContext } from "./shortCodesClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-short-codes/src/generated/src/operations/shortCodesOperations.ts b/sdk/communication/communication-short-codes/src/generated/src/operations/shortCodesOperations.ts index 51176edf4494..8db6006902f4 100644 --- a/sdk/communication/communication-short-codes/src/generated/src/operations/shortCodesOperations.ts +++ b/sdk/communication/communication-short-codes/src/generated/src/operations/shortCodesOperations.ts @@ -6,12 +6,13 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ShortCodesOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { ShortCodesClientContext } from "../shortCodesClientContext"; +import { ShortCodesClient } from "../shortCodesClient"; import { ShortCode, ShortCodesGetShortCodesNextOptionalParams, @@ -47,13 +48,13 @@ import { /// /** Class containing ShortCodesOperations operations. */ export class ShortCodesOperationsImpl implements ShortCodesOperations { - private readonly client: ShortCodesClientContext; + private readonly client: ShortCodesClient; /** * Initialize a new instance of the class ShortCodesOperations class. * @param client Reference to the service client */ - constructor(client: ShortCodesClientContext) { + constructor(client: ShortCodesClient) { this.client = client; } @@ -207,12 +208,18 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * Gets the list of short codes for the current resource. * @param options The options parameters. */ - private _getShortCodes( + private async _getShortCodes( options?: ShortCodesGetShortCodesOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - getShortCodesOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getShortCodes", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + getShortCodesOperationSpec + ) as Promise; + } ); } @@ -221,13 +228,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param programBriefId Program Brief Id. Must be a valid GUID * @param options The options parameters. */ - upsertUSProgramBrief( + async upsertUSProgramBrief( programBriefId: string, options?: ShortCodesUpsertUSProgramBriefOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, options }, - upsertUSProgramBriefOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.upsertUSProgramBrief", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, options }, + upsertUSProgramBriefOperationSpec + ) as Promise; + } ); } @@ -236,13 +249,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param programBriefId Program Brief Id. Must be a valid GUID * @param options The options parameters. */ - deleteUSProgramBrief( + async deleteUSProgramBrief( programBriefId: string, options?: ShortCodesDeleteUSProgramBriefOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, options }, - deleteUSProgramBriefOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.deleteUSProgramBrief", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, options }, + deleteUSProgramBriefOperationSpec + ) as Promise; + } ); } @@ -251,13 +270,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param programBriefId Program Brief Id. Must be a valid GUID * @param options The options parameters. */ - getUSProgramBrief( + async getUSProgramBrief( programBriefId: string, options?: ShortCodesGetUSProgramBriefOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, options }, - getUSProgramBriefOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.getUSProgramBrief", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, options }, + getUSProgramBriefOperationSpec + ) as Promise; + } ); } @@ -266,13 +291,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param programBriefId Program Brief Id. Must be a valid GUID * @param options The options parameters. */ - submitUSProgramBrief( + async submitUSProgramBrief( programBriefId: string, options?: ShortCodesSubmitUSProgramBriefOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, options }, - submitUSProgramBriefOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.submitUSProgramBrief", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, options }, + submitUSProgramBriefOperationSpec + ) as Promise; + } ); } @@ -280,12 +311,18 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * Gets the list of US Program Briefs for the current resource. * @param options The options parameters. */ - private _getUSProgramBriefs( + private async _getUSProgramBriefs( options?: ShortCodesGetUSProgramBriefsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { options }, - getUSProgramBriefsOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getUSProgramBriefs", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { options }, + getUSProgramBriefsOperationSpec + ) as Promise; + } ); } @@ -303,7 +340,7 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * e.g. 'callToAction', 'termsOfService' * @param options The options parameters. */ - createOrReplaceUSProgramBriefAttachment( + async createOrReplaceUSProgramBriefAttachment( programBriefId: string, attachmentId: string, id: string, @@ -313,18 +350,24 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { type: AttachmentType, options?: ShortCodesCreateOrReplaceUSProgramBriefAttachmentOptionalParams ): Promise { - return this.client.sendOperationRequest( - { - programBriefId, - attachmentId, - id, - fileName, - fileType, - fileContentBase64, - type, - options - }, - createOrReplaceUSProgramBriefAttachmentOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.createOrReplaceUSProgramBriefAttachment", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { + programBriefId, + attachmentId, + id, + fileName, + fileType, + fileContentBase64, + type, + options + }, + createOrReplaceUSProgramBriefAttachmentOperationSpec + ) as Promise; + } ); } @@ -334,14 +377,20 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param attachmentId Attachment Id. Must be a valid GUID * @param options The options parameters. */ - getUSProgramBriefAttachment( + async getUSProgramBriefAttachment( programBriefId: string, attachmentId: string, options?: ShortCodesGetUSProgramBriefAttachmentOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, attachmentId, options }, - getUSProgramBriefAttachmentOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.getUSProgramBriefAttachment", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, attachmentId, options }, + getUSProgramBriefAttachmentOperationSpec + ) as Promise; + } ); } @@ -351,14 +400,20 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param attachmentId Attachment Id. Must be a valid GUID * @param options The options parameters. */ - deleteUSProgramBriefAttachment( + async deleteUSProgramBriefAttachment( programBriefId: string, attachmentId: string, options?: ShortCodesDeleteUSProgramBriefAttachmentOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, attachmentId, options }, - deleteUSProgramBriefAttachmentOperationSpec + return tracingClient.withSpan( + "ShortCodesClient.deleteUSProgramBriefAttachment", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, attachmentId, options }, + deleteUSProgramBriefAttachmentOperationSpec + ) as Promise; + } ); } @@ -367,13 +422,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param programBriefId * @param options The options parameters. */ - private _getUSProgramBriefAttachments( + private async _getUSProgramBriefAttachments( programBriefId: string, options?: ShortCodesGetUSProgramBriefAttachmentsOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, options }, - getUSProgramBriefAttachmentsOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getUSProgramBriefAttachments", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, options }, + getUSProgramBriefAttachmentsOperationSpec + ) as Promise; + } ); } @@ -382,13 +443,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param nextLink The nextLink from the previous successful call to the GetShortCodes method. * @param options The options parameters. */ - private _getShortCodesNext( + private async _getShortCodesNext( nextLink: string, options?: ShortCodesGetShortCodesNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { nextLink, options }, - getShortCodesNextOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getShortCodesNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { nextLink, options }, + getShortCodesNextOperationSpec + ) as Promise; + } ); } @@ -397,13 +464,19 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * @param nextLink The nextLink from the previous successful call to the GetUSProgramBriefs method. * @param options The options parameters. */ - private _getUSProgramBriefsNext( + private async _getUSProgramBriefsNext( nextLink: string, options?: ShortCodesGetUSProgramBriefsNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { nextLink, options }, - getUSProgramBriefsNextOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getUSProgramBriefsNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { nextLink, options }, + getUSProgramBriefsNextOperationSpec + ) as Promise; + } ); } @@ -414,14 +487,20 @@ export class ShortCodesOperationsImpl implements ShortCodesOperations { * method. * @param options The options parameters. */ - private _getUSProgramBriefAttachmentsNext( + private async _getUSProgramBriefAttachmentsNext( programBriefId: string, nextLink: string, options?: ShortCodesGetUSProgramBriefAttachmentsNextOptionalParams ): Promise { - return this.client.sendOperationRequest( - { programBriefId, nextLink, options }, - getUSProgramBriefAttachmentsNextOperationSpec + return tracingClient.withSpan( + "ShortCodesClient._getUSProgramBriefAttachmentsNext", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { programBriefId, nextLink, options }, + getUSProgramBriefAttachmentsNextOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-short-codes/src/generated/src/shortCodesClient.ts b/sdk/communication/communication-short-codes/src/generated/src/shortCodesClient.ts index fd5d5a89eeaa..da04755cfdf1 100644 --- a/sdk/communication/communication-short-codes/src/generated/src/shortCodesClient.ts +++ b/sdk/communication/communication-short-codes/src/generated/src/shortCodesClient.ts @@ -6,20 +6,112 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import * as coreRestPipeline from "@azure/core-rest-pipeline"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { ShortCodesOperationsImpl } from "./operations"; import { ShortCodesOperations } from "./operationsInterfaces"; -import { ShortCodesClientContext } from "./shortCodesClientContext"; import { ShortCodesClientOptionalParams } from "./models"; -export class ShortCodesClient extends ShortCodesClientContext { +export class ShortCodesClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the ShortCodesClient class. * @param endpoint The communication resource, for example https://resourcename.communication.azure.com * @param options The parameter options */ constructor(endpoint: string, options?: ShortCodesClientOptionalParams) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: ShortCodesClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-short-codes/1.0.0-beta.5`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + + if (options?.pipeline && options.pipeline.getOrderedPolicies().length > 0) { + const pipelinePolicies: coreRestPipeline.PipelinePolicy[] = options.pipeline.getOrderedPolicies(); + const bearerTokenAuthenticationPolicyFound = pipelinePolicies.some( + (pipelinePolicy) => + pipelinePolicy.name === + coreRestPipeline.bearerTokenAuthenticationPolicyName + ); + if (!bearerTokenAuthenticationPolicyFound) { + this.pipeline.removePolicy({ + name: coreRestPipeline.bearerTokenAuthenticationPolicyName + }); + this.pipeline.addPolicy( + coreRestPipeline.bearerTokenAuthenticationPolicy({ + scopes: `${optionsWithDefaults.baseUri}/.default`, + challengeCallbacks: { + authorizeRequestOnChallenge: + coreClient.authorizeRequestOnClaimChallenge + } + }) + ); + } + } + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2021-10-25-preview"; this.shortCodesOperations = new ShortCodesOperationsImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } shortCodesOperations: ShortCodesOperations; diff --git a/sdk/communication/communication-short-codes/src/generated/src/shortCodesClientContext.ts b/sdk/communication/communication-short-codes/src/generated/src/shortCodesClientContext.ts deleted file mode 100644 index b1557280d262..000000000000 --- a/sdk/communication/communication-short-codes/src/generated/src/shortCodesClientContext.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreClient from "@azure/core-client"; -import { ShortCodesClientOptionalParams } from "./models"; - -export class ShortCodesClientContext extends coreClient.ServiceClient { - endpoint: string; - apiVersion: string; - - /** - * Initializes a new instance of the ShortCodesClientContext class. - * @param endpoint The communication resource, for example https://resourcename.communication.azure.com - * @param options The parameter options - */ - constructor(endpoint: string, options?: ShortCodesClientOptionalParams) { - if (endpoint === undefined) { - throw new Error("'endpoint' cannot be null"); - } - - // Initializing default values for options - if (!options) { - options = {}; - } - const defaults: ShortCodesClientOptionalParams = { - requestContentType: "application/json; charset=utf-8" - }; - - const packageDetails = `azsdk-js-communication-short-codes/1.0.0-beta.4`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - - const optionsWithDefaults = { - ...defaults, - ...options, - userAgentOptions: { - userAgentPrefix - }, - baseUri: options.endpoint || "{endpoint}" - }; - super(optionsWithDefaults); - // Parameter assignments - this.endpoint = endpoint; - - // Assigning values to Constant parameters - this.apiVersion = options.apiVersion || "2021-10-25-preview"; - } -} diff --git a/sdk/communication/communication-short-codes/src/generated/src/tracing.ts b/sdk/communication/communication-short-codes/src/generated/src/tracing.ts new file mode 100644 index 000000000000..809a2f170916 --- /dev/null +++ b/sdk/communication/communication-short-codes/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-short-codes", + packageVersion: "1.0.0-beta.5" +}); diff --git a/sdk/communication/communication-short-codes/src/shortCodesClient.ts b/sdk/communication/communication-short-codes/src/shortCodesClient.ts index a9b6b684041a..4233ad8461c4 100644 --- a/sdk/communication/communication-short-codes/src/shortCodesClient.ts +++ b/sdk/communication/communication-short-codes/src/shortCodesClient.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /// -import { CommonClientOptions, InternalClientPipelineOptions } from "@azure/core-client"; + import { AttachmentType, DeleteUSProgramBriefOptions, @@ -15,6 +15,7 @@ import { ShortCodesGetUSProgramBriefAttachmentsOptionalParams, SubmitUSProgramBriefOptions, } from "./models"; +import { CommonClientOptions, InternalClientPipelineOptions } from "@azure/core-client"; import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; import { ProgramBriefAttachment, @@ -22,12 +23,12 @@ import { ShortCodesUpsertUSProgramBriefOptionalParams, USProgramBrief, } from "./generated/src/models/"; -import { createSpan, logger } from "./utils"; import { isKeyCredential, parseClientArguments } from "@azure/communication-common"; import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ShortCodesClient as ShortCodesGeneratedClient } from "./generated/src"; -import { SpanStatusCode } from "@azure/core-tracing"; import { createCommunicationAuthPolicy } from "@azure/communication-common"; +import { logger } from "./utils"; +import { tracingClient } from "./generated/src/tracing"; /** * Client options used to configure the ShortCodesClient API requests. */ @@ -83,13 +84,16 @@ export class ShortCodesClient { public listShortCodes( options: ListShortCodesOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ShortCodesClient-listShortCodes", options); + const { span, updatedOptions } = tracingClient.startSpan( + "ShortCodesClient-listShortCodes", + options + ); try { return this.client.shortCodesOperations.listShortCodes(updatedOptions); } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { @@ -97,79 +101,64 @@ export class ShortCodesClient { } } - public async upsertUSProgramBrief( + public upsertUSProgramBrief( programBriefId: string, options: ShortCodesUpsertUSProgramBriefOptionalParams = {} ): Promise { - const { span, updatedOptions } = createSpan("ShortCodesClient-upsertUSProgramBrief", options); - try { - return await this.client.shortCodesOperations.upsertUSProgramBrief( - programBriefId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ShortCodesClient-upsertUSProgramBrief", + options, + (updatedOptions) => { + return this.client.shortCodesOperations.upsertUSProgramBrief( + programBriefId, + updatedOptions + ); + } + ); } - public async deleteUSProgramBrief( + public deleteUSProgramBrief( programBriefId: string, - options?: DeleteUSProgramBriefOptions + options: DeleteUSProgramBriefOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ShortCodesClient-deleteUSProgramBrief", options); - try { - return await this.client.shortCodesOperations.deleteUSProgramBrief( - programBriefId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ShortCodesClient-deleteUSProgramBrief", + options, + (updatedOptions) => { + return this.client.shortCodesOperations.deleteUSProgramBrief( + programBriefId, + updatedOptions + ); + } + ); } - public async getUSProgramBrief( + public getUSProgramBrief( programBriefId: string, - options?: GetUSProgramBriefOptions + options: GetUSProgramBriefOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ShortCodesClient-getUSProgramBrief", options); - try { - return await this.client.shortCodesOperations.getUSProgramBrief( - programBriefId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ShortCodesClient-getUSProgramBrief", + options, + (updatedOptions) => { + return this.client.shortCodesOperations.getUSProgramBrief(programBriefId, updatedOptions); + } + ); } public listUSProgramBriefs( options: ListUSProgramBriefsOptions = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan("ShortCodesClient-listUSProgramBriefs", options); + const { span, updatedOptions } = tracingClient.startSpan( + "ShortCodesClient-listUSProgramBriefs", + options + ); try { return this.client.shortCodesOperations.listUSProgramBriefs(updatedOptions); } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { @@ -177,58 +166,45 @@ export class ShortCodesClient { } } - public async submitUSProgramBrief( + public submitUSProgramBrief( programBriefId: string, - options?: SubmitUSProgramBriefOptions + options: SubmitUSProgramBriefOptions = {} ): Promise { - const { span, updatedOptions } = createSpan("ShortCodesClient-submitUSProgramBrief", options); - try { - return await this.client.shortCodesOperations.submitUSProgramBrief( - programBriefId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + return tracingClient.withSpan( + "ShortCodesClient-submitUSProgramBrief", + options, + (updatedOptions) => { + return this.client.shortCodesOperations.submitUSProgramBrief( + programBriefId, + updatedOptions + ); + } + ); } - public async getUSProgramBriefAttachment( + public getUSProgramBriefAttachment( programBriefId: string, attachmentId: string, - options?: ShortCodesGetUSProgramBriefAttachmentOptionalParams + options: ShortCodesGetUSProgramBriefAttachmentOptionalParams = {} ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "ShortCodesClient-getUSProgramBriefAttachment", - options + options, + (updatedOptions) => { + return this.client.shortCodesOperations.getUSProgramBriefAttachment( + programBriefId, + attachmentId, + updatedOptions + ); + } ); - try { - return await this.client.shortCodesOperations.getUSProgramBriefAttachment( - programBriefId, - attachmentId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } public listUSProgramBriefAttachments( programBriefId: string, options: ShortCodesGetUSProgramBriefAttachmentsOptionalParams = {} ): PagedAsyncIterableIterator { - const { span, updatedOptions } = createSpan( + const { span, updatedOptions } = tracingClient.startSpan( "ShortCodesClient-listUSProgramBriefAttachments", options ); @@ -239,8 +215,8 @@ export class ShortCodesClient { ); } catch (e: any) { span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, + status: "error", + error: e, }); throw e; } finally { @@ -248,33 +224,25 @@ export class ShortCodesClient { } } - public async deleteUSProgramBriefAttachment( + public deleteUSProgramBriefAttachment( programBriefId: string, attachmentId: string, - options?: ShortCodesDeleteUSProgramBriefAttachmentOptionalParams + options: ShortCodesDeleteUSProgramBriefAttachmentOptionalParams = {} ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "ShortCodesClient-deleteUSProgramBriefAttachment", - options + options, + (updatedOptions) => { + return this.client.shortCodesOperations.deleteUSProgramBriefAttachment( + programBriefId, + attachmentId, + updatedOptions + ); + } ); - try { - return await this.client.shortCodesOperations.deleteUSProgramBriefAttachment( - programBriefId, - attachmentId, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } - public async createOrReplaceUSProgramBriefAttachment( + public createOrReplaceUSProgramBriefAttachment( programBriefId: string, attachmentId: string, fileName: string, @@ -283,29 +251,21 @@ export class ShortCodesClient { attachmentType: AttachmentType, options: ShortCodesCreateOrReplaceUSProgramBriefAttachmentOptionalParams = {} ): Promise { - const { span, updatedOptions } = createSpan( + return tracingClient.withSpan( "ShortCodesClient-createOrReplaceUSProgramBriefAttachment", - options + options, + (updatedOptions) => { + return this.client.shortCodesOperations.createOrReplaceUSProgramBriefAttachment( + programBriefId, + attachmentId, + attachmentId, + fileName, + fileType, + fileContent, + attachmentType, + updatedOptions + ); + } ); - try { - return await this.client.shortCodesOperations.createOrReplaceUSProgramBriefAttachment( - programBriefId, - attachmentId, - attachmentId, - fileName, - fileType, - fileContent, - attachmentType, - updatedOptions - ); - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } } } diff --git a/sdk/communication/communication-short-codes/src/utils/constants.ts b/sdk/communication/communication-short-codes/src/utils/constants.ts index 3ec689ed2107..2a542c1515b7 100644 --- a/sdk/communication/communication-short-codes/src/utils/constants.ts +++ b/sdk/communication/communication-short-codes/src/utils/constants.ts @@ -1,4 +1,4 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -export const SDK_VERSION: string = "1.0.0-beta.4"; +export const SDK_VERSION: string = "1.0.0-beta.5"; diff --git a/sdk/communication/communication-short-codes/src/utils/index.ts b/sdk/communication/communication-short-codes/src/utils/index.ts index 962243d5a042..22603daf6de5 100644 --- a/sdk/communication/communication-short-codes/src/utils/index.ts +++ b/sdk/communication/communication-short-codes/src/utils/index.ts @@ -3,4 +3,3 @@ export * from "./constants"; export * from "./logger"; -export * from "./tracing"; diff --git a/sdk/communication/communication-short-codes/src/utils/tracing.ts b/sdk/communication/communication-short-codes/src/utils/tracing.ts deleted file mode 100644 index 95110af9b921..000000000000 --- a/sdk/communication/communication-short-codes/src/utils/tracing.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - * @param name - The name of the operation being performed. - * @param tracingOptions - The options for the underlying http request. - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-short-codes/swagger/README.md b/sdk/communication/communication-short-codes/swagger/README.md index 7a18b3c46cc3..6de1d386c69f 100644 --- a/sdk/communication/communication-short-codes/swagger/README.md +++ b/sdk/communication/communication-short-codes/swagger/README.md @@ -7,8 +7,7 @@ ```yaml package-name: "@azure/communication-short-codes" description: Short code acquiring and management client -package-version: 1.0.0-beta.4 -generate-metadata: false +package-version: 1.0.0-beta.5 license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../src/generated tag: package-shortcode-2021-10-25-preview @@ -16,12 +15,18 @@ input-file: ./shortcodes.json model-date-time-as-string: false optional-response-headers: true payload-flattening-threshold: 10 -use-extension: - "@autorest/typescript": "6.0.0-beta.15" add-credentials: false -azure-arm: false skip-enum-validation: true title: Short Codes Client +use-extension: + "@autorest/typescript": "latest" +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` ## Customizations diff --git a/sdk/communication/communication-sms/CHANGELOG.md b/sdk/communication/communication-sms/CHANGELOG.md index f5e2c1bb7156..b88315c637bc 100644 --- a/sdk/communication/communication-sms/CHANGELOG.md +++ b/sdk/communication/communication-sms/CHANGELOG.md @@ -1,5 +1,11 @@ # Release History +## 1.2.0-beta.2 (Unreleased) + +### Features Added + +- Updated to `@azure/core-tracing` 1.0. + ## 1.2.0-beta.1 (2022-05-10) ### Features Added diff --git a/sdk/communication/communication-sms/package.json b/sdk/communication/communication-sms/package.json index ef45982df84d..c81c9a3e2dfd 100644 --- a/sdk/communication/communication-sms/package.json +++ b/sdk/communication/communication-sms/package.json @@ -1,6 +1,6 @@ { "name": "@azure/communication-sms", - "version": "1.2.0-beta.1", + "version": "1.2.0-beta.2", "description": "SDK for Azure Communication SMS service which facilitates the sending of SMS messages.", "sdk-type": "client", "main": "dist/index.js", @@ -68,7 +68,7 @@ "@azure/core-auth": "^1.3.0", "@azure/core-client": "^1.3.2", "@azure/core-rest-pipeline": "^1.3.2", - "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-tracing": "^1.0.0", "@azure/logger": "^1.0.0", "events": "^3.0.0", "tslib": "^2.2.0", diff --git a/sdk/communication/communication-sms/src/generated/src/index.ts b/sdk/communication/communication-sms/src/generated/src/index.ts index 7fec41dc8fd5..edcd173ba72a 100644 --- a/sdk/communication/communication-sms/src/generated/src/index.ts +++ b/sdk/communication/communication-sms/src/generated/src/index.ts @@ -8,5 +8,4 @@ export * from "./models"; export { SmsApiClient } from "./smsApiClient"; -export { SmsApiClientContext } from "./smsApiClientContext"; export * from "./operationsInterfaces"; diff --git a/sdk/communication/communication-sms/src/generated/src/models/index.ts b/sdk/communication/communication-sms/src/generated/src/models/index.ts index e08170980d8c..5080bd591535 100644 --- a/sdk/communication/communication-sms/src/generated/src/models/index.ts +++ b/sdk/communication/communication-sms/src/generated/src/models/index.ts @@ -61,7 +61,9 @@ export interface SmsSendResponseItem { /** Known values of {@link SmsSendResponseItemRepeatabilityResult} that the service accepts. */ export enum KnownSmsSendResponseItemRepeatabilityResult { + /** Accepted */ Accepted = "accepted", + /** Rejected */ Rejected = "rejected" } diff --git a/sdk/communication/communication-sms/src/generated/src/operations/sms.ts b/sdk/communication/communication-sms/src/generated/src/operations/sms.ts index 4ea871c531de..de5f6d9b2e94 100644 --- a/sdk/communication/communication-sms/src/generated/src/operations/sms.ts +++ b/sdk/communication/communication-sms/src/generated/src/operations/sms.ts @@ -6,11 +6,12 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import { tracingClient } from "../tracing"; import { Sms } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; -import { SmsApiClientContext } from "../smsApiClientContext"; +import { SmsApiClient } from "../smsApiClient"; import { SendMessageRequest, SmsSendOptionalParams, @@ -19,13 +20,13 @@ import { /** Class containing Sms operations. */ export class SmsImpl implements Sms { - private readonly client: SmsApiClientContext; + private readonly client: SmsApiClient; /** * Initialize a new instance of the class Sms class. * @param client Reference to the service client */ - constructor(client: SmsApiClientContext) { + constructor(client: SmsApiClient) { this.client = client; } @@ -34,13 +35,19 @@ export class SmsImpl implements Sms { * @param sendMessageRequest Represents the body of the send message request. * @param options The options parameters. */ - send( + async send( sendMessageRequest: SendMessageRequest, options?: SmsSendOptionalParams ): Promise { - return this.client.sendOperationRequest( - { sendMessageRequest, options }, - sendOperationSpec + return tracingClient.withSpan( + "SmsApiClient.send", + options ?? {}, + async (options) => { + return this.client.sendOperationRequest( + { sendMessageRequest, options }, + sendOperationSpec + ) as Promise; + } ); } } diff --git a/sdk/communication/communication-sms/src/generated/src/smsApiClient.ts b/sdk/communication/communication-sms/src/generated/src/smsApiClient.ts index 8430398a4f27..10f541c47083 100644 --- a/sdk/communication/communication-sms/src/generated/src/smsApiClient.ts +++ b/sdk/communication/communication-sms/src/generated/src/smsApiClient.ts @@ -6,20 +6,88 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +import * as coreClient from "@azure/core-client"; +import { + PipelineRequest, + PipelineResponse, + SendRequest +} from "@azure/core-rest-pipeline"; import { SmsImpl } from "./operations"; import { Sms } from "./operationsInterfaces"; -import { SmsApiClientContext } from "./smsApiClientContext"; import { SmsApiClientOptionalParams } from "./models"; -export class SmsApiClient extends SmsApiClientContext { +export class SmsApiClient extends coreClient.ServiceClient { + endpoint: string; + apiVersion: string; + /** * Initializes a new instance of the SmsApiClient class. * @param endpoint The communication resource, for example https://my-resource.communication.azure.com * @param options The parameter options */ constructor(endpoint: string, options?: SmsApiClientOptionalParams) { - super(endpoint, options); + if (endpoint === undefined) { + throw new Error("'endpoint' cannot be null"); + } + + // Initializing default values for options + if (!options) { + options = {}; + } + const defaults: SmsApiClientOptionalParams = { + requestContentType: "application/json; charset=utf-8" + }; + + const packageDetails = `azsdk-js-communication-sms/1.2.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` + : `${packageDetails}`; + + const optionsWithDefaults = { + ...defaults, + ...options, + userAgentOptions: { + userAgentPrefix + }, + baseUri: options.endpoint ?? options.baseUri ?? "{endpoint}" + }; + super(optionsWithDefaults); + // Parameter assignments + this.endpoint = endpoint; + + // Assigning values to Constant parameters + this.apiVersion = options.apiVersion || "2021-03-07"; this.sms = new SmsImpl(this); + this.addCustomApiVersionPolicy(options.apiVersion); + } + + /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */ + private addCustomApiVersionPolicy(apiVersion?: string) { + if (!apiVersion) { + return; + } + const apiVersionPolicy = { + name: "CustomApiVersionPolicy", + async sendRequest( + request: PipelineRequest, + next: SendRequest + ): Promise { + const param = request.url.split("?"); + if (param.length > 1) { + const newParams = param[1].split("&").map((item) => { + if (item.indexOf("api-version") > -1) { + return "api-version=" + apiVersion; + } else { + return item; + } + }); + request.url = param[0] + "?" + newParams.join("&"); + } + return next(request); + } + }; + this.pipeline.addPolicy(apiVersionPolicy); } sms: Sms; diff --git a/sdk/communication/communication-sms/src/generated/src/tracing.ts b/sdk/communication/communication-sms/src/generated/src/tracing.ts new file mode 100644 index 000000000000..a440fb5a6685 --- /dev/null +++ b/sdk/communication/communication-sms/src/generated/src/tracing.ts @@ -0,0 +1,15 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createTracingClient } from "@azure/core-tracing"; + +export const tracingClient = createTracingClient({ + namespace: "Microsoft.Communication", + packageName: "@azure/communication-sms", + packageVersion: "1.2.0-beta.1" +}); diff --git a/sdk/communication/communication-sms/src/smsClient.ts b/sdk/communication/communication-sms/src/smsClient.ts index 7d528a47b922..277576576c3e 100644 --- a/sdk/communication/communication-sms/src/smsClient.ts +++ b/sdk/communication/communication-sms/src/smsClient.ts @@ -3,19 +3,18 @@ /// import { - parseClientArguments, - isKeyCredential, createCommunicationAuthPolicy, + isKeyCredential, + parseClientArguments, } from "@azure/communication-common"; import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; import { CommonClientOptions, OperationOptions } from "@azure/core-client"; import { InternalPipelineOptions } from "@azure/core-rest-pipeline"; -import { SpanStatusCode } from "@azure/core-tracing"; import { SmsApiClient } from "./generated/src/smsApiClient"; -import { createSpan } from "./tracing"; -import { logger } from "./logger"; import { extractOperationOptions } from "./extractOperationOptions"; import { generateSendMessageRequest } from "./utils/smsUtils"; +import { logger } from "./logger"; +import { tracingClient } from "./generated/src/tracing"; /** * Client options used to configure SMS Client API requests. @@ -152,22 +151,12 @@ export class SmsClient { options: SmsSendOptions = { enableDeliveryReport: false } ): Promise { const { operationOptions, restOptions } = extractOperationOptions(options); - const { span, updatedOptions } = createSpan("SmsClient-Send", operationOptions); - - try { + return tracingClient.withSpan("SmsClient-Send", operationOptions, async (updatedOptions) => { const response = await this.api.sms.send( generateSendMessageRequest(sendRequest, restOptions), updatedOptions ); return response.value; - } catch (e: any) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: e.message, - }); - throw e; - } finally { - span.end(); - } + }); } } diff --git a/sdk/communication/communication-sms/src/tracing.ts b/sdk/communication/communication-sms/src/tracing.ts deleted file mode 100644 index a5dc8130b8cd..000000000000 --- a/sdk/communication/communication-sms/src/tracing.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.Communication", - namespace: "Microsoft.Communication", -}); diff --git a/sdk/communication/communication-sms/swagger/README.md b/sdk/communication/communication-sms/swagger/README.md index 12ae03ca6144..119456628953 100644 --- a/sdk/communication/communication-sms/swagger/README.md +++ b/sdk/communication/communication-sms/swagger/README.md @@ -16,9 +16,17 @@ require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/896d05e37d model-date-time-as-string: false optional-response-headers: true use-extension: - "@autorest/typescript": "6.0.0-beta.15" + "@autorest/typescript": "latest" azure-arm: false add-credentials: false package-version: 1.2.0-beta.1 v3: true + +tracing-info: + namespace: "Microsoft.Communication" + packagePrefix: "Azure.Communication" + +typescript: + generate-metadata: false + azure-arm: false ``` diff --git a/sdk/communication/communication-sms/test/internal/smsClient.internal.spec.ts b/sdk/communication/communication-sms/test/internal/smsClient.internal.spec.ts index 426826d15a53..39c418509012 100644 --- a/sdk/communication/communication-sms/test/internal/smsClient.internal.spec.ts +++ b/sdk/communication/communication-sms/test/internal/smsClient.internal.spec.ts @@ -9,7 +9,7 @@ */ import { matrix } from "@azure/test-utils"; -import { isLiveMode, isPlaybackMode, Recorder } from "@azure-tools/test-recorder"; +import { Recorder, isLiveMode, isPlaybackMode } from "@azure-tools/test-recorder"; import * as sinon from "sinon"; import { Uuid } from "../../src/utils/uuid"; import { diff --git a/sdk/communication/communication-sms/test/public/suites/smsClient.send.ts b/sdk/communication/communication-sms/test/public/suites/smsClient.send.ts index 5cb6d5f548f0..2bd4164a77ba 100644 --- a/sdk/communication/communication-sms/test/public/suites/smsClient.send.ts +++ b/sdk/communication/communication-sms/test/public/suites/smsClient.send.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. import { assert } from "chai"; -import { SmsSendRequest, SmsSendOptions } from "../../../src"; +import { SmsSendOptions, SmsSendRequest } from "../../../src"; import { env } from "@azure-tools/test-recorder"; import { Context } from "mocha"; import { assertIsFailureResult, assertIsSuccessResult } from "../utils/assertHelpers"; diff --git a/sdk/communication/communication-sms/test/public/utils/mockHttpClient.ts b/sdk/communication/communication-sms/test/public/utils/mockHttpClient.ts index 89601a69042a..a14e72a49432 100644 --- a/sdk/communication/communication-sms/test/public/utils/mockHttpClient.ts +++ b/sdk/communication/communication-sms/test/public/utils/mockHttpClient.ts @@ -2,10 +2,10 @@ // Licensed under the MIT license. import { - createHttpHeaders, HttpClient, PipelineRequest, PipelineResponse, + createHttpHeaders, } from "@azure/core-rest-pipeline"; export class MockHttpClient implements HttpClient {