From bb90e897de1276451ff48738df276ad40d4d55e1 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Fri, 14 Jun 2024 18:25:03 +0800 Subject: [PATCH 01/18] Remove the hard-code for patch LRO --- .../src/modular/helpers/operationHelpers.ts | 13 +++---------- .../src/modular/serialization/operationHelpers.ts | 13 +++---------- 2 files changed, 6 insertions(+), 20 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 1e7598d5a4..a63e5d2f45 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -179,20 +179,13 @@ export function getDeserializePrivateFunction( } } - let deserializedType = isLroOnly + const deserializedType = isLroOnly ? operation?.lroMetadata?.finalResult : response.type; - let hasLroSubPath = operation?.lroMetadata?.finalResultPath !== undefined; - let deserializedRoot = hasLroSubPath + const hasLroSubPath = operation?.lroMetadata?.finalResultPath !== undefined; + const deserializedRoot = hasLroSubPath ? `result.body.${operation?.lroMetadata?.finalResultPath}` : "result.body"; - // TODO: Hard-coded for LRO PATCH case for now - // https://github.com/Azure/autorest.typescript/issues/2314 - if (isLroOnly && operation.method.toLowerCase() === "patch") { - deserializedType = response.type; - hasLroSubPath = false; - deserializedRoot = "result.body"; - } if (isLroOnly) { const lroLogicalResponse = getRLCLroLogicalResponse(operation.rlcResponse); statements.push(`result = result as ${lroLogicalResponse};`); diff --git a/packages/typespec-ts/src/modular/serialization/operationHelpers.ts b/packages/typespec-ts/src/modular/serialization/operationHelpers.ts index a828d27a09..9b76447d65 100644 --- a/packages/typespec-ts/src/modular/serialization/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/serialization/operationHelpers.ts @@ -181,20 +181,13 @@ export function getDeserializePrivateFunction( } } - let deserializedType = isLroOnly + const deserializedType = isLroOnly ? operation?.lroMetadata?.finalResult : response?.type ?? "void"; // Is setting void here correct? We are handling the case where no response above but here we are - let hasLroSubPath = operation?.lroMetadata?.finalResultPath !== undefined; - let deserializedRoot = hasLroSubPath + const hasLroSubPath = operation?.lroMetadata?.finalResultPath !== undefined; + const deserializedRoot = hasLroSubPath ? `result.body.${operation?.lroMetadata?.finalResultPath}` : "result.body"; - // TODO: Hard-coded for LRO PATCH case for now - // https://github.com/Azure/autorest.typescript/issues/2314 - if (isLroOnly && operation.method.toLowerCase() === "patch") { - deserializedType = response.type; - hasLroSubPath = false; - deserializedRoot = "result.body"; - } if (isLroOnly) { const lroLogicalResponse = getRLCLroLogicalResponse(operation.rlcResponse); statements.push(`result = result as ${lroLogicalResponse};`); From 1e171546019e3b5196b5399538b874ab9e8708f8 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 17 Jun 2024 10:42:37 +0800 Subject: [PATCH 02/18] Update the dpg patch lro --- .../typespec-ts/review/widget_dpg.api.md | 9 --- .../typespec-ts/src/api/budgets/index.ts | 65 +------------------ .../typespec-ts/src/classic/budgets/index.ts | 17 +---- .../generated/typespec-ts/src/index.ts | 1 - .../generated/typespec-ts/src/models/index.ts | 1 - .../typespec-ts/src/models/options.ts | 9 --- .../typespec-ts/src/rest/clientDefinitions.ts | 20 ------ .../typespec-ts/src/rest/isUnexpected.ts | 22 +------ .../typespec-ts/src/rest/parameters.ts | 26 -------- .../typespec-ts/src/rest/pollingHelper.ts | 16 ----- .../typespec-ts/src/rest/responses.ts | 41 ------------ .../typespec-ts/src/restorePollerHelpers.ts | 7 +- .../test/widget_dpg/spec/main.tsp | 5 +- 13 files changed, 9 insertions(+), 230 deletions(-) diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md index f71c63ecda..3e8ce67dd6 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md @@ -31,19 +31,10 @@ export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) -export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; - updateIntervalInMs?: number; -} - // @public (undocumented) export interface BudgetsOperations { // (undocumented) createOrReplace: (name: string, resource: User, options?: BudgetsCreateOrReplaceOptionalParams) => PollerLike, User>; - // (undocumented) - createOrUpdate: (name: string, resource: User, options?: BudgetsCreateOrUpdateOptionalParams) => PollerLike, User>; } // @public diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts index cb9ddda7eb..a5bdc3a025 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts @@ -9,10 +9,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, - BudgetsCreateOrUpdateLogicalResponse, isUnexpected, WidgetServiceContext as Client, } from "../../rest/index.js"; @@ -21,10 +17,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; -import { - BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, -} from "../../models/options.js"; +import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; export function _createOrReplaceSend( context: Client, @@ -79,59 +72,3 @@ export function createOrReplace( _createOrReplaceSend(context, name, resource, options), }) as PollerLike, User>; } - -export function _createOrUpdateSend( - context: Client, - name: string, - resource: User, - options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, -): StreamableMethod< - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - | BudgetsCreateOrUpdateLogicalResponse -> { - return context - .path("/budgets/widgets/createOrUpdate/users/{name}", name) - .patch({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, - body: { role: resource["role"], id: resource["id"] }, - }); -} - -export async function _createOrUpdateDeserialize( - result: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - | BudgetsCreateOrUpdateLogicalResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - result = result as BudgetsCreateOrUpdateLogicalResponse; - return { - name: result.body["name"], - role: result.body["role"], - id: result.body["id"], - }; -} - -/** Long-running resource create or update operation template. */ -export function createOrUpdate( - context: Client, - name: string, - resource: User, - options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, -): PollerLike, User> { - return getLongRunningPoller(context, _createOrUpdateDeserialize, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _createOrUpdateSend(context, name, resource, options), - }) as PollerLike, User>; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts index 2ed6f2c4f6..304428e7fb 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts @@ -3,12 +3,9 @@ import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; import { User } from "../../models/models.js"; -import { createOrReplace, createOrUpdate } from "../../api/budgets/index.js"; +import { createOrReplace } from "../../api/budgets/index.js"; import { PollerLike, OperationState } from "@azure/core-lro"; -import { - BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, -} from "../../models/options.js"; +import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; export interface BudgetsOperations { createOrReplace: ( @@ -16,11 +13,6 @@ export interface BudgetsOperations { resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => PollerLike, User>; - createOrUpdate: ( - name: string, - resource: User, - options?: BudgetsCreateOrUpdateOptionalParams, - ) => PollerLike, User>; } export function getBudgets(context: WidgetServiceContext) { @@ -30,11 +22,6 @@ export function getBudgets(context: WidgetServiceContext) { resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => createOrReplace(context, name, resource, options), - createOrUpdate: ( - name: string, - resource: User, - options?: BudgetsCreateOrUpdateOptionalParams, - ) => createOrUpdate(context, name, resource, options), }; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts index 64e99578d0..d589c7727e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts @@ -26,7 +26,6 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index 74ec7ce46d..9c53707361 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -23,7 +23,6 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts index e9041d06ba..76d2655dd1 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts @@ -39,12 +39,3 @@ export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; } - -export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** The API version to use for this operation. */ - apiVersion?: string; - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts index 14643f2b13..246c23ed06 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -12,7 +12,6 @@ import { WidgetsCreateOrReplaceParameters, WidgetsAnalyzeWidgetParameters, BudgetsCreateOrReplaceParameters, - BudgetsCreateOrUpdateParameters, } from "./parameters.js"; import { WidgetsListWidgets200Response, @@ -37,9 +36,6 @@ import { BudgetsCreateOrReplace200Response, BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; @@ -136,17 +132,6 @@ export interface BudgetsCreateOrReplace { >; } -export interface BudgetsCreateOrUpdate { - /** Long-running resource create or update operation template. */ - patch( - options: BudgetsCreateOrUpdateParameters, - ): StreamableMethod< - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - >; -} - export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): WidgetsListWidgets; @@ -166,11 +151,6 @@ export interface Routes { path: "/budgets/widgets/createOrReplace/users/{name}", name: string, ): BudgetsCreateOrReplace; - /** Resource for '/budgets/widgets/createOrUpdate/users/\{name\}' has methods for the following verbs: patch */ - ( - path: "/budgets/widgets/createOrUpdate/users/{name}", - name: string, - ): BudgetsCreateOrUpdate; } export type WidgetServiceContext = Client & { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts index f6205b939e..2ee6febfd6 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts @@ -26,10 +26,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceLogicalResponse, BudgetsCreateOrReplaceDefaultResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateLogicalResponse, - BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -45,8 +41,6 @@ const responseMap: Record = { "POST /widgets/{id}/analyze": ["200"], "GET /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], "PUT /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], - "GET /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], - "PATCH /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], }; export function isUnexpected( @@ -93,13 +87,6 @@ export function isUnexpected( | BudgetsCreateOrReplaceLogicalResponse | BudgetsCreateOrReplaceDefaultResponse, ): response is BudgetsCreateOrReplaceDefaultResponse; -export function isUnexpected( - response: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, -): response is BudgetsCreateOrUpdateDefaultResponse; export function isUnexpected( response: | WidgetsListWidgets200Response @@ -125,11 +112,7 @@ export function isUnexpected( | BudgetsCreateOrReplace200Response | BudgetsCreateOrReplace201Response | BudgetsCreateOrReplaceLogicalResponse - | BudgetsCreateOrReplaceDefaultResponse - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, + | BudgetsCreateOrReplaceDefaultResponse, ): response is | WidgetsListWidgetsDefaultResponse | WidgetsCreateWidgetDefaultResponse @@ -140,8 +123,7 @@ export function isUnexpected( | WidgetsDeleteWidgetDefaultResponse | WidgetsCreateOrReplaceDefaultResponse | WidgetsAnalyzeWidgetDefaultResponse - | BudgetsCreateOrReplaceDefaultResponse - | BudgetsCreateOrUpdateDefaultResponse { + | BudgetsCreateOrReplaceDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts index 24abbd70ba..8c547f10c0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts @@ -103,29 +103,3 @@ export type BudgetsCreateOrReplaceParameters = BudgetsCreateOrReplaceQueryParam & BudgetsCreateOrReplaceBodyParam & RequestParameters; -/** The resource instance. */ -export type UserResourceMergeAndPatch = Partial; - -export interface BudgetsCreateOrUpdateBodyParam { - /** The resource instance. */ - body: UserResourceMergeAndPatch; -} - -export interface BudgetsCreateOrUpdateQueryParamProperties { - /** The API version to use for this operation. */ - "api-version": string; -} - -export interface BudgetsCreateOrUpdateQueryParam { - queryParameters: BudgetsCreateOrUpdateQueryParamProperties; -} - -export interface BudgetsCreateOrUpdateMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type BudgetsCreateOrUpdateParameters = BudgetsCreateOrUpdateQueryParam & - BudgetsCreateOrUpdateMediaTypesParam & - BudgetsCreateOrUpdateBodyParam & - RequestParameters; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts index 774cb10a5b..3426531d4a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts @@ -20,10 +20,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, - BudgetsCreateOrUpdateLogicalResponse, } from "./responses.js"; /** @@ -104,18 +100,6 @@ export interface SimplePollerLike< * @param options - Options to set a resume state or custom polling interval. * @returns - A poller object to poll for operation state updates and eventually get the final response. */ -export async function getLongRunningPoller< - TResult extends - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, ->( - client: Client, - initialResponse: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; export async function getLongRunningPoller< TResult extends | WidgetsCreateOrReplaceLogicalResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts index c573254135..4b63997112 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts @@ -179,44 +179,3 @@ export interface BudgetsCreateOrReplaceLogicalResponse extends HttpResponse { status: "200"; body: UserOutput; } - -export interface BudgetsCreateOrUpdate200Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; -} - -/** The request has succeeded. */ -export interface BudgetsCreateOrUpdate200Response extends HttpResponse { - status: "200"; - body: UserOutput; - headers: RawHttpHeaders & BudgetsCreateOrUpdate200Headers; -} - -export interface BudgetsCreateOrUpdate201Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface BudgetsCreateOrUpdate201Response extends HttpResponse { - status: "201"; - body: UserOutput; - headers: RawHttpHeaders & BudgetsCreateOrUpdate201Headers; -} - -export interface BudgetsCreateOrUpdateDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface BudgetsCreateOrUpdateDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & BudgetsCreateOrUpdateDefaultHeaders; -} - -/** The final response for long-running createOrUpdate operation */ -export interface BudgetsCreateOrUpdateLogicalResponse extends HttpResponse { - status: "200"; - body: UserOutput; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts index a1f7a1e36b..2181a3515e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts @@ -11,10 +11,7 @@ import { WidgetServiceContext } from "./api/widgetServiceContext.js"; import { WidgetServiceClient } from "./widgetServiceClient.js"; import { getLongRunningPoller } from "./api/pollingHelpers.js"; import { _createOrReplaceDeserialize } from "./api/widgets/index.js"; -import { - _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets, - _createOrUpdateDeserialize, -} from "./api/budgets/index.js"; +import { _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets } from "./api/budgets/index.js"; import { PathUncheckedResponse, OperationOptions, @@ -84,8 +81,6 @@ const deserializeMap: Record = { _createOrReplaceDeserialize, "PUT /budgets/widgets/createOrReplace/users/{name}": _createOrReplaceDeserializeBudgets, - "PATCH /budgets/widgets/createOrUpdate/users/{name}": - _createOrUpdateDeserialize, }; function getDeserializationHelper( diff --git a/packages/typespec-test/test/widget_dpg/spec/main.tsp b/packages/typespec-test/test/widget_dpg/spec/main.tsp index a75784a198..7423dc7513 100644 --- a/packages/typespec-test/test/widget_dpg/spec/main.tsp +++ b/packages/typespec-test/test/widget_dpg/spec/main.tsp @@ -178,6 +178,7 @@ interface Budgets { op createOrReplace is ResourceOperations.LongRunningResourceCreateOrReplace; // the patch case for lro - @route("/widgets/createOrUpdate") - op createOrUpdate is ResourceOperations.LongRunningResourceCreateOrUpdate; + // DPG patch LRO has issue but no real case met yet + // @route("/widgets/createOrUpdate") + // op createOrUpdate is ResourceOperations.LongRunningResourceCreateOrUpdate; } From fba26fe6bf1d94b2f9b1e551861b15d586dc95eb Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 17 Jun 2024 12:58:33 +0800 Subject: [PATCH 03/18] Update the load testing cases --- .../administrationOperationsClient.ts | 38 +- .../api/administrationOperationsContext.ts | 6 +- .../src/administrationOperations/api/index.ts | 2 +- .../api/operations.ts | 466 +++++++-- .../src/administrationOperations/index.ts | 16 +- .../administrationOperations/models/index.ts | 16 +- .../administrationOperations/models/models.ts | 394 +++---- .../models/options.ts | 18 +- .../generated/typespec-ts/src/index.ts | 38 +- .../typespec-ts/src/rest/clientDefinitions.ts | 115 +-- .../generated/typespec-ts/src/rest/index.ts | 7 +- .../typespec-ts/src/rest/isUnexpected.ts | 89 +- ...tingClient.ts => loadTestServiceClient.ts} | 10 +- .../generated/typespec-ts/src/rest/models.ts | 149 ++- .../typespec-ts/src/rest/outputModels.ts | 239 +++-- .../typespec-ts/src/rest/parameters.ts | 81 +- .../typespec-ts/src/rest/pollingHelper.ts | 223 ---- .../typespec-ts/src/rest/responses.ts | 119 ++- .../src/testRunOperations/api/index.ts | 4 +- .../src/testRunOperations/api/operations.ts | 965 ++++++++++++++---- .../testRunOperations/api/pollingHelpers.ts | 139 --- .../api/testRunOperationsContext.ts | 6 +- .../src/testRunOperations/index.ts | 19 +- .../src/testRunOperations/models/index.ts | 18 +- .../src/testRunOperations/models/models.ts | 394 +++---- .../src/testRunOperations/models/options.ts | 41 +- .../testRunOperations/restorePollerHelpers.ts | 157 --- .../testRunOperationsClient.ts | 73 +- .../test/loadtesting_modular/spec/client.tsp | 77 +- .../test/loadtesting_modular/spec/main.tsp | 20 +- .../test/loadtesting_modular/spec/models.tsp | 820 +++++++++------ .../test/loadtesting_modular/spec/routes.tsp | 486 ++++----- 32 files changed, 2863 insertions(+), 2382 deletions(-) rename packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/{azureLoadTestingClient.ts => loadTestServiceClient.ts} (84%) delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index b83a0d4a29..aba71240a2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -5,7 +5,9 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, - FileInfo, + TestFileInfo, + FileType, + FileStatus, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -27,7 +29,7 @@ import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createAdministrationOperations, AdministrationOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, createOrUpdateTest, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, @@ -45,7 +47,7 @@ import { export { AdministrationOperationsClientOptions } from "./api/administrationOperationsContext.js"; export class AdministrationOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -62,7 +64,7 @@ export class AdministrationOperationsClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ createOrUpdateTest( testId: string, body: Test, @@ -71,7 +73,7 @@ export class AdministrationOperationsClient { return createOrUpdateTest(this._client, testId, body, options); } - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ createOrUpdateAppComponents( testId: string, body: TestAppComponents, @@ -112,7 +114,7 @@ export class AdministrationOperationsClient { return getServerMetricsConfig(this._client, testId, options); } - /** Get load test details by test name */ + /** Get load test details by test Id */ getTest( testId: string, options: GetTestOptionalParams = { requestOptions: {} }, @@ -120,12 +122,18 @@ export class AdministrationOperationsClient { return getTest(this._client, testId, options); } - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return getTestFile(this._client, testId, fileName, options); } @@ -133,7 +141,7 @@ export class AdministrationOperationsClient { listTestFiles( testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -148,7 +156,7 @@ export class AdministrationOperationsClient { } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -157,7 +165,13 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return uploadTestFile(this._client, testId, fileName, body, options); } @@ -170,7 +184,7 @@ export class AdministrationOperationsClient { return deleteTestFile(this._client, testId, fileName, options); } - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ deleteTest( testId: string, options: DeleteTestOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index b4a3f0c5d7..318287a1eb 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; export interface AdministrationOperationsClientOptions extends ClientOptions { @@ -11,13 +11,13 @@ export interface AdministrationOperationsClientOptions extends ClientOptions { apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createAdministrationOperations( endpointParam: string, credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts index f7564cbffd..342aa50e7a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts @@ -4,7 +4,7 @@ export { createAdministrationOperations, AdministrationOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./administrationOperationsContext.js"; export { createOrUpdateTest, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index 3384c98052..78223a86d8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -3,17 +3,18 @@ import { Test, - FileInfo, + TestFileInfo, + FileType, + FileStatus, TestAppComponents, TestServerMetricConfig, - PagedFileInfo, + PagedTestFileInfo, PagedTest, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestAdministrationCreateOrUpdateAppComponents200Response, LoadTestAdministrationCreateOrUpdateAppComponents201Response, LoadTestAdministrationCreateOrUpdateAppComponentsDefaultResponse, @@ -41,6 +42,7 @@ import { LoadTestAdministrationListTestsDefaultResponse, LoadTestAdministrationUploadTestFile201Response, LoadTestAdministrationUploadTestFileDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -82,6 +84,14 @@ export function _createOrUpdateTestSend( passFailCriteria: !body.passFailCriteria ? undefined : { passFailMetrics: body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !body.autoStopCriteria + ? undefined + : { + autoStopDisabled: body.autoStopCriteria?.["autoStopDisabled"], + errorRate: body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: body["secrets"], certificate: !body.certificate ? undefined @@ -105,6 +115,14 @@ export function _createOrUpdateTestSend( body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -119,9 +137,12 @@ export function _createOrUpdateTestSend( ], }, }, + baselineTestRunId: body["baselineTestRunId"], description: body["description"], displayName: body["displayName"], subnetId: body["subnetId"], + kind: body["kind"], + publicIPDisabled: body["publicIPDisabled"], keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], }, @@ -142,6 +163,14 @@ export async function _createOrUpdateTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -166,6 +195,14 @@ export async function _createOrUpdateTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -180,21 +217,28 @@ export async function _createOrUpdateTestDeserialize( ], }, }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -207,15 +251,21 @@ export async function _createOrUpdateTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -228,15 +278,21 @@ export async function _createOrUpdateTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -250,13 +306,13 @@ export async function _createOrUpdateTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -264,7 +320,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -274,14 +336,49 @@ export async function _createOrUpdateTestDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" + ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -290,16 +387,24 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create a new test or update an existing test. */ +/** Create a new test or update an existing test by providing the test Id. */ export async function createOrUpdateTest( context: Client, testId: string, @@ -343,14 +448,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test */ +/** Add an app component to a test by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testId: string, @@ -401,9 +512,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -451,9 +568,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -493,9 +616,15 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -536,6 +665,14 @@ export async function _getTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -560,6 +697,14 @@ export async function _getTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -574,21 +719,28 @@ export async function _getTestDeserialize( ], }, }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -601,15 +753,21 @@ export async function _getTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -622,15 +780,21 @@ export async function _getTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -644,13 +808,13 @@ export async function _getTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -658,7 +822,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -668,14 +838,49 @@ export async function _getTestDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" + ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -684,16 +889,24 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get load test details by test name */ +/** Get load test details by test Id */ export async function getTest( context: Client, testId: string, @@ -721,28 +934,42 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } -/** Get test file by the file name. */ +/** Get all the files that are associated with a test. */ export async function getTestFile( context: Client, testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -764,17 +991,20 @@ export async function _listTestFilesDeserialize( result: | LoadTestAdministrationListTestFiles200Response | LoadTestAdministrationListTestFilesDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { value: result.body["value"].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -787,7 +1017,7 @@ export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), @@ -810,8 +1040,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime, - lastModifiedEndTime: options?.lastModifiedEndTime, + lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), maxpagesize: options?.maxpagesize, }, }); @@ -831,6 +1061,14 @@ export async function _listTestsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -854,6 +1092,14 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -868,17 +1114,23 @@ export async function _listTestsDeserialize( ], }, }, + baselineTestRunId: p["baselineTestRunId"], inputArtifacts: !p.inputArtifacts ? undefined : { configFileInfo: !p.inputArtifacts?.configFileInfo ? undefined : { - url: p.inputArtifacts?.configFileInfo?.["url"], fileName: p.inputArtifacts?.configFileInfo?.["fileName"], + url: p.inputArtifacts?.configFileInfo?.["url"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"], + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -889,11 +1141,18 @@ export async function _listTestsDeserialize( testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo ? undefined : { - url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: @@ -904,11 +1163,18 @@ export async function _listTestsDeserialize( userPropFileInfo: !p.inputArtifacts?.userPropFileInfo ? undefined : { - url: p.inputArtifacts?.userPropFileInfo?.["url"], fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], + url: p.inputArtifacts?.userPropFileInfo?.["url"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -920,15 +1186,21 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -938,14 +1210,44 @@ export async function _listTestsDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], + url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: p.inputArtifacts?.["additionalFileInfo"] === undefined ? p.inputArtifacts?.["additionalFileInfo"] : p.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -954,11 +1256,19 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], + kind: p["kind"], + publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -1005,23 +1315,31 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -1031,7 +1349,13 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _uploadTestFileSend( context, testId, @@ -1104,7 +1428,7 @@ export async function _deleteTestDeserialize( return; } -/** Delete a test by its name. */ +/** Delete a test by its test Id. */ export async function deleteTest( context: Client, testId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index cf7499d4f2..657642a135 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -13,6 +13,7 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -20,27 +21,28 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, ResourceMetric, - PagedFileInfo, - PagedTest, APIVersions, TestRun, ErrorDetails, TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -48,17 +50,17 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, MetricValue, DimensionValue, + PagedTestFileInfo, + PagedTest, PagedTestRun, - PagedDimensionValueList, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index de820d25e0..82939ca23f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -9,6 +9,7 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -16,27 +17,28 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, ResourceMetric, - PagedFileInfo, - PagedTest, APIVersions, TestRun, ErrorDetails, TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -44,17 +46,17 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, MetricValue, DimensionValue, + PagedTestFileInfo, + PagedTest, PagedTestRun, - PagedDimensionValueList, } from "./models.js"; export { CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index daab3ea449..27018ab1f3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -13,32 +15,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -77,28 +85,28 @@ export interface PassFailMetric { readonly result?: PFResult; } -/** */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; -/** */ -export type PFAction = "continue" | "stop"; -/** */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Metrics for pass/fail criteria. */ +/** "response_time_ms", "latency", "error", "requests", "requests_per_sec" */ +export type PFMetrics = string; +/** Aggregation functions for pass/fail criteria. */ +/** "count", "percentage", "avg", "p50", "p90", "p95", "p99", "min", "max" */ +export type PFAgFunc = string; +/** Action to take on failure of pass/fail criteria. */ +/** "continue", "stop" */ +export type PFAction = string; +/** Pass/fail criteria result. */ +/** "passed", "undetermined", "failed" */ +export type PFResult = string; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} /** Secret */ export interface Secret { @@ -108,8 +116,9 @@ export interface Secret { type?: SecretType; } -/** */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Types of secrets supported. */ +/** "AKV_SECRET_URI", "SECRET_VALUE" */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -121,15 +130,13 @@ export interface CertificateMetadata { name?: string; } -/** */ -export type CertificateType = "AKV_CERT_URI"; +/** Types of certificates supported. */ +/** "AKV_CERT_URI" */ +export type CertificateType = string; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -143,66 +150,69 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; - -/** Test app component */ +/** Types of file supported. */ +/** "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG_JSON" */ +export type FileType = string; +/** File status. */ +/** "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" */ +export type FileStatus = string; +/** Test kind */ +/** "URL", "JMX" */ +export type TestKind = string; + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -212,30 +222,24 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -255,13 +259,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -290,31 +294,18 @@ export interface ResourceMetric { resourceType: string; } -/** Collection of files. */ -export interface PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - +/** Azure Load Testing API versions. */ /** */ -export type APIVersions = "2022-11-01"; +export type APIVersions = "2022-11-01" | "2023-04-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -347,24 +338,28 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -418,45 +413,59 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; } -/** */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ +/** "PASSED", "NOT_APPLICABLE", "FAILED" */ +export type PFTestResult = string; +/** Test run status. */ +/** "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" */ +export type Status = string; /** Test run app component */ export interface TestRunAppComponents { @@ -468,12 +477,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -488,21 +497,28 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Time Grain */ +/** "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ +export type TimeGrain = string; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -542,25 +558,12 @@ export interface NameAndDesc { name?: string; } -/** */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; -/** */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Aggregation type. */ +/** "Average", "Count", "None", "Total", "Percentile90", "Percentile95", "Percentile99" */ +export type AggregationType = string; +/** Metric unit. */ +/** "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -571,9 +574,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -588,7 +588,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -608,7 +608,7 @@ export interface DimensionFilter { } /** The response to a metrics query. */ -export interface PagedTimeSeriesElement { +export interface Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -625,8 +625,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -639,18 +639,26 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ -export interface PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; +/** Paged collection of TestFileInfo items */ +export interface PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; /** The link to the next page of items */ nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of Test items */ +export interface PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ +export interface PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; /** The link to the next page of items */ nextLink?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts index 17e195ddcf..62943adcc2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts @@ -5,16 +5,19 @@ import { OperationOptions } from "@azure-rest/core-client"; import { FileType } from "./models.js"; export interface CreateOrUpdateTestOptionalParams extends OperationOptions { + /** This request has a JSON Merge Patch body. */ contentType?: string; } export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -41,21 +44,16 @@ export interface ListTestsOptionalParams extends OperationOptions { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date; /** Number of results in response. */ maxpagesize?: number; } export interface UploadTestFileOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; /** File type */ fileType?: FileType; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 966f2b5547..d491e00954 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -13,6 +13,7 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -20,27 +21,28 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, ResourceMetric, - PagedFileInfo, - PagedTest, APIVersions, TestRun, ErrorDetails, TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -48,17 +50,17 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, MetricValue, DimensionValue, + PagedTestFileInfo, + PagedTest, PagedTestRun, - PagedDimensionValueList, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -79,10 +81,6 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperations/testRunOperationsClient.js"; -export { - restorePoller, - RestorePollerOptions, -} from "./testRunOperations/restorePollerHelpers.js"; export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, @@ -91,6 +89,7 @@ export { PFAgFunc as TestRunOperationsClientPFAgFunc, PFAction as TestRunOperationsClientPFAction, PFResult as TestRunOperationsClientPFResult, + AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, @@ -98,27 +97,28 @@ export { LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, - FileInfo as TestRunOperationsClientFileInfo, + TestFileInfo as TestRunOperationsClientTestFileInfo, FileType as TestRunOperationsClientFileType, FileStatus as TestRunOperationsClientFileStatus, + TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, TestServerMetricConfig as TestRunOperationsClientTestServerMetricConfig, ResourceMetric as TestRunOperationsClientResourceMetric, - PagedFileInfo as TestRunOperationsClientPagedFileInfo, - PagedTest as TestRunOperationsClientPagedTest, APIVersions as TestRunOperationsClientAPIVersions, TestRun as TestRunOperationsClientTestRun, ErrorDetails as TestRunOperationsClientErrorDetails, TestRunStatistics as TestRunOperationsClientTestRunStatistics, TestRunArtifacts as TestRunOperationsClientTestRunArtifacts, TestRunInputArtifacts as TestRunOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, PFTestResult as TestRunOperationsClientPFTestResult, Status as TestRunOperationsClientStatus, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, - Interval as TestRunOperationsClientInterval, + TimeGrain as TestRunOperationsClientTimeGrain, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, @@ -126,18 +126,18 @@ export { AggregationType as TestRunOperationsClientAggregationType, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, - TimeGrain as TestRunOperationsClientTimeGrain, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, MetricNamespace as TestRunOperationsClientMetricNamespace, MetricRequestPayload as TestRunOperationsClientMetricRequestPayload, DimensionFilter as TestRunOperationsClientDimensionFilter, - PagedTimeSeriesElement as TestRunOperationsClientPagedTimeSeriesElement, + Metrics as TestRunOperationsClientMetrics, TimeSeriesElement as TestRunOperationsClientTimeSeriesElement, MetricValue as TestRunOperationsClientMetricValue, DimensionValue as TestRunOperationsClientDimensionValue, + PagedTestFileInfo as TestRunOperationsClientPagedTestFileInfo, + PagedTest as TestRunOperationsClientPagedTest, PagedTestRun as TestRunOperationsClientPagedTestRun, - PagedDimensionValueList as TestRunOperationsClientPagedDimensionValueList, - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts index 2d1d85129a..a7c8c3ac30 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -14,12 +14,12 @@ import { LoadTestAdministrationGetAppComponentsParameters, LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters, LoadTestAdministrationGetServerMetricsConfigParameters, - LoadTestRunDeleteTestRunParameters, - LoadTestRunCreateOrUpdateTestRunParameters, LoadTestRunGetTestRunParameters, - LoadTestRunGetTestRunFileParameters, + LoadTestRunCreateOrUpdateTestRunParameters, + LoadTestRunDeleteTestRunParameters, LoadTestRunListTestRunsParameters, - LoadTestRunStopTestRunParameters, + LoadTestRunGetTestRunFileParameters, + LoadTestRunStopParameters, LoadTestRunListMetricNamespacesParameters, LoadTestRunListMetricDefinitionsParameters, LoadTestRunListMetricsParameters, @@ -27,7 +27,7 @@ import { LoadTestRunCreateOrUpdateAppComponentsParameters, LoadTestRunGetAppComponentsParameters, LoadTestRunCreateOrUpdateServerMetricsConfigParameters, - LoadTestRunTestRunListServerMetricsConfigParameters, + LoadTestRunGetServerMetricsConfigParameters, } from "./parameters.js"; import { LoadTestAdministrationCreateOrUpdateTest200Response, @@ -57,19 +57,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -86,13 +86,13 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; export interface LoadTestAdministrationCreateOrUpdateTest { - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ patch( options: LoadTestAdministrationCreateOrUpdateTestParameters, ): StreamableMethod< @@ -100,14 +100,14 @@ export interface LoadTestAdministrationCreateOrUpdateTest { | LoadTestAdministrationCreateOrUpdateTest201Response | LoadTestAdministrationCreateOrUpdateTestDefaultResponse >; - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ delete( options?: LoadTestAdministrationDeleteTestParameters, ): StreamableMethod< | LoadTestAdministrationDeleteTest204Response | LoadTestAdministrationDeleteTestDefaultResponse >; - /** Get load test details by test name */ + /** Get load test details by test Id */ get( options?: LoadTestAdministrationGetTestParameters, ): StreamableMethod< @@ -131,7 +131,7 @@ export interface LoadTestAdministrationListTests { export interface LoadTestAdministrationUploadTestFile { /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -141,7 +141,7 @@ export interface LoadTestAdministrationUploadTestFile { | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse >; - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ get( options?: LoadTestAdministrationGetTestFileParameters, ): StreamableMethod< @@ -168,7 +168,7 @@ export interface LoadTestAdministrationListTestFiles { } export interface LoadTestAdministrationCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ patch( options: LoadTestAdministrationCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -203,15 +203,14 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfig { >; } -export interface LoadTestRunDeleteTestRun { - /** Delete a test run by its name. */ - delete( - options?: LoadTestRunDeleteTestRunParameters, +export interface LoadTestRunGetTestRun { + /** Get test run details by test run Id. */ + get( + options?: LoadTestRunGetTestRunParameters, ): StreamableMethod< - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse >; - /** Create and start a new test run with the given name. */ + /** Create and start a new test run with the given test run Id. */ patch( options: LoadTestRunCreateOrUpdateTestRunParameters, ): StreamableMethod< @@ -219,11 +218,21 @@ export interface LoadTestRunDeleteTestRun { | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse >; - /** Get test run details by name. */ + /** Delete an existing load test run by providing the testRunId. */ + delete( + options?: LoadTestRunDeleteTestRunParameters, + ): StreamableMethod< + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse + >; +} + +export interface LoadTestRunListTestRuns { + /** Get all test runs for the given filters. */ get( - options?: LoadTestRunGetTestRunParameters, + options?: LoadTestRunListTestRunsParameters, ): StreamableMethod< - LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse + LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse >; } @@ -237,21 +246,12 @@ export interface LoadTestRunGetTestRunFile { >; } -export interface LoadTestRunListTestRuns { - /** Get all test runs with given filters */ - get( - options?: LoadTestRunListTestRunsParameters, - ): StreamableMethod< - LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - >; -} - -export interface LoadTestRunStopTestRun { - /** Stop test run by name. */ +export interface LoadTestRunStop { + /** Stop test run by test run Id. */ post( - options?: LoadTestRunStopTestRunParameters, + options?: LoadTestRunStopParameters, ): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse + LoadTestRunStop200Response | LoadTestRunStopDefaultResponse >; } @@ -268,7 +268,7 @@ export interface LoadTestRunListMetricNamespaces { export interface LoadTestRunListMetricDefinitions { /** List the metric definitions for a load test run. */ get( - options?: LoadTestRunListMetricDefinitionsParameters, + options: LoadTestRunListMetricDefinitionsParameters, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response | LoadTestRunListMetricDefinitionsDefaultResponse @@ -295,7 +295,7 @@ export interface LoadTestRunListMetricDimensionValues { } export interface LoadTestRunCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ patch( options: LoadTestRunCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -324,12 +324,12 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfig { | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse >; - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ get( - options?: LoadTestRunTestRunListServerMetricsConfigParameters, + options?: LoadTestRunGetServerMetricsConfigParameters, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse >; } @@ -362,21 +362,18 @@ export interface Routes { path: "/tests/{testId}/server-metrics-config", testId: string, ): LoadTestAdministrationCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: delete, patch, get */ - (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunDeleteTestRun; + /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: get, patch, delete */ + (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunGetTestRun; + /** Resource for '/test-runs' has methods for the following verbs: get */ + (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}/files/\{fileName\}' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/files/{fileName}", testRunId: string, fileName: string, ): LoadTestRunGetTestRunFile; - /** Resource for '/test-runs' has methods for the following verbs: get */ - (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}:stop' has methods for the following verbs: post */ - ( - path: "/test-runs/{testRunId}:stop", - testRunId: string, - ): LoadTestRunStopTestRun; + (path: "/test-runs/{testRunId}:stop", testRunId: string): LoadTestRunStop; /** Resource for '/test-runs/\{testRunId\}/metric-namespaces' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/metric-namespaces", @@ -410,6 +407,6 @@ export interface Routes { ): LoadTestRunCreateOrUpdateServerMetricsConfig; } -export type AzureLoadTestingContext = Client & { +export type LoadTestServiceContext = Client & { path: Routes; }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts index a22d574c4f..b57cb81db2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import AzureLoadTestingClient from "./azureLoadTestingClient.js"; +import LoadTestServiceClient from "./loadTestServiceClient.js"; -export * from "./azureLoadTestingClient.js"; +export * from "./loadTestServiceClient.js"; export * from "./parameters.js"; export * from "./responses.js"; export * from "./clientDefinitions.js"; @@ -11,6 +11,5 @@ export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; export * from "./paginateHelper.js"; -export * from "./pollingHelper.js"; -export default AzureLoadTestingClient; +export default LoadTestServiceClient; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts index e02ac644d2..f57184edf4 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts @@ -29,20 +29,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -59,8 +58,8 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -76,11 +75,11 @@ const responseMap: Record = { "GET /tests/{testId}/app-components": ["200"], "PATCH /tests/{testId}/server-metrics-config": ["200", "201"], "GET /tests/{testId}/server-metrics-config": ["200"], - "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs/{testRunId}": ["200"], "PATCH /test-runs/{testRunId}": ["200", "201"], - "GET /test-runs/{testRunId}/files/{fileName}": ["200"], + "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs": ["200"], + "GET /test-runs/{testRunId}/files/{fileName}": ["200"], "POST /test-runs/{testRunId}:stop": ["200"], "GET /test-runs/{testRunId}/metric-namespaces": ["200"], "GET /test-runs/{testRunId}/metric-definitions": ["200"], @@ -157,26 +156,20 @@ export function isUnexpected( ): response is LoadTestAdministrationGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse, -): response is LoadTestRunDeleteTestRunDefaultResponse; + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse, +): response is LoadTestRunGetTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): response is LoadTestRunCreateOrUpdateTestRunDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse, -): response is LoadTestRunGetTestRunDefaultResponse; -export function isUnexpected( - response: - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse, -): response is LoadTestRunGetTestRunFileDefaultResponse; + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse, +): response is LoadTestRunDeleteTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunListTestRuns200Response @@ -184,9 +177,12 @@ export function isUnexpected( ): response is LoadTestRunListTestRunsDefaultResponse; export function isUnexpected( response: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, -): response is LoadTestRunStopTestRunDefaultResponse; + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse, +): response is LoadTestRunGetTestRunFileDefaultResponse; +export function isUnexpected( + response: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, +): response is LoadTestRunStopDefaultResponse; export function isUnexpected( response: | LoadTestRunListMetricNamespaces200Response @@ -226,9 +222,9 @@ export function isUnexpected( ): response is LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, -): response is LoadTestRunTestRunListServerMetricsConfigDefaultResponse; + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, +): response is LoadTestRunGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: | LoadTestAdministrationCreateOrUpdateTest200Response @@ -258,20 +254,19 @@ export function isUnexpected( | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfig200Response | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStop200Response + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespaces200Response | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitions200Response @@ -288,8 +283,8 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateServerMetricsConfig200Response | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, ): response is | LoadTestAdministrationCreateOrUpdateTestDefaultResponse | LoadTestAdministrationDeleteTestDefaultResponse @@ -303,12 +298,12 @@ export function isUnexpected( | LoadTestAdministrationGetAppComponentsDefaultResponse | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitionsDefaultResponse | LoadTestRunListMetricsDefaultResponse @@ -316,7 +311,7 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateAppComponentsDefaultResponse | LoadTestRunGetAppComponentsDefaultResponse | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse { + | LoadTestRunGetServerMetricsConfigDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts similarity index 84% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts index 5e51f0a87d..2358e988eb 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts @@ -4,10 +4,10 @@ import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; -import { AzureLoadTestingContext } from "./clientDefinitions.js"; +import { LoadTestServiceContext } from "./clientDefinitions.js"; /** - * Initialize a new instance of `AzureLoadTestingContext` + * Initialize a new instance of `LoadTestServiceContext` * @param endpointParam - A sequence of textual characters. * @param credentials - uniquely identify client credential * @param options - the parameter for all optional parameters @@ -16,10 +16,10 @@ export default function createClient( endpointParam: string, credentials: TokenCredential, options: ClientOptions = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - options.apiVersion = options.apiVersion ?? "2022-11-01"; + options.apiVersion = options.apiVersion ?? "2023-04-01-preview"; const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -44,7 +44,7 @@ export default function createClient( endpointUrl, credentials, options, - ) as AzureLoadTestingContext; + ) as LoadTestServiceContext; return client; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index a102d07cb8..51d22d4827 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -13,18 +15,24 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ @@ -61,6 +69,16 @@ export interface PassFailMetric { action?: PFAction; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface Secret { /** The value of the secret for the respective type */ @@ -79,12 +97,9 @@ export interface CertificateMetadata { name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -98,54 +113,47 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; - /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; - /** Validation status of the file */ - validationStatus?: FileStatus; - /** Validation failure error details */ - validationFailureDetails?: string; + fileName: string; } -/** Test app component */ +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -155,15 +163,12 @@ export interface TestAppComponents { components: Record; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Kind of Azure resource type */ @@ -177,7 +182,7 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; + metrics: Record; } /** @@ -206,6 +211,8 @@ export interface ResourceMetric { export interface TestRun { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -243,24 +250,42 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date | string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -301,6 +326,7 @@ export interface TestRunServerMetricConfig { /** Alias for PFMetrics */ export type PFMetrics = + | string | "response_time_ms" | "latency" | "error" @@ -308,6 +334,7 @@ export type PFMetrics = | "requests_per_sec"; /** Alias for PFAgFunc */ export type PFAgFunc = + | string | "count" | "percentage" | "avg" @@ -318,26 +345,36 @@ export type PFAgFunc = | "min" | "max"; /** Alias for PFAction */ -export type PFAction = "continue" | "stop"; +export type PFAction = string | "continue" | "stop"; /** Alias for PFResult */ -export type PFResult = "passed" | "undetermined" | "failed"; +export type PFResult = string | "passed" | "undetermined" | "failed"; /** Alias for SecretType */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretType = string | "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateType */ -export type CertificateType = "AKV_CERT_URI"; +export type CertificateType = string | "AKV_CERT_URI"; /** Alias for FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +export type FileType = + | string + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG_JSON"; /** Alias for FileStatus */ export type FileStatus = + | string | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +/** Alias for TestKind */ +export type TestKind = string | "URL" | "JMX"; /** Alias for PFTestResult */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResult = string | "PASSED" | "NOT_APPLICABLE" | "FAILED"; /** Alias for Status */ export type Status = + | string | "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" @@ -354,5 +391,5 @@ export type Status = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -/** Alias for Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Alias for TimeGrain */ +export type TimeGrain = string | "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index 392e850e81..62a3c3841b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -3,10 +3,12 @@ import { Paged } from "@azure/core-paging"; -/** Load test model */ +/** Load test model. */ export interface TestOutput { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,31 +17,37 @@ export interface TestOutput { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadataOutput; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifactsOutput; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKindOutput; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -79,6 +87,16 @@ export interface PassFailMetricOutput { readonly result?: PFResultOutput; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteriaOutput { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface SecretOutput { /** The value of the secret for the respective type */ @@ -97,12 +115,9 @@ export interface CertificateMetadataOutput { name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfigurationOutput { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -116,56 +131,59 @@ export interface LoadTestConfigurationOutput { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfigOutput; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfigOutput { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; } -/** File info */ -export interface FileInfoOutput { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfoOutput { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileTypeOutput; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; /** Validation status of the file */ - validationStatus?: FileStatusOutput; + readonly validationStatus?: FileStatusOutput; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Test app component */ +/** Test app components */ export interface TestAppComponentsOutput { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -175,30 +193,24 @@ export interface TestAppComponentsOutput { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponentOutput { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -218,12 +230,12 @@ export interface TestServerMetricConfigOutput { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -255,10 +267,12 @@ export interface ResourceMetricOutput { /** Load test run model */ export interface TestRunOutput { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -291,9 +305,9 @@ export interface TestRunOutput { description?: string; /** The test run status. */ readonly status?: StatusOutput; - /** The test run start DateTime(ISO 8601 literal format). */ + /** The test run start DateTime(RFC 3339 literal format). */ readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ + /** The test run end DateTime(RFC 3339 literal format). */ readonly endDateTime?: string; /** Test run initiated time. */ readonly executedDateTime?: string; @@ -303,11 +317,15 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** Type of test. */ + readonly kind?: TestKindOutput; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -362,23 +380,51 @@ export interface TestRunArtifactsOutput { /** The input artifacts for the test run. */ export interface TestRunInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestRunFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestRunFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestRunFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestRunFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; +} + +/** Test run file info. */ +export interface TestRunFileInfoOutput { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; + /** Validation status of the file */ + readonly validationStatus?: FileStatusOutput; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifactsOutput { /** File info */ - resultFileInfo?: FileInfoOutput; + resultFileInfo?: TestRunFileInfoOutput; /** File info */ - logsFileInfo?: FileInfoOutput; + logsFileInfo?: TestRunFileInfoOutput; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfoOutput; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfoOutput { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: string; } /** Represents collection of metric namespaces. */ @@ -451,7 +497,7 @@ export interface TimeSeriesElementOutput { /** Represents a metric value. */ export interface MetricValueOutput { - /** The timestamp for the metric value in ISO 8601 format. */ + /** The timestamp for the metric value in RFC 3339 format. */ timestamp?: string; /** The metric value. */ value?: number; @@ -465,8 +511,14 @@ export interface DimensionValueOutput { value?: string; } +/** Metrics dimension values. */ export interface DimensionValueListOutput { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Test run app component */ @@ -479,11 +531,11 @@ export interface TestRunAppComponentsOutput { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -499,11 +551,11 @@ export interface TestRunServerMetricConfigOutput { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -511,6 +563,7 @@ export interface TestRunServerMetricConfigOutput { /** Alias for PFMetricsOutput */ export type PFMetricsOutput = + | string | "response_time_ms" | "latency" | "error" @@ -518,6 +571,7 @@ export type PFMetricsOutput = | "requests_per_sec"; /** Alias for PFAgFuncOutput */ export type PFAgFuncOutput = + | string | "count" | "percentage" | "avg" @@ -528,33 +582,44 @@ export type PFAgFuncOutput = | "min" | "max"; /** Alias for PFActionOutput */ -export type PFActionOutput = "continue" | "stop"; +export type PFActionOutput = string | "continue" | "stop"; /** Alias for PFResultOutput */ -export type PFResultOutput = "passed" | "undetermined" | "failed"; +export type PFResultOutput = string | "passed" | "undetermined" | "failed"; /** Alias for SecretTypeOutput */ -export type SecretTypeOutput = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretTypeOutput = string | "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateTypeOutput */ -export type CertificateTypeOutput = "AKV_CERT_URI"; +export type CertificateTypeOutput = string | "AKV_CERT_URI"; /** Alias for FileTypeOutput */ export type FileTypeOutput = + | string | "JMX_FILE" | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS"; + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG_JSON"; /** Alias for FileStatusOutput */ export type FileStatusOutput = + | string | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; -/** Collection of tests */ +/** Alias for TestKindOutput */ +export type TestKindOutput = string | "URL" | "JMX"; +/** Paged collection of Test items */ export type PagedTestOutput = Paged; -/** Collection of files. */ -export type PagedFileInfoOutput = Paged; +/** Paged collection of TestFileInfo items */ +export type PagedTestFileInfoOutput = Paged; /** Alias for PFTestResultOutput */ -export type PFTestResultOutput = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResultOutput = + | string + | "PASSED" + | "NOT_APPLICABLE" + | "FAILED"; /** Alias for StatusOutput */ export type StatusOutput = + | string | "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" @@ -571,10 +636,11 @@ export type StatusOutput = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -/** Collection of test runs */ +/** Paged collection of TestRun items */ export type PagedTestRunOutput = Paged; /** Alias for AggregationTypeOutput */ export type AggregationTypeOutput = + | string | "Average" | "Count" | "None" @@ -584,6 +650,7 @@ export type AggregationTypeOutput = | "Percentile99"; /** Alias for MetricUnitOutput */ export type MetricUnitOutput = + | string | "NotSpecified" | "Percent" | "Count" @@ -593,8 +660,12 @@ export type MetricUnitOutput = | "BytesPerSecond" | "CountPerSecond"; /** Alias for TimeGrainOutput */ -export type TimeGrainOutput = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TimeGrainOutput = + | string + | "PT5S" + | "PT10S" + | "PT1M" + | "PT5M" + | "PT1H"; /** The response to a metrics query. */ -export type PagedTimeSeriesElementOutput = Paged; -/** Paged collection of DimensionValueList items */ -export type PagedDimensionValueListOutput = Paged; +export type MetricsOutput = Paged; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 9437426616..81ba59af51 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -8,21 +8,22 @@ import { TestAppComponents, TestServerMetricConfig, TestRun, - Interval, + TimeGrain, MetricRequestPayload, TestRunAppComponents, TestRunServerMetricConfig, } from "./models.js"; -/** Load test model */ +/** The resource instance. */ export type TestResourceMergeAndPatch = Partial; export interface LoadTestAdministrationCreateOrUpdateTestBodyParam { - /** Load test model */ + /** The resource instance. */ body: TestResourceMergeAndPatch; } export interface LoadTestAdministrationCreateOrUpdateTestMediaTypesParam { + /** This request has a JSON Merge Patch body. */ contentType: "application/merge-patch+json"; } @@ -45,16 +46,10 @@ export interface LoadTestAdministrationListTestsQueryParamProperties { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date | string; /** Number of results in response. */ maxpagesize?: number; } @@ -89,6 +84,7 @@ export interface LoadTestAdministrationUploadTestFileQueryParam { } export interface LoadTestAdministrationUploadTestFileMediaTypesParam { + /** Content type. */ contentType: "application/octet-stream"; } @@ -109,6 +105,7 @@ export interface LoadTestAdministrationCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestAdministrationCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -128,6 +125,7 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigBodyPara } export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -137,7 +135,7 @@ export type LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters = RequestParameters; export type LoadTestAdministrationGetServerMetricsConfigParameters = RequestParameters; -export type LoadTestRunDeleteTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunParameters = RequestParameters; /** The resource instance. */ export type TestRunResourceMergeAndPatch = Partial; @@ -170,8 +168,7 @@ export type LoadTestRunCreateOrUpdateTestRunParameters = LoadTestRunCreateOrUpdateTestRunMediaTypesParam & LoadTestRunCreateOrUpdateTestRunBodyParam & RequestParameters; -export type LoadTestRunGetTestRunParameters = RequestParameters; -export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunDeleteTestRunParameters = RequestParameters; export interface LoadTestRunListTestRunsQueryParamProperties { /** @@ -187,10 +184,10 @@ export interface LoadTestRunListTestRunsQueryParamProperties { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date | string; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date | string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -203,16 +200,17 @@ export interface LoadTestRunListTestRunsQueryParam { export type LoadTestRunListTestRunsParameters = LoadTestRunListTestRunsQueryParam & RequestParameters; -export type LoadTestRunStopTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunStopParameters = RequestParameters; export type LoadTestRunListMetricNamespacesParameters = RequestParameters; export interface LoadTestRunListMetricDefinitionsQueryParamProperties { /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; + metricNamespace: string; } export interface LoadTestRunListMetricDefinitionsQueryParam { - queryParameters?: LoadTestRunListMetricDefinitionsQueryParamProperties; + queryParameters: LoadTestRunListMetricDefinitionsQueryParamProperties; } export type LoadTestRunListMetricDefinitionsParameters = @@ -220,27 +218,24 @@ export type LoadTestRunListMetricDefinitionsParameters = export interface LoadTestRunListMetricsBodyParam { /** Metric dimension filter */ - body: MetricRequestPayload; + body?: MetricRequestPayload; } export interface LoadTestRunListMetricsQueryParamProperties { /** The aggregation */ aggregation?: string; - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; + metricname: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + metricNamespace: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricsQueryParam { - queryParameters?: LoadTestRunListMetricsQueryParamProperties; + queryParameters: LoadTestRunListMetricsQueryParamProperties; } export type LoadTestRunListMetricsParameters = @@ -249,17 +244,14 @@ export type LoadTestRunListMetricsParameters = RequestParameters; export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; + metricname: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ metricNamespace: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricDimensionValuesQueryParam { @@ -278,6 +270,7 @@ export interface LoadTestRunCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestRunCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -296,6 +289,7 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam { } export interface LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -303,5 +297,4 @@ export type LoadTestRunCreateOrUpdateServerMetricsConfigParameters = LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam & LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam & RequestParameters; -export type LoadTestRunTestRunListServerMetricsConfigParameters = - RequestParameters; +export type LoadTestRunGetServerMetricsConfigParameters = RequestParameters; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts deleted file mode 100644 index 4b79865fe8..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { Client, HttpResponse } from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { - CancelOnProgress, - CreateHttpPollerOptions, - RunningOperation, - OperationResponse, - OperationState, - createHttpPoller, -} from "@azure/core-lro"; -import { - LoadTestRunCreateOrUpdateTestRun200Response, - LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, -} from "./responses.js"; - -/** - * A simple poller that can be used to poll a long running operation. - */ -export interface SimplePollerLike< - TState extends OperationState, - TResult, -> { - /** - * Returns true if the poller has finished polling. - */ - isDone(): boolean; - /** - * Returns the state of the operation. - */ - getOperationState(): TState; - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult(): TResult | undefined; - /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - */ - poll(options?: { abortSignal?: AbortSignalLike }): Promise; - /** - * Returns a promise that will resolve once the underlying operation is completed. - */ - pollUntilDone(pollOptions?: { - abortSignal?: AbortSignalLike; - }): Promise; - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback: (state: TState) => void): CancelOnProgress; - - /** - * Returns a promise that could be used for serialized version of the poller's operation - * by invoking the operation's serialize method. - */ - serialize(): Promise; - - /** - * Wait the poller to be submitted. - */ - submitted(): Promise; - - /** - * Returns a string representation of the poller's operation. Similar to serialize but returns a string. - * @deprecated Use serialize() instead. - */ - toString(): string; - - /** - * Stops the poller from continuing to poll. Please note this will only stop the client-side polling - * @deprecated Use abortSignal to stop polling instead. - */ - stopPolling(): void; - - /** - * Returns true if the poller is stopped. - * @deprecated Use abortSignal status to track this instead. - */ - isStopped(): boolean; -} - -/** - * Helper function that builds a Poller object to help polling a long running operation. - * @param client - Client to use for sending the request to get additional pages. - * @param initialResponse - The initial response. - * @param options - Options to set a resume state or custom polling interval. - * @returns - A poller object to poll for operation state updates and eventually get the final response. - */ -export async function getLongRunningPoller< - TResult extends - | LoadTestRunCreateOrUpdateTestRunLogicalResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ->( - client: Client, - initialResponse: - | LoadTestRunCreateOrUpdateTestRun200Response - | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller( - client: Client, - initialResponse: TResult, - options: CreateHttpPollerOptions> = {}, -): Promise, TResult>> { - const abortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - // In the case of Rest Clients we are building the LRO poller object from a response that's the reason - // we are not triggering the initial request here, just extracting the information from the - // response we were provided. - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - options?: { abortSignal?: AbortSignalLike }, - ) => { - // This is the callback that is going to be called to poll the service - // to get the latest status. We use the client provided and the polling path - // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location - // depending on the lro pattern that the service implements. If non is provided we default to the initial path. - function abortListener(): void { - abortController.abort(); - } - const inputAbortSignal = options?.abortSignal; - const abortSignal = abortController.signal; - if (inputAbortSignal?.aborted) { - abortController.abort(); - } else if (!abortSignal.aborted) { - inputAbortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client - .pathUnchecked(path ?? initialResponse.request.url) - .get({ abortSignal }); - } finally { - inputAbortSignal?.removeEventListener("abort", abortListener); - } - const lroResponse = getLroResponse(response as TResult); - lroResponse.rawResponse.headers["x-ms-original-url"] = - initialResponse.request.url; - return lroResponse; - }, - }; - - options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; - const httpPoller = createHttpPoller(poller, options); - const simplePoller: SimplePollerLike, TResult> = { - isDone() { - return httpPoller.isDone; - }, - isStopped() { - return abortController.signal.aborted; - }, - getOperationState() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return httpPoller.operationState; - }, - getResult() { - return httpPoller.result; - }, - toString() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return JSON.stringify({ - state: httpPoller.operationState, - }); - }, - stopPolling() { - abortController.abort(); - }, - onProgress: httpPoller.onProgress, - poll: httpPoller.poll, - pollUntilDone: httpPoller.pollUntilDone, - serialize: httpPoller.serialize, - submitted: httpPoller.submitted, - }; - return simplePoller; -} - -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResult, -): OperationResponse { - if (Number.isNaN(response.status)) { - throw new TypeError( - `Status code of the response is not a number. Value: ${response.status}`, - ); - } - - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index 2c79e0b52c..d8f4cd2d58 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,16 +6,17 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - FileInfoOutput, - PagedFileInfoOutput, + FileTypeOutput, + FileStatusOutput, + PagedTestFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, - PagedTimeSeriesElementOutput, - PagedDimensionValueListOutput, + MetricsOutput, + DimensionValueListOutput, TestRunAppComponentsOutput, TestRunServerMetricConfigOutput, } from "./outputModels.js"; @@ -106,7 +107,13 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: FileInfoOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -125,7 +132,13 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -162,7 +175,7 @@ export interface LoadTestAdministrationDeleteTestFileDefaultResponse export interface LoadTestAdministrationListTestFiles200Response extends HttpResponse { status: "200"; - body: PagedFileInfoOutput; + body: PagedTestFileInfoOutput; } export interface LoadTestAdministrationListTestFilesDefaultHeaders { @@ -271,25 +284,21 @@ export interface LoadTestAdministrationGetServerMetricsConfigDefaultResponse LoadTestAdministrationGetServerMetricsConfigDefaultHeaders; } -/** There is no content to send for this request, but the headers may be useful. */ -export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { - status: "204"; +/** The request has succeeded. */ +export interface LoadTestRunGetTestRun200Response extends HttpResponse { + status: "200"; + body: TestRunOutput; } -export interface LoadTestRunDeleteTestRunDefaultHeaders { +export interface LoadTestRunGetTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; -} - -export interface LoadTestRunCreateOrUpdateTestRun200Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; + headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; } /** The request has succeeded. */ @@ -297,12 +306,6 @@ export interface LoadTestRunCreateOrUpdateTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun200Headers; -} - -export interface LoadTestRunCreateOrUpdateTestRun201Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; } /** The request has succeeded and a new resource has been created as a result. */ @@ -310,7 +313,6 @@ export interface LoadTestRunCreateOrUpdateTestRun201Response extends HttpResponse { status: "201"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun201Headers; } export interface LoadTestRunCreateOrUpdateTestRunDefaultHeaders { @@ -325,79 +327,77 @@ export interface LoadTestRunCreateOrUpdateTestRunDefaultResponse headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRunDefaultHeaders; } -/** The final response for long-running CreateOrUpdateTestRun operation */ -export interface LoadTestRunCreateOrUpdateTestRunLogicalResponse - extends HttpResponse { - status: "200"; - body: TestRunOutput; -} - -/** The request has succeeded. */ -export interface LoadTestRunGetTestRun200Response extends HttpResponse { - status: "200"; - body: TestRunOutput; +/** There is no content to send for this request, but the headers may be useful. */ +export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { + status: "204"; } -export interface LoadTestRunGetTestRunDefaultHeaders { +export interface LoadTestRunDeleteTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { +export interface LoadTestRunListTestRuns200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: PagedTestRunOutput; } -export interface LoadTestRunGetTestRunFileDefaultHeaders { +export interface LoadTestRunListTestRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { +export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunListTestRuns200Response extends HttpResponse { +export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: PagedTestRunOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } -export interface LoadTestRunListTestRunsDefaultHeaders { +export interface LoadTestRunGetTestRunFileDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunStopTestRun200Response extends HttpResponse { +export interface LoadTestRunStop200Response extends HttpResponse { status: "200"; body: TestRunOutput; } -export interface LoadTestRunStopTestRunDefaultHeaders { +export interface LoadTestRunStopDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunStopTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunStopDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunStopTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunStopDefaultHeaders; } /** The request has succeeded. */ @@ -441,7 +441,7 @@ export interface LoadTestRunListMetricDefinitionsDefaultResponse /** The request has succeeded. */ export interface LoadTestRunListMetrics200Response extends HttpResponse { status: "200"; - body: PagedTimeSeriesElementOutput; + body: MetricsOutput; } export interface LoadTestRunListMetricsDefaultHeaders { @@ -459,7 +459,7 @@ export interface LoadTestRunListMetricsDefaultResponse extends HttpResponse { export interface LoadTestRunListMetricDimensionValues200Response extends HttpResponse { status: "200"; - body: PagedDimensionValueListOutput; + body: DimensionValueListOutput; } export interface LoadTestRunListMetricDimensionValuesDefaultHeaders { @@ -547,21 +547,20 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse } /** The request has succeeded. */ -export interface LoadTestRunTestRunListServerMetricsConfig200Response +export interface LoadTestRunGetServerMetricsConfig200Response extends HttpResponse { status: "200"; body: TestRunServerMetricConfigOutput; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultHeaders { +export interface LoadTestRunGetServerMetricsConfigDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultResponse +export interface LoadTestRunGetServerMetricsConfigDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & - LoadTestRunTestRunListServerMetricsConfigDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetServerMetricsConfigDefaultHeaders; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index 53a26b11df..de60e781ee 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. export { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -20,5 +20,5 @@ export { export { createTestRunOperations, TestRunOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./testRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 5771618dc5..43442bfd65 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { getLongRunningPoller } from "./pollingHelpers.js"; -import { PollerLike, OperationState } from "@azure/core-lro"; import { - FileInfo, + FileType, + FileStatus, TestRun, TestRunAppComponents, TestRunServerMetricConfig, @@ -12,16 +11,14 @@ import { MetricDefinitionCollection, MetricNamespaceCollection, MetricRequestPayload, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, PagedTestRun, - PagedDimensionValueList, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestRunCreateOrUpdateAppComponents200Response, LoadTestRunCreateOrUpdateAppComponents201Response, LoadTestRunCreateOrUpdateAppComponentsDefaultResponse, @@ -31,11 +28,12 @@ import { LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunDeleteTestRun204Response, LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunGetAppComponents200Response, LoadTestRunGetAppComponentsDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, LoadTestRunGetTestRun200Response, LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, @@ -50,10 +48,7 @@ import { LoadTestRunListMetricsDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -61,7 +56,7 @@ import { createRestError, } from "@azure-rest/core-client"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -77,16 +72,15 @@ import { StopTestRunOptionalParams, } from "../models/options.js"; -export function _testRunSend( +export function _createOrUpdateTestRunSend( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse > { return context .path("/test-runs/{testRunId}", testRunId) @@ -96,72 +90,92 @@ export function _testRunSend( (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, body: { - passFailCriteria: !resource.passFailCriteria + passFailCriteria: !body.passFailCriteria ? undefined - : { passFailMetrics: resource.passFailCriteria?.["passFailMetrics"] }, - secrets: resource["secrets"], - certificate: !resource.certificate + : { passFailMetrics: body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !body.autoStopCriteria ? undefined : { - value: resource.certificate?.["value"], - type: resource.certificate?.["type"], - name: resource.certificate?.["name"], + autoStopDisabled: body.autoStopCriteria?.["autoStopDisabled"], + errorRate: body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - environmentVariables: resource["environmentVariables"], - loadTestConfiguration: !resource.loadTestConfiguration + secrets: body["secrets"], + certificate: !body.certificate ? undefined : { - engineInstances: - resource.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: resource.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: - resource.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !resource.loadTestConfiguration + value: body.certificate?.["value"], + type: body.certificate?.["type"], + name: body.certificate?.["name"], + }, + environmentVariables: body["environmentVariables"], + loadTestConfiguration: !body.loadTestConfiguration + ? undefined + : { + engineInstances: body.loadTestConfiguration?.["engineInstances"], + splitAllCSVs: body.loadTestConfiguration?.["splitAllCSVs"], + quickStartTest: body.loadTestConfiguration?.["quickStartTest"], + optionalLoadTestConfig: !body.loadTestConfiguration ?.optionalLoadTestConfig ? undefined : { endpointUrl: - resource.loadTestConfiguration?.optionalLoadTestConfig?.[ + body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: - resource.loadTestConfiguration?.optionalLoadTestConfig?.[ + body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" ], rampUpTime: - resource.loadTestConfiguration?.optionalLoadTestConfig?.[ + body.loadTestConfiguration?.optionalLoadTestConfig?.[ "rampUpTime" ], duration: - resource.loadTestConfiguration?.optionalLoadTestConfig?.[ + body.loadTestConfiguration?.optionalLoadTestConfig?.[ "duration" ], }, }, - displayName: resource["displayName"], - testId: resource["testId"], - description: resource["description"], + displayName: body["displayName"], + testId: body["testId"], + description: body["description"], }, }); } -export async function _testRunDeserialize( +export async function _createOrUpdateTestRunDeserialize( result: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse, + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); } - result = result as LoadTestRunCreateOrUpdateTestRunLogicalResponse; return { testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -191,6 +205,14 @@ export async function _testRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -215,17 +237,22 @@ export async function _testRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -237,17 +264,22 @@ export async function _testRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -259,17 +291,22 @@ export async function _testRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -281,17 +318,23 @@ export async function _testRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -301,6 +344,34 @@ export async function _testRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -311,10 +382,13 @@ export async function _testRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -326,17 +400,22 @@ export async function _testRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -348,17 +427,22 @@ export async function _testRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -366,6 +450,22 @@ export async function _testRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, }, }, testResult: result.body["testResult"], @@ -374,32 +474,50 @@ export async function _testRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create and start a new test run with the given name. */ -export function testRun( +/** Create and start a new test run with the given test run Id. */ +export async function createOrUpdateTestRun( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, -): PollerLike, TestRun> { - return getLongRunningPoller(context, _testRunDeserialize, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _testRunSend(context, testRunId, resource, options), - }) as PollerLike, TestRun>; + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestRunSend( + context, + testRunId, + body, + options, + ); + return _createOrUpdateTestRunDeserialize(result); } export function _createOrUpdateAppComponentsSend( @@ -435,14 +553,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test run */ +/** Add an app component to a test run by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testRunId: string, @@ -493,9 +617,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -542,7 +672,7 @@ export async function _deleteTestRunDeserialize( return; } -/** Delete a test run by its name. */ +/** Delete an existing load test run by providing the testRunId. */ export async function deleteTestRun( context: Client, testRunId: string, @@ -577,9 +707,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -602,8 +738,8 @@ export function _getServerMetricsConfigSend( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse > { return context .path("/test-runs/{testRunId}/server-metrics-config", testRunId) @@ -612,8 +748,8 @@ export function _getServerMetricsConfigSend( export async function _getServerMetricsConfigDeserialize( result: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -622,14 +758,20 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** List server metrics configuration for the given test run. */ +/** Get associated server metrics configuration for the given test run. */ export async function getServerMetricsConfig( context: Client, testRunId: string, @@ -665,6 +807,14 @@ export async function _getTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -694,6 +844,14 @@ export async function _getTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -718,17 +876,22 @@ export async function _getTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -740,17 +903,22 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -762,17 +930,22 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -784,17 +957,23 @@ export async function _getTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -804,6 +983,34 @@ export async function _getTestRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -814,10 +1021,13 @@ export async function _getTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -829,17 +1039,22 @@ export async function _getTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -851,17 +1066,22 @@ export async function _getTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -869,6 +1089,22 @@ export async function _getTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, }, }, testResult: result.body["testResult"], @@ -877,20 +1113,37 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get test run details by name. */ +/** Get test run details by test run Id. */ export async function getTestRun( context: Client, testRunId: string, @@ -918,16 +1171,24 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -939,7 +1200,13 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _getTestRunFileSend( context, testRunId, @@ -953,7 +1220,9 @@ export function _listMetricDimensionValuesSend( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDimensionValues200Response @@ -968,10 +1237,10 @@ export function _listMetricDimensionValuesSend( .get({ ...operationOptionsToRequestParameters(options), queryParameters: { + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, metricNamespace: metricNamespace, - timespan: options?.timespan, + timespan: timespan, }, }); } @@ -980,43 +1249,44 @@ export async function _listMetricDimensionValuesDeserialize( result: | LoadTestRunListMetricDimensionValues200Response | LoadTestRunListMetricDimensionValuesDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - value: result.body["value"].map((p) => ({ value: p["value"] })), + name: result.body["name"], + value: result.body["value"], nextLink: result.body["nextLink"], }; } /** List the dimension values for the given metric dimension name. */ -export function listMetricDimensionValues( +export async function listMetricDimensionValues( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( +): Promise { + const result = await _listMetricDimensionValuesSend( context, - () => - _listMetricDimensionValuesSend( - context, - testRunId, - name, - metricNamespace, - options, - ), - _listMetricDimensionValuesDeserialize, - { itemName: "value", nextLinkName: "nextLink" }, + testRunId, + name, + metricname, + metricNamespace, + timespan, + options, ); + return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response @@ -1026,7 +1296,7 @@ export function _listMetricDefinitionsSend( .path("/test-runs/{testRunId}/metric-definitions", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: options?.metricNamespace }, + queryParameters: { metricNamespace: metricNamespace }, }); } @@ -1068,9 +1338,15 @@ export async function _listMetricDefinitionsDeserialize( export async function listMetricDefinitions( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _listMetricDefinitionsSend(context, testRunId, options); + const result = await _listMetricDefinitionsSend( + context, + testRunId, + metricNamespace, + options, + ); return _listMetricDefinitionsDeserialize(result); } @@ -1117,7 +1393,10 @@ export async function listMetricNamespaces( export function _listMetricsSend( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse @@ -1128,20 +1407,23 @@ export function _listMetricsSend( ...operationOptionsToRequestParameters(options), queryParameters: { aggregation: options?.aggregation, + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, - metricNamespace: options?.metricNamespace, - timespan: options?.timespan, - }, - body: { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map((p) => ({ - name: p["name"], - values: p["values"], - })), + metricNamespace: metricNamespace, + timespan: timespan, }, + body: + body === undefined + ? body + : { + filters: + body["filters"] === undefined + ? body["filters"] + : body["filters"].map((p) => ({ + name: p["name"], + values: p["values"], + })), + }, }); } @@ -1149,7 +1431,7 @@ export async function _listMetricsDeserialize( result: | LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } @@ -1160,7 +1442,10 @@ export async function _listMetricsDeserialize( p["data"] === undefined ? p["data"] : p["data"].map((p) => ({ - timestamp: p["timestamp"], + timestamp: + p["timestamp"] !== undefined + ? new Date(p["timestamp"]) + : undefined, value: p["value"], })), dimensionValues: @@ -1179,12 +1464,24 @@ export async function _listMetricsDeserialize( export function listMetrics( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listMetricsSend(context, testRunId, body, options), + () => + _listMetricsSend( + context, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ), _listMetricsDeserialize, { itemName: "value", nextLinkName: "nextLink" }, ); @@ -1204,8 +1501,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom, - executionTo: options?.executionTo, + executionFrom: options?.executionFrom?.toISOString(), + executionTo: options?.executionTo?.toISOString(), status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1227,6 +1524,14 @@ export async function _listTestRunsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1255,6 +1560,14 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1279,13 +1592,13 @@ export async function _listTestRunsDeserialize( ?.configFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileName" ], + url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "url" + ], fileType: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileType" @@ -1293,7 +1606,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1307,12 +1625,12 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "fileName" ], + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "fileType" @@ -1320,7 +1638,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -1334,12 +1657,12 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileName" ], + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileType" @@ -1347,7 +1670,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1361,17 +1689,25 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1381,6 +1717,36 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] === undefined @@ -1388,10 +1754,13 @@ export async function _listTestRunsDeserialize( : p.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1404,13 +1773,13 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileName" ], + url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "url" + ], fileType: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileType" @@ -1418,7 +1787,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1431,13 +1805,13 @@ export async function _listTestRunsDeserialize( logsFileInfo: !p.testArtifacts?.outputArtifacts?.logsFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileName" ], + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" + ], fileType: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileType" @@ -1445,7 +1819,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1455,6 +1834,22 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, + artifactsContainerInfo: !p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo + ? undefined + : { + url: p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, }, }, testResult: p["testResult"], @@ -1463,22 +1858,37 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: p["startDateTime"], - endDateTime: p["endDateTime"], - executedDateTime: p["executedDateTime"], + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, + executedDateTime: + p["executedDateTime"] !== undefined + ? new Date(p["executedDateTime"]) + : undefined, portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - createdDateTime: p["createdDateTime"], + kind: p["kind"], + publicIPDisabled: p["publicIPDisabled"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], }; } -/** Get all test runs with given filters */ +/** Get all test runs for the given filters. */ export function listTestRuns( context: Client, options: ListTestRunsOptionalParams = { requestOptions: {} }, @@ -1495,19 +1905,13 @@ export function _stopTestRunSend( context: Client, testRunId: string, options: StopTestRunOptionalParams = { requestOptions: {} }, -): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse -> { +): StreamableMethod { return context - .path("/test-runs/{testRunId}:stop", testRunId) + .path("/test-runs/{testRunId}:stopTestRun", testRunId) .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestRunDeserialize( - result: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, -): Promise { +export async function _stopTestRunDeserialize(result): Promise { if (isUnexpected(result)) { throw createRestError(result); } @@ -1517,6 +1921,14 @@ export async function _stopTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -1546,6 +1958,14 @@ export async function _stopTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1570,17 +1990,22 @@ export async function _stopTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -1592,17 +2017,22 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1614,17 +2044,22 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -1636,17 +2071,23 @@ export async function _stopTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1656,6 +2097,34 @@ export async function _stopTestRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1666,10 +2135,13 @@ export async function _stopTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1681,17 +2153,22 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1703,17 +2180,22 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1721,6 +2203,22 @@ export async function _stopTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, }, }, testResult: result.body["testResult"], @@ -1729,20 +2227,37 @@ export async function _stopTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Stop test run by name. */ +/** Stop test run by test run Id. */ export async function stopTestRun( context: Client, testRunId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts deleted file mode 100644 index d4d54d4e32..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - ResourceLocationConfig, - RunningOperation, - createHttpPoller, - OperationResponse, -} from "@azure/core-lro"; - -import { - Client, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { isUnexpected } from "../../rest/index.js"; - -export interface GetLongRunningPollerOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** - * The potential location of the result of the LRO if specified by the LRO extension in the swagger. - */ - resourceLocationConfig?: ResourceLocationConfig; - /** - * The original url of the LRO - * Should not be null when restoreFrom is set - */ - initialRequestUrl?: string; - /** - * A serialized poller which can be used to resume an existing paused Long-Running-Operation. - */ - restoreFrom?: string; - /** - * The function to get the initial response - */ - getInitialResponse?: () => PromiseLike; -} -export function getLongRunningPoller< - TResponse extends PathUncheckedResponse, - TResult = void, ->( - client: Client, - processResponseBody: (result: TResponse) => Promise, - options: GetLongRunningPollerOptions, -): PollerLike, TResult> { - const { restoreFrom, getInitialResponse } = options; - if (!restoreFrom && !getInitialResponse) { - throw new Error( - "Either restoreFrom or getInitialResponse must be specified", - ); - } - let initialResponse: TResponse | undefined = undefined; - const pollAbortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - if (!getInitialResponse) { - throw new Error( - "getInitialResponse is required when initializing a new poller", - ); - } - initialResponse = await getInitialResponse(); - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - pollOptions?: { - abortSignal?: AbortSignalLike; - }, - ) => { - // The poll request would both listen to the user provided abort signal and the poller's own abort signal - function abortListener(): void { - pollAbortController.abort(); - } - const abortSignal = pollAbortController.signal; - if (options.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (pollOptions?.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (!abortSignal.aborted) { - options.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - pollOptions?.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client.pathUnchecked(path).get({ abortSignal }); - } finally { - options.abortSignal?.removeEventListener("abort", abortListener); - pollOptions?.abortSignal?.removeEventListener("abort", abortListener); - } - if (options.initialRequestUrl || initialResponse) { - response.headers["x-ms-original-url"] = - options.initialRequestUrl ?? initialResponse!.request.url; - } - - return getLroResponse(response as TResponse); - }, - }; - return createHttpPoller(poller, { - intervalInMs: options?.updateIntervalInMs, - resourceLocationConfig: options?.resourceLocationConfig, - restoreFrom: options?.restoreFrom, - processResult: (result: unknown) => { - return processResponseBody(result as TResponse); - }, - }); -} -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @param deserializeFn - deserialize function to convert Rest response to modular output - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResponse, -): OperationResponse { - if (isUnexpected(response as PathUncheckedResponse)) { - throw createRestError(response); - } - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index f71af753dd..a4b3912b22 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; export interface TestRunOperationsClientOptions extends ClientOptions { @@ -11,13 +11,13 @@ export interface TestRunOperationsClientOptions extends ClientOptions { apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createTestRunOperations( endpointParam: string, credential: TokenCredential, options: TestRunOperationsClientOptions = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index 7c9fc4ba24..9a6a3e5cf2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -5,7 +5,6 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperationsClient.js"; -export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Test, PassFailCriteria, @@ -14,6 +13,7 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -21,27 +21,28 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, ResourceMetric, - PagedFileInfo, - PagedTest, APIVersions, TestRun, ErrorDetails, TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -49,18 +50,18 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, MetricValue, DimensionValue, + PagedTestFileInfo, + PagedTest, PagedTestRun, - PagedDimensionValueList, - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index d4e77750f1..bb92ef1f85 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -9,6 +9,7 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -16,27 +17,28 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, ResourceMetric, - PagedFileInfo, - PagedTest, APIVersions, TestRun, ErrorDetails, TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -44,20 +46,20 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - PagedTimeSeriesElement, + Metrics, TimeSeriesElement, MetricValue, DimensionValue, + PagedTestFileInfo, + PagedTest, PagedTestRun, - PagedDimensionValueList, } from "./models.js"; export { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index daab3ea449..27018ab1f3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -13,32 +15,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -77,28 +85,28 @@ export interface PassFailMetric { readonly result?: PFResult; } -/** */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; -/** */ -export type PFAction = "continue" | "stop"; -/** */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Metrics for pass/fail criteria. */ +/** "response_time_ms", "latency", "error", "requests", "requests_per_sec" */ +export type PFMetrics = string; +/** Aggregation functions for pass/fail criteria. */ +/** "count", "percentage", "avg", "p50", "p90", "p95", "p99", "min", "max" */ +export type PFAgFunc = string; +/** Action to take on failure of pass/fail criteria. */ +/** "continue", "stop" */ +export type PFAction = string; +/** Pass/fail criteria result. */ +/** "passed", "undetermined", "failed" */ +export type PFResult = string; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} /** Secret */ export interface Secret { @@ -108,8 +116,9 @@ export interface Secret { type?: SecretType; } -/** */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Types of secrets supported. */ +/** "AKV_SECRET_URI", "SECRET_VALUE" */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -121,15 +130,13 @@ export interface CertificateMetadata { name?: string; } -/** */ -export type CertificateType = "AKV_CERT_URI"; +/** Types of certificates supported. */ +/** "AKV_CERT_URI" */ +export type CertificateType = string; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -143,66 +150,69 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; - -/** Test app component */ +/** Types of file supported. */ +/** "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG_JSON" */ +export type FileType = string; +/** File status. */ +/** "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" */ +export type FileStatus = string; +/** Test kind */ +/** "URL", "JMX" */ +export type TestKind = string; + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -212,30 +222,24 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -255,13 +259,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -290,31 +294,18 @@ export interface ResourceMetric { resourceType: string; } -/** Collection of files. */ -export interface PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - +/** Azure Load Testing API versions. */ /** */ -export type APIVersions = "2022-11-01"; +export type APIVersions = "2022-11-01" | "2023-04-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -347,24 +338,28 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -418,45 +413,59 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; } -/** */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ +/** "PASSED", "NOT_APPLICABLE", "FAILED" */ +export type PFTestResult = string; +/** Test run status. */ +/** "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" */ +export type Status = string; /** Test run app component */ export interface TestRunAppComponents { @@ -468,12 +477,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -488,21 +497,28 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Time Grain */ +/** "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ +export type TimeGrain = string; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -542,25 +558,12 @@ export interface NameAndDesc { name?: string; } -/** */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; -/** */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Aggregation type. */ +/** "Average", "Count", "None", "Total", "Percentile90", "Percentile95", "Percentile99" */ +export type AggregationType = string; +/** Metric unit. */ +/** "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -571,9 +574,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -588,7 +588,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -608,7 +608,7 @@ export interface DimensionFilter { } /** The response to a metrics query. */ -export interface PagedTimeSeriesElement { +export interface Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -625,8 +625,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -639,18 +639,26 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ -export interface PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; +/** Paged collection of TestFileInfo items */ +export interface PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; /** The link to the next page of items */ nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of Test items */ +export interface PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ +export interface PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; /** The link to the next page of items */ nextLink?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index 84eb77cd52..8e9fd54c34 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -2,11 +2,9 @@ // Licensed under the MIT license. import { OperationOptions } from "@azure-rest/core-client"; -import { Interval } from "./models.js"; +import { TimeGrain } from "./models.js"; -export interface TestRunOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; +export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { /** This request has a JSON Merge Patch body. */ contentType?: string; /** @@ -20,11 +18,13 @@ export interface TestRunOptionalParams extends OperationOptions { export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -42,20 +42,10 @@ export interface GetTestRunFileOptionalParams extends OperationOptions {} export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } -export interface ListMetricDefinitionsOptionalParams extends OperationOptions { - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; -} +export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} export interface ListMetricNamespacesOptionalParams extends OperationOptions {} @@ -63,16 +53,7 @@ export interface ListMetricsOptionalParams extends OperationOptions { /** The aggregation */ aggregation?: string; /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } export interface ListTestRunsOptionalParams extends OperationOptions { @@ -89,10 +70,10 @@ export interface ListTestRunsOptionalParams extends OperationOptions { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts deleted file mode 100644 index 08d79ecc89..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - deserializeState, - ResourceLocationConfig, -} from "@azure/core-lro"; -import { AzureLoadTestingContext } from "./api/testRunOperationsContext.js"; -import { TestRunOperationsClient } from "./testRunOperationsClient.js"; -import { getLongRunningPoller } from "./api/pollingHelpers.js"; -import { _testRunDeserialize } from "./api/operations.js"; -import { - PathUncheckedResponse, - OperationOptions, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; - -export interface RestorePollerOptions< - TResult, - TResponse extends PathUncheckedResponse = PathUncheckedResponse, -> extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** Deserialization function for raw response body */ - processResponseBody?: (result: TResponse) => Promise; -} - -/** - * Creates a poller from the serialized state of another poller. This can be - * useful when you want to create pollers on a different host or a poller - * needs to be constructed after the original one is not in scope. - */ -export function restorePoller( - client: AzureLoadTestingContext | TestRunOperationsClient, - serializedState: string, - sourceOperation: ( - ...args: any[] - ) => PollerLike, TResult>, - options?: RestorePollerOptions, -): PollerLike, TResult> { - const pollerConfig = deserializeState(serializedState).config; - const { initialRequestUrl, requestMethod, metadata } = pollerConfig; - if (!initialRequestUrl || !requestMethod) { - throw new Error( - `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, - ); - } - const resourceLocationConfig = metadata?.["resourceLocationConfig"] as - | ResourceLocationConfig - | undefined; - const deserializeHelper = - options?.processResponseBody ?? - getDeserializationHelper(initialRequestUrl, requestMethod); - if (!deserializeHelper) { - throw new Error( - `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, - ); - } - return getLongRunningPoller( - (client as any)["_client"] ?? client, - deserializeHelper as (result: TResponse) => Promise, - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - resourceLocationConfig, - restoreFrom: serializedState, - initialRequestUrl, - }, - ); -} - -const deserializeMap: Record = { - "PATCH /test-runs/{testRunId}": _testRunDeserialize, -}; - -function getDeserializationHelper( - urlStr: string, - method: string, -): ((result: unknown) => Promise) | undefined { - const path = new URL(urlStr).pathname; - const pathParts = path.split("/"); - - // Traverse list to match the longest candidate - // matchedLen: the length of candidate path - // matchedValue: the matched status code array - let matchedLen = -1, - matchedValue: ((result: unknown) => Promise) | undefined; - - // Iterate the responseMap to find a match - for (const [key, value] of Object.entries(deserializeMap)) { - // Extracting the path from the map key which is in format - // GET /path/foo - if (!key.startsWith(method)) { - continue; - } - const candidatePath = getPathFromMapKey(key); - // Get each part of the url path - const candidateParts = candidatePath.split("/"); - - // track if we have found a match to return the values found. - let found = true; - for ( - let i = candidateParts.length - 1, j = pathParts.length - 1; - i >= 1 && j >= 1; - i--, j-- - ) { - if ( - candidateParts[i]?.startsWith("{") && - candidateParts[i]?.indexOf("}") !== -1 - ) { - const start = candidateParts[i]!.indexOf("}") + 1, - end = candidateParts[i]?.length; - // If the current part of the candidate is a "template" part - // Try to use the suffix of pattern to match the path - // {guid} ==> $ - // {guid}:export ==> :export$ - const isMatched = new RegExp( - `${candidateParts[i]?.slice(start, end)}`, - ).test(pathParts[j] || ""); - - if (!isMatched) { - found = false; - break; - } - continue; - } - - // If the candidate part is not a template and - // the parts don't match mark the candidate as not found - // to move on with the next candidate path. - if (candidateParts[i] !== pathParts[j]) { - found = false; - break; - } - } - - // We finished evaluating the current candidate parts - // Update the matched value if and only if we found the longer pattern - if (found && candidatePath.length > matchedLen) { - matchedLen = candidatePath.length; - matchedValue = value as (result: unknown) => Promise; - } - } - - return matchedValue; -} - -function getPathFromMapKey(mapKey: string): string { - const pathStart = mapKey.indexOf("/"); - return mapKey.slice(pathStart); -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index af36f1eef8..70f670a240 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { PollerLike, OperationState } from "@azure/core-lro"; import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - FileInfo, + FileType, + FileStatus, TestRun, TestRunAppComponents, TestRunServerMetricConfig, @@ -16,7 +16,7 @@ import { TimeSeriesElement, } from "./models/models.js"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -33,7 +33,7 @@ import { } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -49,13 +49,13 @@ import { stopTestRun, createTestRunOperations, TestRunOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./api/index.js"; export { TestRunOperationsClientOptions } from "./api/testRunOperationsContext.js"; export class TestRunOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -68,16 +68,16 @@ export class TestRunOperationsClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given name. */ - testRun( + /** Create and start a new test run with the given test run Id. */ + createOrUpdateTestRun( testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, - ): PollerLike, TestRun> { - return testRun(this._client, testRunId, resource, options); + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTestRun(this._client, testRunId, body, options); } - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ createOrUpdateAppComponents( testRunId: string, body: TestRunAppComponents, @@ -102,7 +102,7 @@ export class TestRunOperationsClient { ); } - /** Delete a test run by its name. */ + /** Delete an existing load test run by providing the testRunId. */ deleteTestRun( testRunId: string, options: DeleteTestRunOptionalParams = { requestOptions: {} }, @@ -121,7 +121,7 @@ export class TestRunOperationsClient { return getAppComponents(this._client, testRunId, options); } - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ getServerMetricsConfig( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, @@ -129,7 +129,7 @@ export class TestRunOperationsClient { return getServerMetricsConfig(this._client, testRunId, options); } - /** Get test run details by name. */ + /** Get test run details by test run Id. */ getTestRun( testRunId: string, options: GetTestRunOptionalParams = { requestOptions: {} }, @@ -142,7 +142,13 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -150,14 +156,18 @@ export class TestRunOperationsClient { listMetricDimensionValues( testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): Promise { return listMetricDimensionValues( this._client, testRunId, name, + metricname, metricNamespace, + timespan, options, ); } @@ -165,9 +175,15 @@ export class TestRunOperationsClient { /** List the metric definitions for a load test run. */ listMetricDefinitions( testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - return listMetricDefinitions(this._client, testRunId, options); + return listMetricDefinitions( + this._client, + testRunId, + metricNamespace, + options, + ); } /** List the metric namespaces for a load test run. */ @@ -181,20 +197,31 @@ export class TestRunOperationsClient { /** List the metric values for a load test run. */ listMetrics( testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { - return listMetrics(this._client, testRunId, body, options); + return listMetrics( + this._client, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ); } - /** Get all test runs with given filters */ + /** Get all test runs for the given filters. */ listTestRuns( options: ListTestRunsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } - /** Stop test run by name. */ + /** Stop test run by test run Id. */ stopTestRun( testRunId: string, options: StopTestRunOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp index 203666d54f..8f2d6060a0 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp @@ -3,47 +3,58 @@ import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Versioning; using Azure.ClientGenerator.Core; -using AzureLoadTesting; +using Microsoft.LoadTestService; @useDependency(APIVersions.v2022_11_01) +@useDependency(APIVersions.v2023_04_01_preview) namespace Customizations; +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestAdministrationClient", - service: AzureLoadTesting, + name: "LoadTestAdministrationClient", + service: Microsoft.LoadTestService, }) interface AdministrationOperations { - CreateOrUpdateTest is LoadTestAdministration.CreateOrUpdateTest; - CreateOrUpdateAppComponents is LoadTestAdministration.CreateOrUpdateAppComponents; - CreateOrUpdateServerMetricsConfig is LoadTestAdministration.CreateOrUpdateServerMetricsConfig; - GetAppComponents is LoadTestAdministration.GetAppComponents; - GetServerMetricsConfig is LoadTestAdministration.GetServerMetricsConfig; - GetTest is LoadTestAdministration.GetTest; - GetTestFile is LoadTestAdministration.GetTestFile; - ListTestFiles is LoadTestAdministration.ListTestFiles; - ListTests is LoadTestAdministration.ListTests; - UploadTestFile is LoadTestAdministration.UploadTestFile; - DeleteTestFile is LoadTestAdministration.DeleteTestFile; - DeleteTest is LoadTestAdministration.DeleteTest; -}; + createOrUpdateTest is LoadTestAdministration.createOrUpdateTest; + createOrUpdateAppComponents is LoadTestAdministration.createOrUpdateAppComponents; + createOrUpdateServerMetricsConfig is LoadTestAdministration.createOrUpdateServerMetricsConfig; + getAppComponents is LoadTestAdministration.getAppComponents; + getServerMetricsConfig is LoadTestAdministration.getServerMetricsConfig; + getTest is LoadTestAdministration.getTest; + getTestFile is LoadTestAdministration.getTestFile; + listTestFiles is LoadTestAdministration.listTestFiles; + listTests is LoadTestAdministration.listTests; + #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." + @clientName("BeginUploadTestFile", "python") + uploadTestFile is LoadTestAdministration.uploadTestFile; + deleteTestFile is LoadTestAdministration.deleteTestFile; + deleteTest is LoadTestAdministration.deleteTest; +} +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestRunClient", - service: AzureLoadTesting, + name: "LoadTestRunClient", + service: Microsoft.LoadTestService, }) interface TestRunOperations { - TestRun is LoadTestRun.CreateOrUpdateTestRun; - CreateOrUpdateAppComponents is LoadTestRun.CreateOrUpdateAppComponents; - CreateOrUpdateServerMetricsConfig is LoadTestRun.CreateOrUpdateServerMetricsConfig; - DeleteTestRun is LoadTestRun.DeleteTestRun; - GetAppComponents is LoadTestRun.GetAppComponents; - GetServerMetricsConfig is LoadTestRun.GetServerMetricsConfig; - GetTestRun is LoadTestRun.GetTestRun; - GetTestRunFile is LoadTestRun.GetTestRunFile; - ListMetricDimensionValues is LoadTestRun.ListMetricDimensionValues; - ListMetricDefinitions is LoadTestRun.ListMetricDefinitions; - ListMetricNamespaces is LoadTestRun.ListMetricNamespaces; - ListMetrics is LoadTestRun.ListMetrics; - ListTestRuns is LoadTestRun.ListTestRuns; - StopTestRun is LoadTestRun.StopTestRun; -}; + @clientName("BeginTestRun", "python") + createOrUpdateTestRun is LoadTestRun.createOrUpdateTestRun; + createOrUpdateAppComponents is LoadTestRun.createOrUpdateAppComponents; + createOrUpdateServerMetricsConfig is LoadTestRun.createOrUpdateServerMetricsConfig; + deleteTestRun is LoadTestRun.deleteTestRun; + getAppComponents is LoadTestRun.getAppComponents; + getServerMetricsConfig is LoadTestRun.getServerMetricsConfig; + getTestRun is LoadTestRun.getTestRun; + getTestRunFile is LoadTestRun.getTestRunFile; + listMetricDimensionValues is LoadTestRun.listMetricDimensionValues; + @clientName("get_metric_definitions", "python") + @clientName("getMetricDefinitions", "java") + listMetricDefinitions is LoadTestRun.listMetricDefinitions; + @clientName("get_metric_namespaces", "python") + @clientName("getMetricNamespaces", "java") + listMetricNamespaces is LoadTestRun.listMetricNamespaces; + listMetrics is LoadTestRun.listMetrics; + listTestRuns is LoadTestRun.listTestRuns; + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + stopTestRun is LoadTestRun.stop; +} diff --git a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp index 6fc3242049..db65771939 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp @@ -1,5 +1,6 @@ import "@typespec/rest"; import "@typespec/http"; +import "@typespec/versioning"; import "./routes.tsp"; using TypeSpec.Rest; @@ -9,7 +10,9 @@ using Azure.Core; @versioned(APIVersions) @useAuth(Oauth2) -@service({title: "Azure Load Testing"}) +@service({ + title: "Azure Load Testing", +}) @server( "https://{endpoint}", "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", @@ -18,17 +21,22 @@ using Azure.Core; } ) @doc(""" -These APIs allow end users to create, view and run load tests using Azure Load -Test Service. +These APIs allow end users to create, view and run load tests using Azure Load Test Service. """) -namespace AzureLoadTesting; +namespace Microsoft.LoadTestService; +@doc("Azure Load Testing API versions.") enum APIVersions { + @doc("The 2022-11-01 version of the Azure Load Testing API.") @useDependency(Azure.Core.Versions.v1_0_Preview_2) v2022_11_01: "2022-11-01", + + @doc("The 2023-04-01-preview version of the Azure Load Testing API.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + v2023_04_01_preview: "2023-04-01-preview", } -@doc("The Azure Active Directory OAuth2 Flow") +@doc("OAuth 2.0 Flow with Microsoft Entra ID.") model Oauth2 is OAuth2Auth<[ { @@ -36,4 +44,4 @@ model Oauth2 authorizationUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; scopes: ["https://cnt-prod.loadtesting.azure.com/.default"]; } - ]>; \ No newline at end of file + ]>; diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp index cb943d38b7..eab85f74cd 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp @@ -1,142 +1,204 @@ import "@typespec/rest"; import "@typespec/http"; import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Rest; using TypeSpec.Http; +using TypeSpec.Versioning; +using Azure.ClientGenerator.Core; -namespace AzureLoadTesting; +namespace Microsoft.LoadTestService; -enum PFMetrics { - @doc("Pass fail criteria for response time metric") response_time_ms, - @doc("Pass fail criteria for response time metric") latency, - @doc("Pass fail criteria for error metric") error, - @doc("Pass fail criteria for total requests") requests, - @doc("Pass fail criteria for request rate.") requests_per_sec, -} - -enum PFAgFunc { - @doc("Criteria applies for count value") count, - @doc("Criteria applies for given percentage value") percentage, - @doc("Criteria applies for avg value") avg, - @doc("Criteria applies for 50th percentile value") p50, - @doc("Criteria applies for 90th percentile value") p90, - @doc("Criteria applies for 95th percentile value") p95, - @doc("Criteria applies for 99th percentile value") p99, - @doc("Criteria applies for minimum value") min, - @doc("Criteria applies for maximum value") max, -} - -enum PFAction { - @doc("Test will continue to run even if pass fail metric criteria metric gets failed") - continue, - @doc("Test run will stop if pass fail criteria metric is not passed.") stop, -} - -enum PFResult { - @doc("Given pass fail criteria metric has passed.") passed, - @doc("Given pass fail criteria metric couldn't determine.") undetermined, - @doc("Given pass fail criteria metric has failed.") failed, -} - -enum SecretType { - @doc("If the secret is stored in an Azure Key Vault") AKV_SECRET_URI, - @doc("If the Plain text secret value provided") SECRET_VALUE, -} - -enum CertificateType { - @doc("If the certificate is stored in an Azure Key Vault") AKV_CERT_URI, -} - -enum FileType { - @doc("If file is jmx script") JMX_FILE, - @doc("If file is user properties") USER_PROPERTIES, - @doc("If file is not any of other supported type") ADDITIONAL_ARTIFACTS, -} - -enum FileStatus { - @doc("File is not validated.") NOT_VALIDATED, - @doc("File is validated.") VALIDATION_SUCCESS, - @doc("File validation is failed.") VALIDATION_FAILURE, - @doc("File validation is in progress.") VALIDATION_INITIATED, - @doc("Validation is not required.") VALIDATION_NOT_REQUIRED, -} - -enum PFTestResult { - @doc("Pass/fail criteria has passed.") PASSED, - @doc("Pass/fail criteria is not applicable.") NOT_APPLICABLE, - @doc("Pass/fail criteria has failed.") FAILED, -} - -enum Status { - @doc("Test run request is accepted") ACCEPTED, - @doc("Test run is not yet started.") NOTSTARTED, - @doc("Test run is getting provision") PROVISIONING, - @doc("Test run is provisioned") PROVISIONED, - @doc("Test run is getting configure") CONFIGURING, - @doc("Test run configuration is done") CONFIGURED, - @doc("Test run has started executing") EXECUTING, - @doc("Test run has been executed") EXECUTED, - @doc("Test run is getting deprovision") DEPROVISIONING, - @doc("Test run request is deprovisioned") DEPROVISIONED, - @doc("Test run request is finished") DONE, - @doc("Test run request is getting cancelled") CANCELLING, - @doc("Test run request is cancelled") CANCELLED, - @doc("Test run request is failed") FAILED, - @doc("Test run JMX file is validated") VALIDATION_SUCCESS, - @doc("Test run JMX file validation is failed") VALIDATION_FAILURE, -} - -enum AggregationType { - @doc("Average value") Average, - @doc("Total count") Count, - @doc("Aggregation will be average in this case") None, - @doc("Total sum") Total, - @doc("90th percentile") Percentile90, - @doc("95th percentile") Percentile95, - @doc("99th percentile") Percentile99, -} - -enum MetricUnit { - @doc("No unit specified") NotSpecified, - @doc("Percentage") Percent, - @doc("Value count") Count, - @doc("Seconds") Seconds, - @doc("Milliseconds") Milliseconds, - @doc("Bytes") Bytes, - @doc("Bytes per second") BytesPerSecond, - @doc("Count per second") CountPerSecond, -} - -enum TimeGrain { - @doc("5 seconds, available only if test run duration is less than 10 minutes") - PT5S, - @doc("10 seconds, available only if test run duration is less than 10 minutes") - PT10S, - @doc("1 minute") PT1M, - @doc("5 minutes, available only if test run duration is greater than 1 minute") - PT5M, - @doc("1 hour, available only if test run duration is greater than 1 minute") - PT1H, -} - -enum Interval { - @doc("5 seconds, available only if test run duration is less than 10 minutes") - PT5S, - @doc("10 seconds, available only if test run duration is less than 10 minutes") - PT10S, - @doc("1 minute") PT1M, - @doc("5 minutes, available only if test run duration is greater than 1 minute") - PT5M, - @doc("1 hour, available only if test run duration is greater than 1 minute") - PT1H, -} - -@doc("Load test model") +@doc("Metrics for pass/fail criteria.") +union PFMetrics { + string, + + @doc("Pass fail criteria for response time metric in milliseconds.") + "response_time_ms", + + @doc("Pass fail criteria for latency metric in milliseconds.") "latency", + @doc("Pass fail criteria for error metric.") "error", + @doc("Pass fail criteria for total requests.") "requests", + @doc("Pass fail criteria for request per second.") "requests_per_sec", +} + +@doc("Aggregation functions for pass/fail criteria.") +union PFAgFunc { + string, + @doc("Criteria applies for count value.") "count", + @doc("Criteria applies for given percentage value.") "percentage", + @doc("Criteria applies for avg value.") "avg", + @doc("Criteria applies for 50th percentile value.") "p50", + @doc("Criteria applies for 90th percentile value.") "p90", + @doc("Criteria applies for 95th percentile value.") "p95", + @doc("Criteria applies for 99th percentile value.") "p99", + @doc("Criteria applies for minimum value.") "min", + @doc("Criteria applies for maximum value.") "max", +} + +@doc("Action to take on failure of pass/fail criteria.") +union PFAction { + string, + + @doc("Test will continue to run even if pass fail metric criteria metric gets failed.") + continue: "continue", + + @doc("Test run will stop if pass fail criteria metric is not passed.") + stop: "stop", +} + +@doc("Pass/fail criteria result.") +union PFResult { + string, + @doc("Given pass fail criteria metric has passed.") "passed", + @doc("Given pass fail criteria metric couldn't determine.") "undetermined", + @doc("Given pass fail criteria metric has failed.") "failed", +} + +@doc("Types of secrets supported.") +union SecretType { + string, + @doc("If the secret is stored in an Azure Key Vault.") "AKV_SECRET_URI", + @doc("If the secret value provided as plain text.") "SECRET_VALUE", +} + +@doc("Types of certificates supported.") +union CertificateType { + string, + @doc("If the certificate is stored in an Azure Key Vault.") "AKV_CERT_URI", +} + +@doc("Types of file supported.") +union FileType { + string, + @doc("If the file is a JMX script.") "JMX_FILE", + @doc("If the file is a user properties file.") "USER_PROPERTIES", + + @doc("If the file is not among any of the other supported file types.") + "ADDITIONAL_ARTIFACTS", + + @added(APIVersions.v2023_04_01_preview) + @doc("If the file is a compressed archive containing a collection of various artifacts or resources.") + "ZIPPED_ARTIFACTS", + + @added(APIVersions.v2023_04_01_preview) + @doc("If the file is a JSON config file to define the requests for a URL test.") + "URL_TEST_CONFIG_JSON", +} + +@doc("File status.") +union FileStatus { + string, + @doc("File is not validated.") "NOT_VALIDATED", + @doc("File is validated.") "VALIDATION_SUCCESS", + @doc("File validation is failed.") "VALIDATION_FAILURE", + @doc("File validation is in progress.") "VALIDATION_INITIATED", + @doc("Validation is not required.") "VALIDATION_NOT_REQUIRED", +} + +@doc("Test result based on pass/fail criteria.") +union PFTestResult { + string, + @doc("Pass/fail criteria has passed.") "PASSED", + @doc("Pass/fail criteria is not applicable.") "NOT_APPLICABLE", + @doc("Pass/fail criteria has failed.") "FAILED", +} + +@doc("Test run status.") +union Status { + string, + @doc("Test run request is accepted.") "ACCEPTED", + @doc("Test run is not yet started.") "NOTSTARTED", + @doc("Test run is provisioning.") "PROVISIONING", + @doc("Test run is provisioned.") "PROVISIONED", + @doc("Test run is getting configured.") "CONFIGURING", + @doc("Test run configuration is done.") "CONFIGURED", + @doc("Test run has started executing.") "EXECUTING", + @doc("Test run execution is completed.") "EXECUTED", + @doc("Test run is getting deprovisioned.") "DEPROVISIONING", + @doc("Test run is deprovisioned.") "DEPROVISIONED", + @doc("Test run is completed.") "DONE", + @doc("Test run is being cancelled.") "CANCELLING", + @doc("Test run request is cancelled.") "CANCELLED", + @doc("Test run request is failed.") "FAILED", + @doc("Test run JMX file is validated.") "VALIDATION_SUCCESS", + @doc("Test run JMX file validation is failed.") "VALIDATION_FAILURE", +} + +@doc("Aggregation type.") +union AggregationType { + string, + @doc("Average value.") "Average", + @doc("Total count.") "Count", + @doc("Aggregation will be average in this case.") "None", + @doc("Total sum.") "Total", + @doc("90th percentile.") "Percentile90", + @doc("95th percentile.") "Percentile95", + @doc("99th percentile.") "Percentile99", +} + +@doc("Metric unit.") +union MetricUnit { + string, + @doc("No unit specified.") "NotSpecified", + @doc("Percentage.") "Percent", + @doc("Value count.") "Count", + @doc("Seconds.") "Seconds", + @doc("Milliseconds") "Milliseconds", + @doc("Bytes") "Bytes", + @doc("Bytes per second") "BytesPerSecond", + @doc("Count per second") "CountPerSecond", +} + +@doc("Time Grain") +union TimeGrain { + string, + + @doc("5 seconds, available only if test run duration is less than 10 minutes.") + PT5S: "PT5S", + + @doc("10 seconds, available only if test run duration is less than 10 minutes.") + PT10S: "PT10S", + + @doc("1 minute") + PT1M: "PT1M", + + @doc("5 minutes, available only if test run duration is greater than 1 minute.") + PT5M: "PT5M", + + @doc("1 hour, available only if test run duration is greater than 1 minute.") + PT1H: "PT1H", +} + +@added(APIVersions.v2023_04_01_preview) +@doc("Test kind") +union TestKind { + string, + @doc("URL Test") "URL", + @doc("JMX Test") "JMX", +} + +@doc("Test file info.") +@resource("files") +@parentResource(Test) +model TestFileInfo is FileInfo; + +@doc("Test run file info.") +@resource("files") +@parentResource(TestRun) +model TestRunFileInfo is FileInfo; + +@doc("Load test model.") +@resource("tests") model Test { @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; + @added(APIVersions.v2023_04_01_preview) + @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") + autoStopCriteria?: AutoStopCriteria; + @doc(""" Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret @@ -146,7 +208,7 @@ SECRET_VALUE. """) secrets?: Record; - @doc("Certificates metadata") + @doc("Certificates metadata.") certificate?: CertificateMetadata; @doc("Environment variables which are defined as a set of pairs.") @@ -155,44 +217,44 @@ SECRET_VALUE. @doc("The load test configuration.") loadTestConfiguration?: LoadTestConfiguration; + @added(APIVersions.v2023_04_01_preview) + @doc("Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs") + baselineTestRunId?: string; + @doc("The input artifacts for the test.") @visibility("read") inputArtifacts?: TestInputArtifacts; - @doc("Unique test name as identifier.") - @visibility("read") - testId?: string; + ...TestIdPathParameter; + @maxLength(100) @doc("The test description.") description?: string; + @maxLength(50) + @minLength(2) @doc("Display name of a test.") displayName?: string; @doc("Subnet ID on which the load test instances should run.") subnetId?: string; + @added(APIVersions.v2023_04_01_preview) + @doc("Kind of test.") + kind?: TestKind; + + #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" + @added(APIVersions.v2023_04_01_preview) + @doc("Inject load test engines without deploying public IP for outbound access") + publicIPDisabled?: boolean; + @doc("Type of the managed identity referencing the Key vault.") keyvaultReferenceIdentityType?: string; @doc("Resource Id of the managed identity referencing the Key vault.") keyvaultReferenceIdentityId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc("Pass fail criteria for a test.") @@ -224,14 +286,14 @@ The aggregation function to be applied on the client metric. Allowed functions The value to compare with the client metric. Allowed values - ‘error : [0.0 , 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. """) - value?: float32; + value?: float64; @doc("Action taken after the threshold is met. Default is ‘continue’.") - action?: PFAction; + action?: PFAction = PFAction.continue; @doc("The actual value of the client metric for the test run.") @visibility("read") - actualValue?: float32; + actualValue?: float64; @doc("Outcome of the test run.") @visibility("read") @@ -259,119 +321,121 @@ model CertificateMetadata { name?: string; } -@doc("The load test configuration.") +@added(APIVersions.v2023_04_01_preview) +@doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") +model AutoStopCriteria { + @doc("Whether auto-stop should be disabled. The default value is false.") + autoStopDisabled?: boolean = false; + + @doc("Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0") + errorRate?: float32 = 90; + + @doc("Time window during which the error percentage should be evaluated in seconds.") + errorRateTimeWindowInSeconds?: int32 = 60; +} + +@doc("Configurations for the load test.") model LoadTestConfiguration { @doc(""" -The number of engine instances to execute load test. Supported values are in -range of 1-45. Required for creating a new test. +The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. """) engineInstances?: int32; + #suppress "@azure-tools/typespec-azure-core/casing-style" "CSV is an abbervation and should be all caps" @doc(""" If false, Azure Load Testing copies and processes your input files unmodified across all test engine instances. If true, Azure Load Testing splits the CSV input data evenly across all engine instances. If you provide multiple CSV files, each file will be split evenly. """) - splitAllCSVs?: boolean; + splitAllCSVs?: boolean = false; @doc(""" If true, optionalLoadTestConfig is required and JMX script for the load test is not required to upload. """) - quickStartTest?: boolean; + quickStartTest?: boolean = false; - @doc("Optional load test config") + @doc("Configuration for quick load test") optionalLoadTestConfig?: OptionalLoadTestConfig; } -@doc("Optional load test config") +@doc("Configuration for quick load test") model OptionalLoadTestConfig { - @doc(""" -Test URL. Provide the complete HTTP URL. For example, -http://contoso-app.azurewebsites.net/login -""") + @doc("Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login") endpointUrl?: string; - @doc("No of concurrent virtual users") + @doc("Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it.") + @added(APIVersions.v2023_04_01_preview) + requestsPerSecond?: int32; + + @doc("Maximum response time in milliseconds of the API/endpoint.") + @added(APIVersions.v2023_04_01_preview) + maxResponseTimeInMs?: int32; + + @doc("No of concurrent virtual users.") virtualUsers?: int32; - @doc("Ramp up time") + @doc("Ramp up time in seconds.") rampUpTime?: int32; - @doc("Test run duration") + @doc("Test run duration in seconds.") duration?: int32; } @doc("The input artifacts for the test.") model TestInputArtifacts { @doc("File info") - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; @doc("File info") - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; @doc("File info") - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; @doc("File info") - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + + @added(APIVersions.v2023_04_01_preview) + @doc("The config json file for url based test") + urlTestConfigFileInfo?: TestFileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: FileInfo[]; + additionalFileInfo?: TestFileInfo[]; } @doc("File info") model FileInfo { - @doc("File URL.") - url?: string; - @doc("Name of the file.") - fileName?: string; + @key + @visibility + fileName: string; + + @doc("File URL.") + //update description + @visibility("read") + url?: url; @doc("File type") + @visibility("read") fileType?: FileType; - @doc("Expiry time of the file (ISO 8601 literal format)") - expireDateTime?: offsetDateTime; + @doc("Expiry time of the file (RFC 3339 literal format)") + @visibility("read") + expireDateTime?: utcDateTime; @doc("Validation status of the file") + @visibility("read") validationStatus?: FileStatus; @doc("Validation failure error details") + @visibility("read") validationFailureDetails?: string; } -@doc("The definition of an error object.") -@error -model ErrorResponseBody { - @doc("Error from a REST request.") - error: Error; -} - -@doc("Error from a REST request.") -model Error { - @doc("The error code.") - code: string; - - @doc("The error message.") - message: string; - - @doc("The error target.") - target?: string; - - @doc("Additional details and inner errors.") - details?: Error[]; -} - -@doc("Collection of tests") -model TestsList is Azure.Core.Page; - -@doc("Collection of files.") -model FileInfoList is Azure.Core.Page; - -@doc("Test app component") +@doc("Test app components") model TestAppComponents { @doc(""" Azure resource collection { resource id (fully qualified resource Id e.g @@ -384,40 +448,24 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo @visibility("read") testId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc(""" -An Azure resource object (Refer azure generic resource model : -https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) +An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) """) model AppComponent { @doc(""" -fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} +fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} """) @visibility("read") - resourceId?: string; + resourceId: string; @doc("Azure resource name, required while creating the app component.") - resourceName?: string; + resourceName: string; @doc("Azure resource type, required while creating the app component.") - resourceType?: string; + resourceType: string; @doc("Azure resource display name") displayName?: string; @@ -445,23 +493,9 @@ Azure resource metrics collection {metric id : metrics object} (Refer : https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition for metric id). """) - metrics?: Record; - - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; + metrics: Record; - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc(""" @@ -498,21 +532,16 @@ model ResourceMetric { @doc("Load test run model") @resource("test-runs") -model TestRuns { - // FIXME: is testRunId optional or required in the response? Resource key and path params cannot be optional - @key - @doc("Unique test run name as identifier") - @visibility("read") - testRunId: string; -} - -@doc("Load test run model") model TestRun { - ...TestRuns, + ...TestRunIdPathParameter; @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; + @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") + @added(APIVersions.v2023_04_01_preview) + autoStopCriteria?: AutoStopCriteria; + @doc(""" Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret @@ -551,12 +580,17 @@ SECRET_VALUE. @visibility("read") virtualUsers?: int32; + @maxLength(50) + @minLength(2) @doc("Display name of a testRun.") displayName?: string; + @maxLength(50) + @minLength(2) @doc("Associated test Id.") testId?: string; + @maxLength(100) @doc("The test run description.") description?: string; @@ -564,17 +598,17 @@ SECRET_VALUE. @visibility("read") status?: Status; - @doc("The test run start DateTime(ISO 8601 literal format).") + @doc("The test run start DateTime(RFC 3339 literal format).") @visibility("read") - startDateTime?: offsetDateTime; + startDateTime?: utcDateTime; - @doc("The test run end DateTime(ISO 8601 literal format).") + @doc("The test run end DateTime(RFC 3339 literal format).") @visibility("read") - endDateTime?: offsetDateTime; + endDateTime?: utcDateTime; @doc("Test run initiated time.") @visibility("read") - executedDateTime?: offsetDateTime; + executedDateTime?: utcDateTime; @doc("Portal url.") @visibility("read") @@ -582,27 +616,24 @@ SECRET_VALUE. @doc("Test run duration in milliseconds.") @visibility("read") - duration?: int32; + duration?: int64; @doc("Subnet ID on which the load test instances should run.") @visibility("read") subnetId?: string; - @doc("The creation datetime(ISO 8601 literal format).") + @added(APIVersions.v2023_04_01_preview) + @doc("Type of test.") @visibility("read") - createdDateTime?: offsetDateTime; + kind?: TestKind; - @doc("The user that created.") + #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" + @added(APIVersions.v2023_04_01_preview) + @doc("Inject load test engines without deploying public IP for outbound access") @visibility("read") - createdBy?: string; + publicIPDisabled?: boolean; - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc("Error details if there is any failure in load test run") @@ -620,55 +651,57 @@ model TestRunStatistics { @doc("Sampler count.") @visibility("read") - sampleCount?: float32; + sampleCount?: float64; @doc("Error count.") @visibility("read") - errorCount?: float32; + errorCount?: float64; @doc("Error percentage.") @visibility("read") - errorPct?: float32; + errorPct?: float64; @doc("Mean response time.") @visibility("read") - meanResTime?: float32; + meanResTime?: float64; @doc("Median response time.") @visibility("read") - medianResTime?: float32; + medianResTime?: float64; @doc("Max response time.") @visibility("read") - maxResTime?: float32; + maxResTime?: float64; @doc("Minimum response time.") @visibility("read") - minResTime?: float32; + minResTime?: float64; @doc("90 percentile response time.") @visibility("read") - pct1ResTime?: float32; + pct1ResTime?: float64; @doc("95 percentile response time.") @visibility("read") - pct2ResTime?: float32; + pct2ResTime?: float64; @doc("99 percentile response time.") @visibility("read") - pct3ResTime?: float32; + pct3ResTime?: float64; @doc("Throughput.") @visibility("read") - throughput?: float32; + throughput?: float64; + #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Received network bytes.") @visibility("read") - receivedKBytesPerSec?: float32; + receivedKBytesPerSec?: float64; + #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Send network bytes.") @visibility("read") - sentKBytesPerSec?: float32; + sentKBytesPerSec?: float64; } @doc("Collection of test run artifacts") @@ -684,33 +717,48 @@ model TestRunArtifacts { @doc("The input artifacts for the test run.") model TestRunInputArtifacts { @doc("File info") - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; @doc("File info") - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; @doc("File info") - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; @doc("File info") - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + + @added(APIVersions.v2023_04_01_preview) + @doc("The config json file for url based test") + urlTestConfigFileInfo?: TestRunFileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: FileInfo[]; + additionalFileInfo?: TestRunFileInfo[]; } @doc("The output artifacts for the test run.") model TestRunOutputArtifacts { @doc("File info") - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; @doc("File info") - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + + @doc("The container for test run artifacts.") + @added(APIVersions.v2023_04_01_preview) + artifactsContainerInfo?: ArtifactsContainerInfo; } -@doc("Collection of test runs") -model TestRunsList is Azure.Core.Page; +@doc("Artifacts container info.") +@added(APIVersions.v2023_04_01_preview) +model ArtifactsContainerInfo { + @doc("This is a SAS URI to an Azure Storage Container that contains the test run artifacts.") + url?: url; + + @doc("Expiry time of the container (RFC 3339 literal format)") + expireDateTime?: utcDateTime; +} @doc("Represents collection of metric namespaces.") model MetricNamespaceCollection { @@ -781,7 +829,7 @@ a duration 'PT1M', 'PT1H', etc. timeGrain?: TimeGrain; } -@doc("Filters to fetch the set of metric") +@doc("Filters to fetch the set of metric.") model MetricRequestPayload { @doc(""" Get metrics for specific dimension values. Example: Metric contains dimension @@ -802,6 +850,8 @@ model DimensionFilter { } @doc("The response to a metrics query.") +@friendlyName("Metrics") +// using friendlyName to change the name of the model due to issue in using projectedName '@encodedName("application/json", "Metrics")' https://github.com/microsoft/typespec/issues/2276 model Metrics is Azure.Core.Page; @doc("The time series returned when a data query is performed.") @@ -815,11 +865,11 @@ model TimeSeriesElement { @doc("Represents a metric value.") model MetricValue { - @doc("The timestamp for the metric value in ISO 8601 format.") - timestamp?: string; + @doc("The timestamp for the metric value in RFC 3339 format.") + timestamp?: utcDateTime; @doc("The metric value.") - value?: float32; + value?: float64; } @doc("Represents a metric dimension value.") @@ -831,42 +881,41 @@ model DimensionValue { value?: string; } -@resource("values") -@parentResource(Dimension) +@doc("Metrics dimension values.") model DimensionValueList { - @key - value: string[]; -} + @doc("The dimension name") + @visibility("read") + @added(APIVersions.v2023_04_01_preview) + name?: string; -@resource("metric-dimensions") -@parentResource(TestRuns) -model Dimension { - @key - @doc("Dimension name") - @visibility("query") - name: string; + @doc("The dimension value") + value?: string[]; + + @doc("Link for the next set of values in case of paginated results, if applicable.") + nextLink?: ResourceLocation; } -model MetricDimensions { - @doc("The interval (i.e. timegrain) of the query.") +@doc("Metric Dimensions") +model MetricDimensionsRequest { + @doc("Metric name") @query - interval?: Interval; + metricname: string; - @doc("Metric name") + @doc("The interval (i.e. timegrain) of the query.") @query - metricName?: string; + interval?: TimeGrain = TimeGrain.PT1M; @doc("Metric namespace to query metric definitions for.") @query metricNamespace: string; @doc(""" - The timespan of the query. It is a string with the following format - 'startDateTime_ISO/endDateTime_ISO'. + The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. """) @query - timespan?: string; -}; + @clientName("time_interval", "python") + timespan: string; +} @doc("Test run app component") model TestRunAppComponents { @@ -881,21 +930,7 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo @visibility("read") testRunId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc("Test run server metrics configuration") @@ -911,23 +946,136 @@ for metric id). """) metrics?: Record; - @doc("The creation datetime(ISO 8601 literal format).") + ...SystemMetaData; +} + +@doc("Query parameters for list test run operation") +model OldTestRunIdQueryParam { + @doc(""" +Existing test run identifier that should be rerun, if this is provided, the +test will run with the JMX file, configuration and app components from the +existing test run. You can override the configuration values for new test run +in the request body. +""") + @query + oldTestRunId?: string; +} + +@doc("Parameters for list test run operation") +model ListTestRunQueryParams { + @doc(""" +Sort on the supported fields in (field asc/desc) format. eg: executedDateTime +asc. Supported fields - executedDateTime +""") + @query + orderby?: string; + + @doc(""" +Prefix based, case sensitive search on searchable fields - description, +executedUser. For example, to search for a test run, with description 500 VUs, +the search parameter can be 500. +""") + @query + search?: string; + + @doc("Unique name of an existing load test.") + @query + testId?: string; + + @doc("Start DateTime(RFC 3339 literal format) of test-run execution time filter range.") + @query + executionFrom?: utcDateTime; + + @doc("End DateTime(RFC 3339 literal format) of test-run execution time filter range.") + @query + executionTo?: utcDateTime; + + @doc("Comma separated list of test run status.") + @query + status?: string; + + @doc("Number of results in response.") + @query + maxpagesize?: int32 = 50; +} + +@doc("Parameters for list test operation") +model ListTestQueryParams { + @doc(""" +Sort on the supported fields in (field asc/desc) format. eg: +lastModifiedDateTime asc. Supported fields - lastModifiedDateTime +""") + @query + orderby?: string; + + @doc(""" +Prefix based, case sensitive search on searchable fields - displayName, +createdBy. For example, to search for a test, with display name is Login Test, +the search parameter can be Login. +""") + @query + search?: string; + + @doc(""" +Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. +""") + @query + lastModifiedStartTime?: utcDateTime; + + @doc(""" +End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. +""") + @query + lastModifiedEndTime?: utcDateTime; + + @doc("Number of results in response.") + @query + maxpagesize?: int32 = 50; +} + +@doc("System metadata.") +model SystemMetaData { + @doc("The creation datetime(RFC 3339 literal format).") @visibility("read") - createdDateTime?: offsetDateTime; + createdDateTime?: utcDateTime; @doc("The user that created.") @visibility("read") createdBy?: string; - @doc("The last Modified datetime(ISO 8601 literal format).") + @doc("The last Modified datetime(RFC 3339 literal format).") @visibility("read") - lastModifiedDateTime?: offsetDateTime; + lastModifiedDateTime?: utcDateTime; @doc("The user that last modified.") @visibility("read") lastModifiedBy?: string; } -alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & T; +@doc("Test Id path parameter.") +model TestIdPathParameter { + @doc("Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @maxLength(50) + @minLength(2) + @key + @visibility("read") + @pattern("^[a-z0-9_-]*$") + testId: string; +} + +@doc("Test run Id path parameter.") +model TestRunIdPathParameter { + @doc("Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @visibility("read") + @maxLength(50) + @minLength(2) + @key + @pattern("^[a-z0-9_-]*$") + testRunId: string; +} + +alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & + T; -alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | TypeSpec.Http.Response<200> & T; +alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | (TypeSpec.Http.Response<200> & + T); diff --git a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp index fd8f628931..e767bbc297 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp @@ -1,67 +1,39 @@ import "@azure-tools/typespec-azure-core"; import "@typespec/rest"; +import "@typespec/http"; +import "@typespec/openapi"; +import "@azure-tools/typespec-client-generator-core"; import "./models.tsp"; using Azure.Core; using Azure.Core.Traits; using TypeSpec.Rest; using TypeSpec.Http; +using TypeSpec.Versioning; +using OpenAPI; +using Azure.ClientGenerator.Core; -namespace AzureLoadTesting; +namespace Microsoft.LoadTestService; -interface LoadTestAdministration { - @summary("Create a new test or update an existing test.") - @doc("Create a new test or update an existing test.") - @route("/tests/{testId}") - @patch - CreateOrUpdateTest is Azure.Core.Foundations.Operation< - { - @header contentType: "application/merge-patch+json", - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; +@@encodedName(Azure.Core.Foundations.ResourceBody.resource, + "application/json", + "body" +); +@@clientName(Azure.Core.Foundations.ResourceBody.resource, "body"); - @doc("Load test model") - @body - body: Test; - }, - ResourceCreatedOrOkResponse - >; +@tag("Test") +interface LoadTestAdministration { + @summary("Create a new test or update an existing test by providing the test Id.") + @doc("Create a new test or update an existing test by providing the test Id.") + createOrUpdateTest is StandardResourceOperations.ResourceCreateOrUpdate; - @summary("Delete a test by its name.") - @doc("Delete a test by its name.") - @route("/tests/{testId}") - @delete - DeleteTest is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - void - >; + @summary("Delete a test by its test Id.") + @doc("Delete a test by its test Id.") + deleteTest is StandardResourceOperations.ResourceDelete; - @summary("Get load test details by test name") - @doc("Get load test details by test name") - @route("/tests/{testId}") - @get - GetTest is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - Test - >; + @summary("Get load test details by test Id") + @doc("Get load test details by test Id") + getTest is StandardResourceOperations.ResourceRead; @summary(""" Get all load tests by the fully qualified resource Id e.g @@ -71,66 +43,39 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo Get all load tests by the fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. """) - @route("/tests") - @get - ListTests is Azure.Core.Foundations.Operation< - { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: -lastModifiedDateTime asc. Supported fields - lastModifiedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - displayName, -createdBy. For example, to search for a test, with display name is Login Test, -the search parameter can be Login. -""") - @query - search?: string; - - @doc(""" -Start DateTime(ISO 8601 literal format) of the last updated time range to -filter tests. -""") - @query - lastModifiedStartTime?: offsetDateTime; - - @doc(""" -End DateTime(ISO 8601 literal format) of the last updated time range to filter -tests. -""") - @query - lastModifiedEndTime?: offsetDateTime; - - @doc("Number of results in response.") - @query - maxpagesize?: int32; - }, - TestsList + listTests is StandardResourceOperations.ResourceList< + Test, + ListQueryParametersTrait >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Our operation is not following the standard put behavior https://github.com/Azure/typespec-azure/issues/3743" + #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." @summary(""" -Upload input file for a given test name. File size can't be more than 50 MB. +Upload input file for a given test Id. File size can't be more than 50 MB. Existing file with same name for the given test will be overwritten. File should be provided in the request body as application/octet-stream. """) @doc(""" -Upload input file for a given test name. File size can't be more than 50 MB. +Upload input file for a given test Id. File size can't be more than 50 MB. Existing file with same name for the given test will be overwritten. File should be provided in the request body as application/octet-stream. """) @route("/tests/{testId}/files/{fileName}") @put - UploadTestFile is Azure.Core.Foundations.Operation< + uploadTestFile is Azure.Core.Foundations.Operation< { - @header contentType: "application/octet-stream", + @header + @doc("Content type.") + contentType: "application/octet-stream"; + @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("Unique name for test file with file extension like : App.jmx") @@ -145,77 +90,40 @@ numeric, underscore or hyphen characters. @body body: bytes; }, - ResourceCreatedResponse + ResourceCreatedResponse >; - @summary("Get test file by the file name.") - @doc("Get test file by the file name.") - @route("/tests/{testId}/files/{fileName}") - @get - GetTestFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - - @doc("File name with file extension like app.jmx") - @path - fileName: string; - }, - FileInfo - >; + @summary("Get all the files that are associated with a test.") + @doc("Get all the files that are associated with a test.") + getTestFile is StandardResourceOperations.ResourceRead; @summary("Delete file by the file name for a test") @doc("Delete file by the file name for a test") - @route("/tests/{testId}/files/{fileName}") - @delete - DeleteTestFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - - @doc("File name with file extension like app.jmx") - @path - fileName: string; - }, - void - >; + deleteTestFile is StandardResourceOperations.ResourceDelete; @summary("Get all test files.") @doc("Get all test files.") - @route("/tests/{testId}/files") - @get - ListTestFiles is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - FileInfoList - >; + listTestFiles is StandardResourceOperations.ResourceList; - @summary("Associate an app component (collection of azure resources) to a test") - @doc("Associate an app component (collection of azure resources) to a test") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Add an app component to a test.") + @doc("Add an app component to a test by providing the resource Id, name and type.") @route("/tests/{testId}/app-components") @patch - CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< + createOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("App Component model.") @@ -225,34 +133,45 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Get associated app component (collection of azure resources) for the given test.") @doc("Get associated app component (collection of azure resources) for the given test.") @route("/tests/{testId}/app-components") @get - GetAppComponents is Azure.Core.Foundations.Operation< + getAppComponents is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; }, TestAppComponents >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test") @doc("Configure server metrics for a test") @route("/tests/{testId}/server-metrics-config") @patch - CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("Server metric configuration model.") @@ -262,253 +181,180 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List server metrics configuration for the given test.") @doc("List server metrics configuration for the given test.") @route("/tests/{testId}/server-metrics-config") @get - GetServerMetricsConfig is Azure.Core.Foundations.Operation< + getServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; }, TestServerMetricConfig >; } +@tag("TestRun") interface LoadTestRun { - @summary("Delete a test run by its name.") - @doc("Delete a test run by its name.") - @route("/test-runs/{testRunId}") - @delete - DeleteTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - void - >; - - @summary("Create and start a new test run with the given name.") - @doc("Create and start a new test run with the given name.") - // @pollingOperation(LoadTestRun.GetTestRun) - CreateOrUpdateTestRun is LongRunningResourceCreateOrUpdate< - TestRun, - QueryParametersTrait< - { - @doc(""" - Existing test run identifier that should be rerun, if this is provided, the - test will run with the JMX file, configuration and app components from the - existing test run. You can override the configuration values for new test run - in the request body. - """) - @query - oldTestRunId?: string; - } - > + @summary("Get test run details by test run Id.") + @doc("Get test run details by test run Id.") + getTestRun is StandardResourceOperations.ResourceRead; + + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Create and start a new test run with the given test run Id.") + @doc("Create and start a new test run with the given test run Id.") + createOrUpdateTestRun is StandardResourceOperations.ResourceCreateOrUpdate< + TestRun, + QueryParametersTrait >; + @summary("Delete an existing load test run.") + @doc("Delete an existing load test run by providing the testRunId.") + deleteTestRun is StandardResourceOperations.ResourceDelete; - @summary("Get test run details by name.") - @doc("Get test run details by name.") - @route("/test-runs/{testRunId}") - @get - GetTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - TestRun + @summary("Get all test runs for the given filters.") + @doc("Get all test runs for the given filters.") + listTestRuns is StandardResourceOperations.ResourceList< + TestRun, + ListQueryParametersTrait >; @summary("Get test run file by file name.") @doc("Get test run file by file name.") - @route("/test-runs/{testRunId}/files/{fileName}") - @get - GetTestRunFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - - @doc("Test run file name with file extension") - @path - fileName: string; - }, - FileInfo - >; + getTestRunFile is StandardResourceOperations.ResourceRead; - @summary("Get all test runs with given filters") - @doc("Get all test runs with given filters") - @route("/test-runs") - @get - ListTestRuns is Azure.Core.Foundations.Operation< - { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: executedDateTime -asc. Supported fields - executedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - description, -executedUser. For example, to search for a test run, with description 500 VUs, -the search parameter can be 500. -""") - @query - search?: string; - - @doc("Unique name of an existing load test.") - @query - testId?: string; - - @doc("Start DateTime(ISO 8601 literal format) of test-run execution time filter range.") - @query - executionFrom?: offsetDateTime; - - @doc("End DateTime(ISO 8601 literal format) of test-run execution time filter range.") - @query - executionTo?: offsetDateTime; - - @doc("Comma separated list of test run status.") - @query - status?: string; - - @doc("Number of results in response.") - @query - maxpagesize?: int32; - }, - TestRunsList - >; - - @summary("Stop test run by name.") - @doc("Stop test run by name.") - @route("/test-runs/{testRunId}:stop") - @post - StopTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - TestRun - >; + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + @summary("Stop test run by test run Id.") + @doc("Stop test run by test run Id.") + @operationId("LoadTestRun_StopTestRun") + stop is StandardResourceOperations.ResourceAction; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric namespaces for a load test run.") @doc("List the metric namespaces for a load test run.") @route("/test-runs/{testRunId}/metric-namespaces") @get - ListMetricNamespaces is Azure.Core.Foundations.Operation< + listMetricNamespaces is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, MetricNamespaceCollection >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric definitions for a load test run.") @doc("List the metric definitions for a load test run.") @route("/test-runs/{testRunId}/metric-definitions") @get - ListMetricDefinitions is Azure.Core.Foundations.Operation< + listMetricDefinitions is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Metric namespace to query metric definitions for.") @query - metricNamespace?: string; + metricNamespace: string; }, MetricDefinitionCollection >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric values for a load test run.") @doc("List the metric values for a load test run.") @route("/test-runs/{testRunId}/metrics") @post - ListMetrics is Azure.Core.Foundations.Operation< + listMetrics is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("The aggregation") @query aggregation?: string; - @doc("The interval (i.e. timegrain) of the query.") - @query - interval?: Interval; - - @doc("Metric name") - @query - metricName?: string; - - @doc("Metric namespace to query metric definitions for.") - @query - metricNamespace?: string; - - @doc(""" -The timespan of the query. It is a string with the following format -'startDateTime_ISO/endDateTime_ISO'. -""") - @query - timespan?: string; + ...MetricDimensionsRequest; @doc("Metric dimension filter ") @body - body: MetricRequestPayload; + body?: MetricRequestPayload; }, Metrics >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the dimension values for the given metric dimension name.") @doc("List the dimension values for the given metric dimension name.") - ListMetricDimensionValues is Azure.Core.ResourceList< - DimensionValueList, QueryParametersTrait + @route("/test-runs/{testRunId}/metric-dimensions/{name}/values") + listMetricDimensionValues is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test run, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") + testRunId: string; + + @doc("Dimension name") + @path + name: string; + + ...MetricDimensionsRequest; + }, + DimensionValueList >; - @summary("Associate an app component (collection of azure resources) to a test run") - @doc("Associate an app component (collection of azure resources) to a test run") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Add an app component to a test run.") + @doc("Add an app component to a test run by providing the resource Id, name and type.") @route("/test-runs/{testRunId}/app-components") @patch - CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< + createOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, +Unique Id for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("App Component model.") @@ -518,6 +364,7 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary(""" Get associated app component (collection of azure resources) for the given test run. @@ -528,30 +375,40 @@ run. """) @route("/test-runs/{testRunId}/app-components") @get - GetAppComponents is Azure.Core.Foundations.Operation< + getAppComponents is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunAppComponents >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test run") @doc("Configure server metrics for a test run") @route("/test-runs/{testRunId}/server-metrics-config") @patch - CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, +Unique Id for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Server metric configuration model.") @@ -561,20 +418,23 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; - @summary("List server metrics configuration for the given test run.") - @doc("List server metrics configuration for the given test run.") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Get associated server metrics configuration for the given test run.") + @doc("Get associated server metrics configuration for the given test run.") @route("/test-runs/{testRunId}/server-metrics-config") @get - @encodedName("application/json", "TestRun_ListServerMetricsConfig") - GetServerMetricsConfig is Azure.Core.Foundations.Operation< + getServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunServerMetricConfig >; -}; +} From d382b8116434718b79bbcf2d070f3565b9f0794d Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 17 Jun 2024 12:58:54 +0800 Subject: [PATCH 04/18] Update the test cases --- .../generated/openapi/openapi.2022-11-01.json | 3935 ++++++++++++++++ .../openapi/openapi.2023-04-01-preview.json | 4108 +++++++++++++++++ .../test/loadtesting_modular/tspconfig.yaml | 4 + 3 files changed, 8047 insertions(+) create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2022-11-01.json create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2023-04-01-preview.json diff --git a/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2022-11-01.json b/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2022-11-01.json new file mode 100644 index 0000000000..bc96a5be3d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2022-11-01.json @@ -0,0 +1,3935 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Azure Load Testing", + "description": "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", + "version": "2022-11-01" + }, + "tags": [ + { + "name": "Test" + }, + { + "name": "TestRun" + } + ], + "paths": { + "/test-runs": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listTestRuns", + "summary": "Get all test runs for the given filters.", + "description": "Get all test runs for the given filters.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.orderby" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.search" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.testId" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.executionFrom" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.executionTo" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.status" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.maxpagesize" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getTestRun", + "summary": "Get test run details by test run Id.", + "description": "Get test run details by test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateTestRun", + "summary": "Create and start a new test run with the given test run Id.", + "description": "Create and start a new test run with the given test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "$ref": "#/components/parameters/OldTestRunIdQueryParam" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The resource instance.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunCreateOrUpdate" + } + } + } + } + }, + "delete": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_deleteTestRun", + "summary": "Delete an existing load test run.", + "description": "Delete an existing load test run by providing the testRunId.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/app-components": { + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateAppComponents", + "summary": "Add an app component to a test run.", + "description": "Add an app component to a test run by providing the resource Id, name and type.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique Id for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "App Component model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponentsUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getAppComponents", + "summary": "Get associated app component (collection of azure resources) for the given test\nrun.", + "description": "Get associated app component (collection of azure resources) for the given test\nrun.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/files/{fileName}": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getTestRunFile", + "summary": "Get test run file by file name.", + "description": "Get test run file by file name.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-definitions": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricDefinitions", + "summary": "List the metric definitions for a load test run.", + "description": "List the metric definitions for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "metricNamespace", + "in": "query", + "required": true, + "description": "Metric namespace to query metric definitions for.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricDefinitionCollection" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-dimensions/{name}/values": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricDimensionValues", + "summary": "List the dimension values for the given metric dimension name.", + "description": "List the dimension values for the given metric dimension name.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "name", + "in": "path", + "required": true, + "description": "Dimension name", + "schema": { + "type": "string" + } + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricname" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.interval" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricNamespace" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.timespan" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DimensionValueList" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-namespaces": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricNamespaces", + "summary": "List the metric namespaces for a load test run.", + "description": "List the metric namespaces for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricNamespaceCollection" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metrics": { + "post": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetrics", + "summary": "List the metric values for a load test run.", + "description": "List the metric values for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "aggregation", + "in": "query", + "required": false, + "description": "The aggregation", + "schema": { + "type": "string" + } + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricname" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.interval" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricNamespace" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.timespan" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Metrics" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Metric dimension filter ", + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricRequestPayload" + } + } + } + } + } + }, + "/test-runs/{testRunId}/server-metrics-config": { + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateServerMetricsConfig", + "summary": "Configure server metrics for a test run", + "description": "Configure server metrics for a test run", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique Id for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Server metric configuration model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + } + }, + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getServerMetricsConfig", + "summary": "Get associated server metrics configuration for the given test run.", + "description": "Get associated server metrics configuration for the given test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}:stop": { + "post": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_StopTestRun", + "summary": "Stop test run by test run Id.", + "description": "Stop test run by test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests": { + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_listTests", + "summary": "Get all load tests by the fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}.", + "description": "Get all load tests by the fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.orderby" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.search" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.lastModifiedStartTime" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.lastModifiedEndTime" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.maxpagesize" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTest" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateTest", + "summary": "Create a new test or update an existing test by providing the test Id.", + "description": "Create a new test or update an existing test by providing the test Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The resource instance.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestCreateOrUpdate" + } + } + } + } + }, + "delete": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_deleteTest", + "summary": "Delete a test by its test Id.", + "description": "Delete a test by its test Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getTest", + "summary": "Get load test details by test Id", + "description": "Get load test details by test Id", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/app-components": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateAppComponents", + "summary": "Add an app component to a test.", + "description": "Add an app component to a test by providing the resource Id, name and type.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "App Component model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponentsUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getAppComponents", + "summary": "Get associated app component (collection of azure resources) for the given test.", + "description": "Get associated app component (collection of azure resources) for the given test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/files": { + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_listTestFiles", + "summary": "Get all test files.", + "description": "Get all test files.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/files/{fileName}": { + "put": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_uploadTestFile", + "summary": "Upload input file for a given test Id. File size can't be more than 50 MB.\nExisting file with same name for the given test will be overwritten. File\nshould be provided in the request body as application/octet-stream.", + "description": "Upload input file for a given test Id. File size can't be more than 50 MB.\nExisting file with same name for the given test will be overwritten. File\nshould be provided in the request body as application/octet-stream.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Unique name for test file with file extension like : App.jmx", + "schema": { + "type": "string" + } + }, + { + "name": "fileType", + "in": "query", + "required": false, + "description": "File type", + "schema": { + "$ref": "#/components/schemas/FileType" + } + } + ], + "responses": { + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The file content as application/octet-stream.", + "required": true, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getTestFile", + "summary": "Get all the files that are associated with a test.", + "description": "Get all the files that are associated with a test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "delete": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_deleteTestFile", + "summary": "Delete file by the file name for a test", + "description": "Delete file by the file name for a test", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/server-metrics-config": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateServerMetricsConfig", + "summary": "Configure server metrics for a test", + "description": "Configure server metrics for a test", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Server metric configuration model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfigUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getServerMetricsConfig", + "summary": "List server metrics configuration for the given test.", + "description": "List server metrics configuration for the given test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + } + }, + "security": [ + { + "Oauth2": [ + "https://cnt-prod.loadtesting.azure.com/.default" + ] + } + ], + "components": { + "parameters": { + "Azure.Core.Foundations.ApiVersionParameter": { + "name": "api-version", + "in": "query", + "required": true, + "description": "The API version to use for this operation.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "ListTestQueryParams.lastModifiedEndTime": { + "name": "lastModifiedEndTime", + "in": "query", + "required": false, + "description": "End DateTime(RFC 3339 literal format) of the last updated time range to filter tests.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestQueryParams.lastModifiedStartTime": { + "name": "lastModifiedStartTime", + "in": "query", + "required": false, + "description": "Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestQueryParams.maxpagesize": { + "name": "maxpagesize", + "in": "query", + "required": false, + "description": "Number of results in response.", + "schema": { + "type": "integer", + "format": "int32", + "default": 50 + } + }, + "ListTestQueryParams.orderby": { + "name": "orderby", + "in": "query", + "required": false, + "description": "Sort on the supported fields in (field asc/desc) format. eg:\nlastModifiedDateTime asc. Supported fields - lastModifiedDateTime", + "schema": { + "type": "string" + } + }, + "ListTestQueryParams.search": { + "name": "search", + "in": "query", + "required": false, + "description": "Prefix based, case sensitive search on searchable fields - displayName,\ncreatedBy. For example, to search for a test, with display name is Login Test,\nthe search parameter can be Login.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.executionFrom": { + "name": "executionFrom", + "in": "query", + "required": false, + "description": "Start DateTime(RFC 3339 literal format) of test-run execution time filter range.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestRunQueryParams.executionTo": { + "name": "executionTo", + "in": "query", + "required": false, + "description": "End DateTime(RFC 3339 literal format) of test-run execution time filter range.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestRunQueryParams.maxpagesize": { + "name": "maxpagesize", + "in": "query", + "required": false, + "description": "Number of results in response.", + "schema": { + "type": "integer", + "format": "int32", + "default": 50 + } + }, + "ListTestRunQueryParams.orderby": { + "name": "orderby", + "in": "query", + "required": false, + "description": "Sort on the supported fields in (field asc/desc) format. eg: executedDateTime\nasc. Supported fields - executedDateTime", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.search": { + "name": "search", + "in": "query", + "required": false, + "description": "Prefix based, case sensitive search on searchable fields - description,\nexecutedUser. For example, to search for a test run, with description 500 VUs,\nthe search parameter can be 500.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.status": { + "name": "status", + "in": "query", + "required": false, + "description": "Comma separated list of test run status.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.testId": { + "name": "testId", + "in": "query", + "required": false, + "description": "Unique name of an existing load test.", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.interval": { + "name": "interval", + "in": "query", + "required": false, + "description": "The interval (i.e. timegrain) of the query.", + "schema": { + "$ref": "#/components/schemas/TimeGrain", + "default": "PT1M" + } + }, + "MetricDimensionsRequest.metricNamespace": { + "name": "metricNamespace", + "in": "query", + "required": true, + "description": "Metric namespace to query metric definitions for.", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.metricname": { + "name": "metricname", + "in": "query", + "required": true, + "description": "Metric name", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.timespan": { + "name": "timespan", + "in": "query", + "required": true, + "description": "The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.", + "schema": { + "type": "string" + } + }, + "OldTestRunIdQueryParam": { + "name": "oldTestRunId", + "in": "query", + "required": false, + "description": "Existing test run identifier that should be rerun, if this is provided, the\ntest will run with the JMX file, configuration and app components from the\nexisting test run. You can override the configuration values for new test run\nin the request body.", + "schema": { + "type": "string" + } + } + }, + "schemas": { + "APIVersions": { + "type": "string", + "enum": [ + "2022-11-01", + "2023-04-01-preview" + ], + "description": "Azure Load Testing API versions." + }, + "AggregationType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "Average", + "Count", + "None", + "Total", + "Percentile90", + "Percentile95", + "Percentile99" + ] + } + ], + "description": "Aggregation type." + }, + "AppComponent": { + "type": "object", + "required": [ + "resourceId", + "resourceName", + "resourceType" + ], + "properties": { + "resourceId": { + "type": "string", + "description": "fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}", + "readOnly": true + }, + "resourceName": { + "type": "string", + "description": "Azure resource name, required while creating the app component." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type, required while creating the app component." + }, + "displayName": { + "type": "string", + "description": "Azure resource display name" + }, + "resourceGroup": { + "type": "string", + "description": "Resource group name of the Azure resource", + "readOnly": true + }, + "subscriptionId": { + "type": "string", + "description": "Subscription Id of the Azure resource", + "readOnly": true + }, + "kind": { + "type": "string", + "description": "Kind of Azure resource type" + } + }, + "description": "An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource)" + }, + "AppComponentUpdate": { + "type": "object", + "properties": { + "resourceName": { + "type": "string", + "description": "Azure resource name, required while creating the app component." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type, required while creating the app component." + }, + "displayName": { + "type": "string", + "description": "Azure resource display name" + }, + "kind": { + "type": "string", + "description": "Kind of Azure resource type" + } + }, + "description": "An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource)" + }, + "Azure.Core.Foundations.Error": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "One of a server-defined set of error codes." + }, + "message": { + "type": "string", + "description": "A human-readable representation of the error." + }, + "target": { + "type": "string", + "description": "The target of the error." + }, + "details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Azure.Core.Foundations.Error" + }, + "description": "An array of details about specific errors that led to this reported error." + }, + "innererror": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.InnerError" + } + ], + "description": "An object containing more specific information than the current object about the error." + } + }, + "description": "The error object." + }, + "Azure.Core.Foundations.ErrorResponse": { + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.Error" + } + ], + "description": "The error object." + } + }, + "description": "A response containing error details." + }, + "Azure.Core.Foundations.InnerError": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "One of a server-defined set of error codes." + }, + "innererror": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.InnerError" + } + ], + "description": "Inner error." + } + }, + "description": "An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses." + }, + "CertificateMetadata": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The value of the certificate for respective type" + }, + "type": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateType" + } + ], + "description": "Type of certificate" + }, + "name": { + "type": "string", + "description": "Name of the certificate." + } + }, + "description": "Certificates metadata" + }, + "CertificateType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "AKV_CERT_URI" + ] + } + ], + "description": "Types of certificates supported." + }, + "DimensionFilter": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The dimension name" + }, + "values": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dimension values. Maximum values can be 20." + } + }, + "description": "Dimension name and values to filter" + }, + "DimensionValue": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the dimension." + }, + "value": { + "type": "string", + "description": "The value of the dimension." + } + }, + "description": "Represents a metric dimension value." + }, + "DimensionValueList": { + "type": "object", + "properties": { + "value": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dimension value" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "Link for the next set of values in case of paginated results, if applicable." + } + }, + "description": "Metrics dimension values." + }, + "ErrorDetails": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Error details in case test run was not successfully run.", + "readOnly": true + } + }, + "description": "Error details if there is any failure in load test run" + }, + "FileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "File info" + }, + "FileStatus": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "NOT_VALIDATED", + "VALIDATION_SUCCESS", + "VALIDATION_FAILURE", + "VALIDATION_INITIATED", + "VALIDATION_NOT_REQUIRED" + ] + } + ], + "description": "File status." + }, + "FileType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "JMX_FILE", + "USER_PROPERTIES", + "ADDITIONAL_ARTIFACTS" + ] + } + ], + "description": "Types of file supported." + }, + "LoadTestConfiguration": { + "type": "object", + "properties": { + "engineInstances": { + "type": "integer", + "format": "int32", + "description": "The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test." + }, + "splitAllCSVs": { + "type": "boolean", + "description": "If false, Azure Load Testing copies and processes your input files unmodified\nacross all test engine instances. If true, Azure Load Testing splits the CSV\ninput data evenly across all engine instances. If you provide multiple CSV\nfiles, each file will be split evenly.", + "default": false + }, + "quickStartTest": { + "type": "boolean", + "description": "If true, optionalLoadTestConfig is required and JMX script for the load test is\nnot required to upload.", + "default": false + }, + "optionalLoadTestConfig": { + "allOf": [ + { + "$ref": "#/components/schemas/OptionalLoadTestConfig" + } + ], + "description": "Configuration for quick load test" + } + }, + "description": "Configurations for the load test." + }, + "MetricAvailability": { + "type": "object", + "properties": { + "timeGrain": { + "allOf": [ + { + "$ref": "#/components/schemas/TimeGrain" + } + ], + "description": "The time grain specifies the aggregation interval for the metric. Expressed as\na duration 'PT1M', 'PT1H', etc." + } + }, + "description": "Metric availability specifies the time grain (aggregation interval or frequency)" + }, + "MetricDefinition": { + "type": "object", + "properties": { + "dimensions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NameAndDesc" + }, + "description": "List of dimensions" + }, + "description": { + "type": "string", + "description": "The metric description" + }, + "name": { + "type": "string", + "description": "The metric name" + }, + "namespace": { + "type": "string", + "description": "The namespace the metric belongs to." + }, + "primaryAggregationType": { + "allOf": [ + { + "$ref": "#/components/schemas/AggregationType" + } + ], + "description": "The primary aggregation type value defining how to use the values for display." + }, + "supportedAggregationTypes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The collection of what all aggregation types are supported." + }, + "unit": { + "allOf": [ + { + "$ref": "#/components/schemas/MetricUnit" + } + ], + "description": "The unit of the metric." + }, + "metricAvailabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricAvailability" + }, + "description": "Metric availability specifies the time grain (aggregation interval or\nfrequency)." + } + }, + "description": "Metric definition" + }, + "MetricDefinitionCollection": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricDefinition" + }, + "description": "the values for the metric definitions." + } + }, + "description": "Represents collection of metric definitions." + }, + "MetricNamespace": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "The namespace description." + }, + "name": { + "type": "string", + "description": "The metric namespace name." + } + }, + "description": "Metric namespace class specifies the metadata for a metric namespace." + }, + "MetricNamespaceCollection": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricNamespace" + }, + "description": "The values for the metric namespaces." + } + }, + "description": "Represents collection of metric namespaces." + }, + "MetricRequestPayload": { + "type": "object", + "properties": { + "filters": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DimensionFilter" + }, + "description": "Get metrics for specific dimension values. Example: Metric contains dimension\nlike SamplerName, Error. To retrieve all the time series data where SamplerName\nis equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be\n{\"SamplerName\", [\"HTTPRequest1\", \"HTTPRequest2\"}" + } + }, + "description": "Filters to fetch the set of metric." + }, + "MetricUnit": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "NotSpecified", + "Percent", + "Count", + "Seconds", + "Milliseconds", + "Bytes", + "BytesPerSecond", + "CountPerSecond" + ] + } + ], + "description": "Metric unit." + }, + "MetricValue": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "The timestamp for the metric value in RFC 3339 format." + }, + "value": { + "type": "number", + "format": "double", + "description": "The metric value." + } + }, + "description": "Represents a metric value." + }, + "Metrics": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TimeSeriesElement" + }, + "description": "The TimeSeriesElement items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "The response to a metrics query." + }, + "NameAndDesc": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "The description" + }, + "name": { + "type": "string", + "description": "The name" + } + }, + "description": "The name and description" + }, + "Oauth2": { + "type": "object", + "required": [ + "type", + "flows", + "defaultScopes" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ], + "description": "OAuth2 authentication" + }, + "flows": { + "type": "array", + "items": {}, + "description": "Supported OAuth2 flows" + }, + "defaultScopes": { + "type": "array", + "items": {}, + "description": "Oauth2 scopes of every flow. Overridden by scope definitions in specific flows" + } + }, + "description": "OAuth 2.0 Flow with Microsoft Entra ID." + }, + "OptionalLoadTestConfig": { + "type": "object", + "properties": { + "endpointUrl": { + "type": "string", + "description": "Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login" + }, + "virtualUsers": { + "type": "integer", + "format": "int32", + "description": "No of concurrent virtual users." + }, + "rampUpTime": { + "type": "integer", + "format": "int32", + "description": "Ramp up time in seconds." + }, + "duration": { + "type": "integer", + "format": "int32", + "description": "Test run duration in seconds." + } + }, + "description": "Configuration for quick load test" + }, + "PFAction": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "continue", + "stop" + ] + } + ], + "description": "Action to take on failure of pass/fail criteria." + }, + "PFAgFunc": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "count", + "percentage", + "avg", + "p50", + "p90", + "p95", + "p99", + "min", + "max" + ] + } + ], + "description": "Aggregation functions for pass/fail criteria." + }, + "PFMetrics": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "response_time_ms", + "latency", + "error", + "requests", + "requests_per_sec" + ] + } + ], + "description": "Metrics for pass/fail criteria." + }, + "PFTestResult": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "PASSED", + "NOT_APPLICABLE", + "FAILED" + ] + } + ], + "description": "Test result based on pass/fail criteria." + }, + "PagedTest": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Test" + }, + "description": "The Test items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of Test items" + }, + "PagedTestFileInfo": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestFileInfo" + }, + "description": "The TestFileInfo items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of TestFileInfo items" + }, + "PagedTestRun": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestRun" + }, + "description": "The TestRun items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of TestRun items" + }, + "PassFailCriteria": { + "type": "object", + "properties": { + "passFailMetrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PassFailMetric" + }, + "description": "Map of id and pass fail metrics { id : pass fail metrics }." + } + }, + "description": "Pass fail criteria for a test." + }, + "PassFailMetric": { + "type": "object", + "properties": { + "clientMetric": { + "allOf": [ + { + "$ref": "#/components/schemas/PFMetrics" + } + ], + "description": "The client metric on which the criteria should be applied." + }, + "aggregate": { + "allOf": [ + { + "$ref": "#/components/schemas/PFAgFunc" + } + ], + "description": "The aggregation function to be applied on the client metric. Allowed functions\n- ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’,\n‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec,\n‘count’ - for requests" + }, + "condition": { + "type": "string", + "description": "The comparison operator. Supported types ‘>’, ‘<’ " + }, + "requestName": { + "type": "string", + "description": "Request name for which the Pass fail criteria has to be applied " + }, + "value": { + "type": "number", + "format": "double", + "description": "The value to compare with the client metric. Allowed values - ‘error : [0.0 ,\n100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms." + }, + "action": { + "allOf": [ + { + "$ref": "#/components/schemas/PFAction" + } + ], + "description": "Action taken after the threshold is met. Default is ‘continue’.", + "default": "continue" + } + }, + "description": "Pass fail metric" + }, + "ResourceMetric": { + "type": "object", + "required": [ + "resourceId", + "metricNamespace", + "name", + "aggregation", + "resourceType" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique name for metric.", + "readOnly": true + }, + "resourceId": { + "type": "string", + "description": "Azure resource id." + }, + "metricNamespace": { + "type": "string", + "description": "Metric name space." + }, + "displayDescription": { + "type": "string", + "description": "Metric description." + }, + "name": { + "type": "string", + "description": "The invariant value of metric name" + }, + "aggregation": { + "type": "string", + "description": "Metric aggregation." + }, + "unit": { + "type": "string", + "description": "Metric unit." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type." + } + }, + "description": "Associated metric definition for particular metrics of the azure resource (\nRefer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition)." + }, + "ResourceMetricUpdate": { + "type": "object", + "properties": { + "resourceId": { + "type": "string", + "description": "Azure resource id." + }, + "metricNamespace": { + "type": "string", + "description": "Metric name space." + }, + "displayDescription": { + "type": "string", + "description": "Metric description." + }, + "name": { + "type": "string", + "description": "The invariant value of metric name" + }, + "aggregation": { + "type": "string", + "description": "Metric aggregation." + }, + "unit": { + "type": "string", + "description": "Metric unit." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type." + } + }, + "description": "Associated metric definition for particular metrics of the azure resource (\nRefer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition)." + }, + "Secret": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The value of the secret for the respective type" + }, + "type": { + "allOf": [ + { + "$ref": "#/components/schemas/SecretType" + } + ], + "description": "Type of secret" + } + }, + "description": "Secret" + }, + "SecretType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "AKV_SECRET_URI", + "SECRET_VALUE" + ] + } + ], + "description": "Types of secrets supported." + }, + "Status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "ACCEPTED", + "NOTSTARTED", + "PROVISIONING", + "PROVISIONED", + "CONFIGURING", + "CONFIGURED", + "EXECUTING", + "EXECUTED", + "DEPROVISIONING", + "DEPROVISIONED", + "DONE", + "CANCELLING", + "CANCELLED", + "FAILED", + "VALIDATION_SUCCESS", + "VALIDATION_FAILURE" + ] + } + ], + "description": "Test run status." + }, + "SystemMetaData": { + "type": "object", + "properties": { + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "System metadata." + }, + "Test": { + "type": "object", + "required": [ + "testId" + ], + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata." + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "inputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestInputArtifacts" + } + ], + "description": "The input artifacts for the test.", + "readOnly": true + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test description." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a test." + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run." + }, + "keyvaultReferenceIdentityType": { + "type": "string", + "description": "Type of the managed identity referencing the Key vault." + }, + "keyvaultReferenceIdentityId": { + "type": "string", + "description": "Resource Id of the managed identity referencing the Key vault." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Load test model." + }, + "TestAppComponents": { + "type": "object", + "required": [ + "components" + ], + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponent" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + }, + "testId": { + "type": "string", + "description": "Test identifier", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test app components" + }, + "TestAppComponentsUpdate": { + "type": "object", + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponentUpdate" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + } + }, + "description": "Test app components" + }, + "TestCreateOrUpdate": { + "type": "object", + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata." + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test description." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a test." + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run." + }, + "keyvaultReferenceIdentityType": { + "type": "string", + "description": "Type of the managed identity referencing the Key vault." + }, + "keyvaultReferenceIdentityId": { + "type": "string", + "description": "Resource Id of the managed identity referencing the Key vault." + } + }, + "description": "Load test model." + }, + "TestFileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "Test file info." + }, + "TestIdPathParameter": { + "type": "object", + "required": [ + "testId" + ], + "properties": { + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + } + }, + "description": "Test Id path parameter." + }, + "TestInputArtifacts": { + "type": "object", + "properties": { + "configFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "testScriptFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "userPropFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "inputArtifactsZipFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "additionalFileInfo": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestFileInfo" + }, + "description": "Additional supported files for the test run", + "readOnly": true + } + }, + "description": "The input artifacts for the test." + }, + "TestRun": { + "type": "object", + "required": [ + "testRunId" + ], + "properties": { + "testRunId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + }, + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata" + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "errorDetails": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ErrorDetails" + }, + "description": "Error details if there is any failure in load test run", + "readOnly": true + }, + "testRunStatistics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/TestRunStatistics" + }, + "description": "Test run statistics.", + "readOnly": true + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "testArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunArtifacts" + } + ], + "description": "Collection of test run artifacts", + "readOnly": true + }, + "testResult": { + "allOf": [ + { + "$ref": "#/components/schemas/PFTestResult" + } + ], + "description": "Test result for pass/Fail criteria used during the test run.", + "readOnly": true + }, + "virtualUsers": { + "type": "integer", + "format": "int32", + "description": "Number of virtual users, for which test has been run.", + "readOnly": true + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a testRun." + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Associated test Id." + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test run description." + }, + "status": { + "allOf": [ + { + "$ref": "#/components/schemas/Status" + } + ], + "description": "The test run status.", + "readOnly": true + }, + "startDateTime": { + "type": "string", + "format": "date-time", + "description": "The test run start DateTime(RFC 3339 literal format).", + "readOnly": true + }, + "endDateTime": { + "type": "string", + "format": "date-time", + "description": "The test run end DateTime(RFC 3339 literal format).", + "readOnly": true + }, + "executedDateTime": { + "type": "string", + "format": "date-time", + "description": "Test run initiated time.", + "readOnly": true + }, + "portalUrl": { + "type": "string", + "description": "Portal url.", + "readOnly": true + }, + "duration": { + "type": "integer", + "format": "int64", + "description": "Test run duration in milliseconds.", + "readOnly": true + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run.", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Load test run model" + }, + "TestRunAppComponents": { + "type": "object", + "required": [ + "components" + ], + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponent" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + }, + "testRunId": { + "type": "string", + "description": "Test run identifier", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test run app component" + }, + "TestRunAppComponentsUpdate": { + "type": "object", + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponentUpdate" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + } + }, + "description": "Test run app component" + }, + "TestRunArtifacts": { + "type": "object", + "properties": { + "inputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunInputArtifacts" + } + ], + "description": "The input artifacts for the test run.", + "readOnly": true + }, + "outputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunOutputArtifacts" + } + ], + "description": "The output artifacts for the test run." + } + }, + "description": "Collection of test run artifacts" + }, + "TestRunCreateOrUpdate": { + "type": "object", + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata" + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a testRun." + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Associated test Id." + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test run description." + } + }, + "description": "Load test run model" + }, + "TestRunFileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "Test run file info." + }, + "TestRunIdPathParameter": { + "type": "object", + "required": [ + "testRunId" + ], + "properties": { + "testRunId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + } + }, + "description": "Test run Id path parameter." + }, + "TestRunInputArtifacts": { + "type": "object", + "properties": { + "configFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "testScriptFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "userPropFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "inputArtifactsZipFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "additionalFileInfo": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestRunFileInfo" + }, + "description": "Additional supported files for the test run", + "readOnly": true + } + }, + "description": "The input artifacts for the test run." + }, + "TestRunOutputArtifacts": { + "type": "object", + "properties": { + "resultFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "logsFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + } + }, + "description": "The output artifacts for the test run." + }, + "TestRunServerMetricConfig": { + "type": "object", + "properties": { + "testRunId": { + "type": "string", + "description": "Test run identifier", + "readOnly": true + }, + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetric" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test run server metrics configuration" + }, + "TestRunStatistics": { + "type": "object", + "properties": { + "transaction": { + "type": "string", + "description": "Transaction name.", + "readOnly": true + }, + "sampleCount": { + "type": "number", + "format": "double", + "description": "Sampler count.", + "readOnly": true + }, + "errorCount": { + "type": "number", + "format": "double", + "description": "Error count.", + "readOnly": true + }, + "errorPct": { + "type": "number", + "format": "double", + "description": "Error percentage.", + "readOnly": true + }, + "meanResTime": { + "type": "number", + "format": "double", + "description": "Mean response time.", + "readOnly": true + }, + "medianResTime": { + "type": "number", + "format": "double", + "description": "Median response time.", + "readOnly": true + }, + "maxResTime": { + "type": "number", + "format": "double", + "description": "Max response time.", + "readOnly": true + }, + "minResTime": { + "type": "number", + "format": "double", + "description": "Minimum response time.", + "readOnly": true + }, + "pct1ResTime": { + "type": "number", + "format": "double", + "description": "90 percentile response time.", + "readOnly": true + }, + "pct2ResTime": { + "type": "number", + "format": "double", + "description": "95 percentile response time.", + "readOnly": true + }, + "pct3ResTime": { + "type": "number", + "format": "double", + "description": "99 percentile response time.", + "readOnly": true + }, + "throughput": { + "type": "number", + "format": "double", + "description": "Throughput.", + "readOnly": true + }, + "receivedKBytesPerSec": { + "type": "number", + "format": "double", + "description": "Received network bytes.", + "readOnly": true + }, + "sentKBytesPerSec": { + "type": "number", + "format": "double", + "description": "Send network bytes.", + "readOnly": true + } + }, + "description": "Test run statistics." + }, + "TestServerMetricConfig": { + "type": "object", + "required": [ + "metrics" + ], + "properties": { + "testId": { + "type": "string", + "description": "Test identifier", + "readOnly": true + }, + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetric" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test server metrics configuration" + }, + "TestServerMetricConfigUpdate": { + "type": "object", + "properties": { + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetricUpdate" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + } + }, + "description": "Test server metrics configuration" + }, + "TimeGrain": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "PT5S", + "PT10S", + "PT1M", + "PT5M", + "PT1H" + ] + } + ], + "description": "Time Grain" + }, + "TimeSeriesElement": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricValue" + }, + "description": "An array of data points representing the metric values." + }, + "dimensionValues": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DimensionValue" + }, + "description": "The dimension values " + } + }, + "description": "The time series returned when a data query is performed." + } + }, + "securitySchemes": { + "Oauth2": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", + "scopes": { + "https://cnt-prod.loadtesting.azure.com/.default": "" + } + } + }, + "description": "OAuth 2.0 Flow with Microsoft Entra ID." + } + } + }, + "servers": [ + { + "url": "https://{endpoint}", + "description": "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", + "variables": { + "endpoint": { + "default": "" + } + } + } + ] +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2023-04-01-preview.json b/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2023-04-01-preview.json new file mode 100644 index 0000000000..b7c5ab6a41 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/openapi/openapi.2023-04-01-preview.json @@ -0,0 +1,4108 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "Azure Load Testing", + "description": "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", + "version": "2023-04-01-preview" + }, + "tags": [ + { + "name": "Test" + }, + { + "name": "TestRun" + } + ], + "paths": { + "/test-runs": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listTestRuns", + "summary": "Get all test runs for the given filters.", + "description": "Get all test runs for the given filters.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.orderby" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.search" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.testId" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.executionFrom" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.executionTo" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.status" + }, + { + "$ref": "#/components/parameters/ListTestRunQueryParams.maxpagesize" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getTestRun", + "summary": "Get test run details by test run Id.", + "description": "Get test run details by test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateTestRun", + "summary": "Create and start a new test run with the given test run Id.", + "description": "Create and start a new test run with the given test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "$ref": "#/components/parameters/OldTestRunIdQueryParam" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The resource instance.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunCreateOrUpdate" + } + } + } + } + }, + "delete": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_deleteTestRun", + "summary": "Delete an existing load test run.", + "description": "Delete an existing load test run by providing the testRunId.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/app-components": { + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateAppComponents", + "summary": "Add an app component to a test run.", + "description": "Add an app component to a test run by providing the resource Id, name and type.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique Id for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "App Component model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponentsUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getAppComponents", + "summary": "Get associated app component (collection of azure resources) for the given test\nrun.", + "description": "Get associated app component (collection of azure resources) for the given test\nrun.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/files/{fileName}": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getTestRunFile", + "summary": "Get test run file by file name.", + "description": "Get test run file by file name.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-definitions": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricDefinitions", + "summary": "List the metric definitions for a load test run.", + "description": "List the metric definitions for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "metricNamespace", + "in": "query", + "required": true, + "description": "Metric namespace to query metric definitions for.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricDefinitionCollection" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-dimensions/{name}/values": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricDimensionValues", + "summary": "List the dimension values for the given metric dimension name.", + "description": "List the dimension values for the given metric dimension name.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "name", + "in": "path", + "required": true, + "description": "Dimension name", + "schema": { + "type": "string" + } + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricname" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.interval" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricNamespace" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.timespan" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DimensionValueList" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metric-namespaces": { + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetricNamespaces", + "summary": "List the metric namespaces for a load test run.", + "description": "List the metric namespaces for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricNamespaceCollection" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}/metrics": { + "post": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_listMetrics", + "summary": "List the metric values for a load test run.", + "description": "List the metric values for a load test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "aggregation", + "in": "query", + "required": false, + "description": "The aggregation", + "schema": { + "type": "string" + } + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricname" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.interval" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.metricNamespace" + }, + { + "$ref": "#/components/parameters/MetricDimensionsRequest.timespan" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Metrics" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Metric dimension filter ", + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MetricRequestPayload" + } + } + } + } + } + }, + "/test-runs/{testRunId}/server-metrics-config": { + "patch": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_createOrUpdateServerMetricsConfig", + "summary": "Configure server metrics for a test run", + "description": "Configure server metrics for a test run", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique Id for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Server metric configuration model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + } + }, + "get": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_getServerMetricsConfig", + "summary": "Get associated server metrics configuration for the given test run.", + "description": "Get associated server metrics configuration for the given test run.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique name for the load test run, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRunServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/test-runs/{testRunId}:stop": { + "post": { + "tags": [ + "TestRun" + ], + "operationId": "LoadTestRun_StopTestRun", + "summary": "Stop test run by test run Id.", + "description": "Stop test run by test run Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testRunId", + "in": "path", + "required": true, + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestRun" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests": { + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_listTests", + "summary": "Get all load tests by the fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}.", + "description": "Get all load tests by the fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.orderby" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.search" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.lastModifiedStartTime" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.lastModifiedEndTime" + }, + { + "$ref": "#/components/parameters/ListTestQueryParams.maxpagesize" + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTest" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateTest", + "summary": "Create a new test or update an existing test by providing the test Id.", + "description": "Create a new test or update an existing test by providing the test Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The resource instance.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestCreateOrUpdate" + } + } + } + } + }, + "delete": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_deleteTest", + "summary": "Delete a test by its test Id.", + "description": "Delete a test by its test Id.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getTest", + "summary": "Get load test details by test Id", + "description": "Get load test details by test Id", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Test" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/app-components": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateAppComponents", + "summary": "Add an app component to a test.", + "description": "Add an app component to a test by providing the resource Id, name and type.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "App Component model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponentsUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getAppComponents", + "summary": "Get associated app component (collection of azure resources) for the given test.", + "description": "Get associated app component (collection of azure resources) for the given test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestAppComponents" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/files": { + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_listTestFiles", + "summary": "Get all test files.", + "description": "Get all test files.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PagedTestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/files/{fileName}": { + "put": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_uploadTestFile", + "summary": "Upload input file for a given test Id. File size can't be more than 50 MB.\nExisting file with same name for the given test will be overwritten. File\nshould be provided in the request body as application/octet-stream.", + "description": "Upload input file for a given test Id. File size can't be more than 50 MB.\nExisting file with same name for the given test will be overwritten. File\nshould be provided in the request body as application/octet-stream.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Unique name for test file with file extension like : App.jmx", + "schema": { + "type": "string" + } + }, + { + "name": "fileType", + "in": "query", + "required": false, + "description": "File type", + "schema": { + "$ref": "#/components/schemas/FileType" + } + } + ], + "responses": { + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "The file content as application/octet-stream.", + "required": true, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getTestFile", + "summary": "Get all the files that are associated with a test.", + "description": "Get all the files that are associated with a test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestFileInfo" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + }, + "delete": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_deleteTestFile", + "summary": "Delete file by the file name for a test", + "description": "Delete file by the file name for a test", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + }, + { + "name": "fileName", + "in": "path", + "required": true, + "description": "Name of the file.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "There is no content to send for this request, but the headers may be useful. " + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + }, + "/tests/{testId}/server-metrics-config": { + "patch": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_createOrUpdateServerMetricsConfig", + "summary": "Configure server metrics for a test", + "description": "Configure server metrics for a test", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "201": { + "description": "The request has succeeded and a new resource has been created as a result.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + }, + "requestBody": { + "description": "Server metric configuration model.", + "required": true, + "content": { + "application/merge-patch+json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfigUpdate" + } + } + } + } + }, + "get": { + "tags": [ + "Test" + ], + "operationId": "LoadTestAdministration_getServerMetricsConfig", + "summary": "List server metrics configuration for the given test.", + "description": "List server metrics configuration for the given test.", + "parameters": [ + { + "$ref": "#/components/parameters/Azure.Core.Foundations.ApiVersionParameter" + }, + { + "name": "testId", + "in": "path", + "required": true, + "description": "Unique name for the load test, must contain only lower-case alphabetic,\nnumeric, underscore or hyphen characters.", + "schema": { + "type": "string", + "pattern": "^[a-z0-9_-]*$", + "minLength": 2, + "maxLength": 50 + } + } + ], + "responses": { + "200": { + "description": "The request has succeeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestServerMetricConfig" + } + } + } + }, + "default": { + "description": "An unexpected error response.", + "headers": { + "x-ms-error-code": { + "required": false, + "description": "String error code indicating what went wrong.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Azure.Core.Foundations.ErrorResponse" + } + } + } + } + } + } + } + }, + "security": [ + { + "Oauth2": [ + "https://cnt-prod.loadtesting.azure.com/.default" + ] + } + ], + "components": { + "parameters": { + "Azure.Core.Foundations.ApiVersionParameter": { + "name": "api-version", + "in": "query", + "required": true, + "description": "The API version to use for this operation.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "ListTestQueryParams.lastModifiedEndTime": { + "name": "lastModifiedEndTime", + "in": "query", + "required": false, + "description": "End DateTime(RFC 3339 literal format) of the last updated time range to filter tests.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestQueryParams.lastModifiedStartTime": { + "name": "lastModifiedStartTime", + "in": "query", + "required": false, + "description": "Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestQueryParams.maxpagesize": { + "name": "maxpagesize", + "in": "query", + "required": false, + "description": "Number of results in response.", + "schema": { + "type": "integer", + "format": "int32", + "default": 50 + } + }, + "ListTestQueryParams.orderby": { + "name": "orderby", + "in": "query", + "required": false, + "description": "Sort on the supported fields in (field asc/desc) format. eg:\nlastModifiedDateTime asc. Supported fields - lastModifiedDateTime", + "schema": { + "type": "string" + } + }, + "ListTestQueryParams.search": { + "name": "search", + "in": "query", + "required": false, + "description": "Prefix based, case sensitive search on searchable fields - displayName,\ncreatedBy. For example, to search for a test, with display name is Login Test,\nthe search parameter can be Login.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.executionFrom": { + "name": "executionFrom", + "in": "query", + "required": false, + "description": "Start DateTime(RFC 3339 literal format) of test-run execution time filter range.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestRunQueryParams.executionTo": { + "name": "executionTo", + "in": "query", + "required": false, + "description": "End DateTime(RFC 3339 literal format) of test-run execution time filter range.", + "schema": { + "type": "string", + "format": "date-time" + } + }, + "ListTestRunQueryParams.maxpagesize": { + "name": "maxpagesize", + "in": "query", + "required": false, + "description": "Number of results in response.", + "schema": { + "type": "integer", + "format": "int32", + "default": 50 + } + }, + "ListTestRunQueryParams.orderby": { + "name": "orderby", + "in": "query", + "required": false, + "description": "Sort on the supported fields in (field asc/desc) format. eg: executedDateTime\nasc. Supported fields - executedDateTime", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.search": { + "name": "search", + "in": "query", + "required": false, + "description": "Prefix based, case sensitive search on searchable fields - description,\nexecutedUser. For example, to search for a test run, with description 500 VUs,\nthe search parameter can be 500.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.status": { + "name": "status", + "in": "query", + "required": false, + "description": "Comma separated list of test run status.", + "schema": { + "type": "string" + } + }, + "ListTestRunQueryParams.testId": { + "name": "testId", + "in": "query", + "required": false, + "description": "Unique name of an existing load test.", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.interval": { + "name": "interval", + "in": "query", + "required": false, + "description": "The interval (i.e. timegrain) of the query.", + "schema": { + "$ref": "#/components/schemas/TimeGrain", + "default": "PT1M" + } + }, + "MetricDimensionsRequest.metricNamespace": { + "name": "metricNamespace", + "in": "query", + "required": true, + "description": "Metric namespace to query metric definitions for.", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.metricname": { + "name": "metricname", + "in": "query", + "required": true, + "description": "Metric name", + "schema": { + "type": "string" + } + }, + "MetricDimensionsRequest.timespan": { + "name": "timespan", + "in": "query", + "required": true, + "description": "The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'.", + "schema": { + "type": "string" + } + }, + "OldTestRunIdQueryParam": { + "name": "oldTestRunId", + "in": "query", + "required": false, + "description": "Existing test run identifier that should be rerun, if this is provided, the\ntest will run with the JMX file, configuration and app components from the\nexisting test run. You can override the configuration values for new test run\nin the request body.", + "schema": { + "type": "string" + } + } + }, + "schemas": { + "APIVersions": { + "type": "string", + "enum": [ + "2022-11-01", + "2023-04-01-preview" + ], + "description": "Azure Load Testing API versions." + }, + "AggregationType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "Average", + "Count", + "None", + "Total", + "Percentile90", + "Percentile95", + "Percentile99" + ] + } + ], + "description": "Aggregation type." + }, + "AppComponent": { + "type": "object", + "required": [ + "resourceId", + "resourceName", + "resourceType" + ], + "properties": { + "resourceId": { + "type": "string", + "description": "fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}", + "readOnly": true + }, + "resourceName": { + "type": "string", + "description": "Azure resource name, required while creating the app component." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type, required while creating the app component." + }, + "displayName": { + "type": "string", + "description": "Azure resource display name" + }, + "resourceGroup": { + "type": "string", + "description": "Resource group name of the Azure resource", + "readOnly": true + }, + "subscriptionId": { + "type": "string", + "description": "Subscription Id of the Azure resource", + "readOnly": true + }, + "kind": { + "type": "string", + "description": "Kind of Azure resource type" + } + }, + "description": "An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource)" + }, + "AppComponentUpdate": { + "type": "object", + "properties": { + "resourceName": { + "type": "string", + "description": "Azure resource name, required while creating the app component." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type, required while creating the app component." + }, + "displayName": { + "type": "string", + "description": "Azure resource display name" + }, + "kind": { + "type": "string", + "description": "Kind of Azure resource type" + } + }, + "description": "An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource)" + }, + "ArtifactsContainerInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "This is a SAS URI to an Azure Storage Container that contains the test run artifacts." + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the container (RFC 3339 literal format)" + } + }, + "description": "Artifacts container info." + }, + "AutoStopCriteria": { + "type": "object", + "properties": { + "autoStopDisabled": { + "type": "boolean", + "description": "Whether auto-stop should be disabled. The default value is false.", + "default": false + }, + "errorRate": { + "type": "number", + "format": "float", + "description": "Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0", + "default": 90 + }, + "errorRateTimeWindowInSeconds": { + "type": "integer", + "format": "int32", + "description": "Time window during which the error percentage should be evaluated in seconds.", + "default": 60 + } + }, + "description": "Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window." + }, + "Azure.Core.Foundations.Error": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "string", + "description": "One of a server-defined set of error codes." + }, + "message": { + "type": "string", + "description": "A human-readable representation of the error." + }, + "target": { + "type": "string", + "description": "The target of the error." + }, + "details": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Azure.Core.Foundations.Error" + }, + "description": "An array of details about specific errors that led to this reported error." + }, + "innererror": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.InnerError" + } + ], + "description": "An object containing more specific information than the current object about the error." + } + }, + "description": "The error object." + }, + "Azure.Core.Foundations.ErrorResponse": { + "type": "object", + "required": [ + "error" + ], + "properties": { + "error": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.Error" + } + ], + "description": "The error object." + } + }, + "description": "A response containing error details." + }, + "Azure.Core.Foundations.InnerError": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "One of a server-defined set of error codes." + }, + "innererror": { + "allOf": [ + { + "$ref": "#/components/schemas/Azure.Core.Foundations.InnerError" + } + ], + "description": "Inner error." + } + }, + "description": "An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses." + }, + "CertificateMetadata": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The value of the certificate for respective type" + }, + "type": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateType" + } + ], + "description": "Type of certificate" + }, + "name": { + "type": "string", + "description": "Name of the certificate." + } + }, + "description": "Certificates metadata" + }, + "CertificateType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "AKV_CERT_URI" + ] + } + ], + "description": "Types of certificates supported." + }, + "DimensionFilter": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The dimension name" + }, + "values": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dimension values. Maximum values can be 20." + } + }, + "description": "Dimension name and values to filter" + }, + "DimensionValue": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The name of the dimension." + }, + "value": { + "type": "string", + "description": "The value of the dimension." + } + }, + "description": "Represents a metric dimension value." + }, + "DimensionValueList": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The dimension name", + "readOnly": true + }, + "value": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The dimension value" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "Link for the next set of values in case of paginated results, if applicable." + } + }, + "description": "Metrics dimension values." + }, + "ErrorDetails": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Error details in case test run was not successfully run.", + "readOnly": true + } + }, + "description": "Error details if there is any failure in load test run" + }, + "FileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "File info" + }, + "FileStatus": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "NOT_VALIDATED", + "VALIDATION_SUCCESS", + "VALIDATION_FAILURE", + "VALIDATION_INITIATED", + "VALIDATION_NOT_REQUIRED" + ] + } + ], + "description": "File status." + }, + "FileType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "JMX_FILE", + "USER_PROPERTIES", + "ADDITIONAL_ARTIFACTS", + "ZIPPED_ARTIFACTS", + "URL_TEST_CONFIG_JSON" + ] + } + ], + "description": "Types of file supported." + }, + "LoadTestConfiguration": { + "type": "object", + "properties": { + "engineInstances": { + "type": "integer", + "format": "int32", + "description": "The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test." + }, + "splitAllCSVs": { + "type": "boolean", + "description": "If false, Azure Load Testing copies and processes your input files unmodified\nacross all test engine instances. If true, Azure Load Testing splits the CSV\ninput data evenly across all engine instances. If you provide multiple CSV\nfiles, each file will be split evenly.", + "default": false + }, + "quickStartTest": { + "type": "boolean", + "description": "If true, optionalLoadTestConfig is required and JMX script for the load test is\nnot required to upload.", + "default": false + }, + "optionalLoadTestConfig": { + "allOf": [ + { + "$ref": "#/components/schemas/OptionalLoadTestConfig" + } + ], + "description": "Configuration for quick load test" + } + }, + "description": "Configurations for the load test." + }, + "MetricAvailability": { + "type": "object", + "properties": { + "timeGrain": { + "allOf": [ + { + "$ref": "#/components/schemas/TimeGrain" + } + ], + "description": "The time grain specifies the aggregation interval for the metric. Expressed as\na duration 'PT1M', 'PT1H', etc." + } + }, + "description": "Metric availability specifies the time grain (aggregation interval or frequency)" + }, + "MetricDefinition": { + "type": "object", + "properties": { + "dimensions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NameAndDesc" + }, + "description": "List of dimensions" + }, + "description": { + "type": "string", + "description": "The metric description" + }, + "name": { + "type": "string", + "description": "The metric name" + }, + "namespace": { + "type": "string", + "description": "The namespace the metric belongs to." + }, + "primaryAggregationType": { + "allOf": [ + { + "$ref": "#/components/schemas/AggregationType" + } + ], + "description": "The primary aggregation type value defining how to use the values for display." + }, + "supportedAggregationTypes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The collection of what all aggregation types are supported." + }, + "unit": { + "allOf": [ + { + "$ref": "#/components/schemas/MetricUnit" + } + ], + "description": "The unit of the metric." + }, + "metricAvailabilities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricAvailability" + }, + "description": "Metric availability specifies the time grain (aggregation interval or\nfrequency)." + } + }, + "description": "Metric definition" + }, + "MetricDefinitionCollection": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricDefinition" + }, + "description": "the values for the metric definitions." + } + }, + "description": "Represents collection of metric definitions." + }, + "MetricNamespace": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "The namespace description." + }, + "name": { + "type": "string", + "description": "The metric namespace name." + } + }, + "description": "Metric namespace class specifies the metadata for a metric namespace." + }, + "MetricNamespaceCollection": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricNamespace" + }, + "description": "The values for the metric namespaces." + } + }, + "description": "Represents collection of metric namespaces." + }, + "MetricRequestPayload": { + "type": "object", + "properties": { + "filters": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DimensionFilter" + }, + "description": "Get metrics for specific dimension values. Example: Metric contains dimension\nlike SamplerName, Error. To retrieve all the time series data where SamplerName\nis equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be\n{\"SamplerName\", [\"HTTPRequest1\", \"HTTPRequest2\"}" + } + }, + "description": "Filters to fetch the set of metric." + }, + "MetricUnit": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "NotSpecified", + "Percent", + "Count", + "Seconds", + "Milliseconds", + "Bytes", + "BytesPerSecond", + "CountPerSecond" + ] + } + ], + "description": "Metric unit." + }, + "MetricValue": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "format": "date-time", + "description": "The timestamp for the metric value in RFC 3339 format." + }, + "value": { + "type": "number", + "format": "double", + "description": "The metric value." + } + }, + "description": "Represents a metric value." + }, + "Metrics": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TimeSeriesElement" + }, + "description": "The TimeSeriesElement items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "The response to a metrics query." + }, + "NameAndDesc": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "The description" + }, + "name": { + "type": "string", + "description": "The name" + } + }, + "description": "The name and description" + }, + "Oauth2": { + "type": "object", + "required": [ + "type", + "flows", + "defaultScopes" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ], + "description": "OAuth2 authentication" + }, + "flows": { + "type": "array", + "items": {}, + "description": "Supported OAuth2 flows" + }, + "defaultScopes": { + "type": "array", + "items": {}, + "description": "Oauth2 scopes of every flow. Overridden by scope definitions in specific flows" + } + }, + "description": "OAuth 2.0 Flow with Microsoft Entra ID." + }, + "OptionalLoadTestConfig": { + "type": "object", + "properties": { + "endpointUrl": { + "type": "string", + "description": "Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login" + }, + "requestsPerSecond": { + "type": "integer", + "format": "int32", + "description": "Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it." + }, + "maxResponseTimeInMs": { + "type": "integer", + "format": "int32", + "description": "Maximum response time in milliseconds of the API/endpoint." + }, + "virtualUsers": { + "type": "integer", + "format": "int32", + "description": "No of concurrent virtual users." + }, + "rampUpTime": { + "type": "integer", + "format": "int32", + "description": "Ramp up time in seconds." + }, + "duration": { + "type": "integer", + "format": "int32", + "description": "Test run duration in seconds." + } + }, + "description": "Configuration for quick load test" + }, + "PFAction": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "continue", + "stop" + ] + } + ], + "description": "Action to take on failure of pass/fail criteria." + }, + "PFAgFunc": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "count", + "percentage", + "avg", + "p50", + "p90", + "p95", + "p99", + "min", + "max" + ] + } + ], + "description": "Aggregation functions for pass/fail criteria." + }, + "PFMetrics": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "response_time_ms", + "latency", + "error", + "requests", + "requests_per_sec" + ] + } + ], + "description": "Metrics for pass/fail criteria." + }, + "PFTestResult": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "PASSED", + "NOT_APPLICABLE", + "FAILED" + ] + } + ], + "description": "Test result based on pass/fail criteria." + }, + "PagedTest": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Test" + }, + "description": "The Test items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of Test items" + }, + "PagedTestFileInfo": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestFileInfo" + }, + "description": "The TestFileInfo items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of TestFileInfo items" + }, + "PagedTestRun": { + "type": "object", + "required": [ + "value" + ], + "properties": { + "value": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestRun" + }, + "description": "The TestRun items on this page" + }, + "nextLink": { + "type": "string", + "format": "uri", + "description": "The link to the next page of items" + } + }, + "description": "Paged collection of TestRun items" + }, + "PassFailCriteria": { + "type": "object", + "properties": { + "passFailMetrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/PassFailMetric" + }, + "description": "Map of id and pass fail metrics { id : pass fail metrics }." + } + }, + "description": "Pass fail criteria for a test." + }, + "PassFailMetric": { + "type": "object", + "properties": { + "clientMetric": { + "allOf": [ + { + "$ref": "#/components/schemas/PFMetrics" + } + ], + "description": "The client metric on which the criteria should be applied." + }, + "aggregate": { + "allOf": [ + { + "$ref": "#/components/schemas/PFAgFunc" + } + ], + "description": "The aggregation function to be applied on the client metric. Allowed functions\n- ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’,\n‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec,\n‘count’ - for requests" + }, + "condition": { + "type": "string", + "description": "The comparison operator. Supported types ‘>’, ‘<’ " + }, + "requestName": { + "type": "string", + "description": "Request name for which the Pass fail criteria has to be applied " + }, + "value": { + "type": "number", + "format": "double", + "description": "The value to compare with the client metric. Allowed values - ‘error : [0.0 ,\n100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms." + }, + "action": { + "allOf": [ + { + "$ref": "#/components/schemas/PFAction" + } + ], + "description": "Action taken after the threshold is met. Default is ‘continue’.", + "default": "continue" + } + }, + "description": "Pass fail metric" + }, + "ResourceMetric": { + "type": "object", + "required": [ + "resourceId", + "metricNamespace", + "name", + "aggregation", + "resourceType" + ], + "properties": { + "id": { + "type": "string", + "description": "Unique name for metric.", + "readOnly": true + }, + "resourceId": { + "type": "string", + "description": "Azure resource id." + }, + "metricNamespace": { + "type": "string", + "description": "Metric name space." + }, + "displayDescription": { + "type": "string", + "description": "Metric description." + }, + "name": { + "type": "string", + "description": "The invariant value of metric name" + }, + "aggregation": { + "type": "string", + "description": "Metric aggregation." + }, + "unit": { + "type": "string", + "description": "Metric unit." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type." + } + }, + "description": "Associated metric definition for particular metrics of the azure resource (\nRefer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition)." + }, + "ResourceMetricUpdate": { + "type": "object", + "properties": { + "resourceId": { + "type": "string", + "description": "Azure resource id." + }, + "metricNamespace": { + "type": "string", + "description": "Metric name space." + }, + "displayDescription": { + "type": "string", + "description": "Metric description." + }, + "name": { + "type": "string", + "description": "The invariant value of metric name" + }, + "aggregation": { + "type": "string", + "description": "Metric aggregation." + }, + "unit": { + "type": "string", + "description": "Metric unit." + }, + "resourceType": { + "type": "string", + "description": "Azure resource type." + } + }, + "description": "Associated metric definition for particular metrics of the azure resource (\nRefer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition)." + }, + "Secret": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The value of the secret for the respective type" + }, + "type": { + "allOf": [ + { + "$ref": "#/components/schemas/SecretType" + } + ], + "description": "Type of secret" + } + }, + "description": "Secret" + }, + "SecretType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "AKV_SECRET_URI", + "SECRET_VALUE" + ] + } + ], + "description": "Types of secrets supported." + }, + "Status": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "ACCEPTED", + "NOTSTARTED", + "PROVISIONING", + "PROVISIONED", + "CONFIGURING", + "CONFIGURED", + "EXECUTING", + "EXECUTED", + "DEPROVISIONING", + "DEPROVISIONED", + "DONE", + "CANCELLING", + "CANCELLED", + "FAILED", + "VALIDATION_SUCCESS", + "VALIDATION_FAILURE" + ] + } + ], + "description": "Test run status." + }, + "SystemMetaData": { + "type": "object", + "properties": { + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "System metadata." + }, + "Test": { + "type": "object", + "required": [ + "testId" + ], + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "autoStopCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/AutoStopCriteria" + } + ], + "description": "Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata." + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "baselineTestRunId": { + "type": "string", + "description": "Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs" + }, + "inputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestInputArtifacts" + } + ], + "description": "The input artifacts for the test.", + "readOnly": true + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test description." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a test." + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run." + }, + "kind": { + "allOf": [ + { + "$ref": "#/components/schemas/TestKind" + } + ], + "description": "Kind of test." + }, + "publicIPDisabled": { + "type": "boolean", + "description": "Inject load test engines without deploying public IP for outbound access" + }, + "keyvaultReferenceIdentityType": { + "type": "string", + "description": "Type of the managed identity referencing the Key vault." + }, + "keyvaultReferenceIdentityId": { + "type": "string", + "description": "Resource Id of the managed identity referencing the Key vault." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Load test model." + }, + "TestAppComponents": { + "type": "object", + "required": [ + "components" + ], + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponent" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + }, + "testId": { + "type": "string", + "description": "Test identifier", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test app components" + }, + "TestAppComponentsUpdate": { + "type": "object", + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponentUpdate" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + } + }, + "description": "Test app components" + }, + "TestCreateOrUpdate": { + "type": "object", + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "autoStopCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/AutoStopCriteria" + } + ], + "description": "Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata." + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "baselineTestRunId": { + "type": "string", + "description": "Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs" + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test description." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a test." + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run." + }, + "kind": { + "allOf": [ + { + "$ref": "#/components/schemas/TestKind" + } + ], + "description": "Kind of test." + }, + "publicIPDisabled": { + "type": "boolean", + "description": "Inject load test engines without deploying public IP for outbound access" + }, + "keyvaultReferenceIdentityType": { + "type": "string", + "description": "Type of the managed identity referencing the Key vault." + }, + "keyvaultReferenceIdentityId": { + "type": "string", + "description": "Resource Id of the managed identity referencing the Key vault." + } + }, + "description": "Load test model." + }, + "TestFileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "Test file info." + }, + "TestIdPathParameter": { + "type": "object", + "required": [ + "testId" + ], + "properties": { + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + } + }, + "description": "Test Id path parameter." + }, + "TestInputArtifacts": { + "type": "object", + "properties": { + "configFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "testScriptFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "userPropFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "inputArtifactsZipFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "File info" + }, + "urlTestConfigFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestFileInfo" + } + ], + "description": "The config json file for url based test" + }, + "additionalFileInfo": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestFileInfo" + }, + "description": "Additional supported files for the test run", + "readOnly": true + } + }, + "description": "The input artifacts for the test." + }, + "TestKind": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "URL", + "JMX" + ] + } + ], + "description": "Test kind" + }, + "TestRun": { + "type": "object", + "required": [ + "testRunId" + ], + "properties": { + "testRunId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + }, + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "autoStopCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/AutoStopCriteria" + } + ], + "description": "Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata" + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "errorDetails": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ErrorDetails" + }, + "description": "Error details if there is any failure in load test run", + "readOnly": true + }, + "testRunStatistics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/TestRunStatistics" + }, + "description": "Test run statistics.", + "readOnly": true + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "testArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunArtifacts" + } + ], + "description": "Collection of test run artifacts", + "readOnly": true + }, + "testResult": { + "allOf": [ + { + "$ref": "#/components/schemas/PFTestResult" + } + ], + "description": "Test result for pass/Fail criteria used during the test run.", + "readOnly": true + }, + "virtualUsers": { + "type": "integer", + "format": "int32", + "description": "Number of virtual users, for which test has been run.", + "readOnly": true + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a testRun." + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Associated test Id." + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test run description." + }, + "status": { + "allOf": [ + { + "$ref": "#/components/schemas/Status" + } + ], + "description": "The test run status.", + "readOnly": true + }, + "startDateTime": { + "type": "string", + "format": "date-time", + "description": "The test run start DateTime(RFC 3339 literal format).", + "readOnly": true + }, + "endDateTime": { + "type": "string", + "format": "date-time", + "description": "The test run end DateTime(RFC 3339 literal format).", + "readOnly": true + }, + "executedDateTime": { + "type": "string", + "format": "date-time", + "description": "Test run initiated time.", + "readOnly": true + }, + "portalUrl": { + "type": "string", + "description": "Portal url.", + "readOnly": true + }, + "duration": { + "type": "integer", + "format": "int64", + "description": "Test run duration in milliseconds.", + "readOnly": true + }, + "subnetId": { + "type": "string", + "description": "Subnet ID on which the load test instances should run.", + "readOnly": true + }, + "kind": { + "allOf": [ + { + "$ref": "#/components/schemas/TestKind" + } + ], + "description": "Type of test.", + "readOnly": true + }, + "publicIPDisabled": { + "type": "boolean", + "description": "Inject load test engines without deploying public IP for outbound access", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Load test run model" + }, + "TestRunAppComponents": { + "type": "object", + "required": [ + "components" + ], + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponent" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + }, + "testRunId": { + "type": "string", + "description": "Test run identifier", + "readOnly": true + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test run app component" + }, + "TestRunAppComponentsUpdate": { + "type": "object", + "properties": { + "components": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AppComponentUpdate" + }, + "description": "Azure resource collection { resource id (fully qualified resource Id e.g\nsubscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName})\n: resource object } " + } + }, + "description": "Test run app component" + }, + "TestRunArtifacts": { + "type": "object", + "properties": { + "inputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunInputArtifacts" + } + ], + "description": "The input artifacts for the test run.", + "readOnly": true + }, + "outputArtifacts": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunOutputArtifacts" + } + ], + "description": "The output artifacts for the test run." + } + }, + "description": "Collection of test run artifacts" + }, + "TestRunCreateOrUpdate": { + "type": "object", + "properties": { + "passFailCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/PassFailCriteria" + } + ], + "description": "Pass fail criteria for a test." + }, + "autoStopCriteria": { + "allOf": [ + { + "$ref": "#/components/schemas/AutoStopCriteria" + } + ], + "description": "Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window." + }, + "secrets": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Secret" + }, + "description": "Secrets can be stored in an Azure Key Vault or any other secret store. If the\nsecret is stored in an Azure Key Vault, the value should be the secret\nidentifier and the type should be AKV_SECRET_URI. If the secret is stored\nelsewhere, the secret value should be provided directly and the type should be\nSECRET_VALUE." + }, + "certificate": { + "allOf": [ + { + "$ref": "#/components/schemas/CertificateMetadata" + } + ], + "description": "Certificates metadata" + }, + "environmentVariables": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables which are defined as a set of pairs." + }, + "loadTestConfiguration": { + "allOf": [ + { + "$ref": "#/components/schemas/LoadTestConfiguration" + } + ], + "description": "The load test configuration." + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Display name of a testRun." + }, + "testId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "description": "Associated test Id." + }, + "description": { + "type": "string", + "maxLength": 100, + "description": "The test run description." + } + }, + "description": "Load test run model" + }, + "TestRunFileInfo": { + "type": "object", + "properties": { + "url": { + "type": "string", + "format": "uri", + "description": "File URL.", + "readOnly": true + }, + "fileType": { + "allOf": [ + { + "$ref": "#/components/schemas/FileType" + } + ], + "description": "File type", + "readOnly": true + }, + "expireDateTime": { + "type": "string", + "format": "date-time", + "description": "Expiry time of the file (RFC 3339 literal format)", + "readOnly": true + }, + "validationStatus": { + "allOf": [ + { + "$ref": "#/components/schemas/FileStatus" + } + ], + "description": "Validation status of the file", + "readOnly": true + }, + "validationFailureDetails": { + "type": "string", + "description": "Validation failure error details", + "readOnly": true + } + }, + "description": "Test run file info." + }, + "TestRunIdPathParameter": { + "type": "object", + "required": [ + "testRunId" + ], + "properties": { + "testRunId": { + "type": "string", + "minLength": 2, + "maxLength": 50, + "pattern": "^[a-z0-9_-]*$", + "description": "Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.", + "readOnly": true + } + }, + "description": "Test run Id path parameter." + }, + "TestRunInputArtifacts": { + "type": "object", + "properties": { + "configFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "testScriptFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "userPropFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "inputArtifactsZipFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "urlTestConfigFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "The config json file for url based test" + }, + "additionalFileInfo": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TestRunFileInfo" + }, + "description": "Additional supported files for the test run", + "readOnly": true + } + }, + "description": "The input artifacts for the test run." + }, + "TestRunOutputArtifacts": { + "type": "object", + "properties": { + "resultFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "logsFileInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/TestRunFileInfo" + } + ], + "description": "File info" + }, + "artifactsContainerInfo": { + "allOf": [ + { + "$ref": "#/components/schemas/ArtifactsContainerInfo" + } + ], + "description": "The container for test run artifacts." + } + }, + "description": "The output artifacts for the test run." + }, + "TestRunServerMetricConfig": { + "type": "object", + "properties": { + "testRunId": { + "type": "string", + "description": "Test run identifier", + "readOnly": true + }, + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetric" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test run server metrics configuration" + }, + "TestRunStatistics": { + "type": "object", + "properties": { + "transaction": { + "type": "string", + "description": "Transaction name.", + "readOnly": true + }, + "sampleCount": { + "type": "number", + "format": "double", + "description": "Sampler count.", + "readOnly": true + }, + "errorCount": { + "type": "number", + "format": "double", + "description": "Error count.", + "readOnly": true + }, + "errorPct": { + "type": "number", + "format": "double", + "description": "Error percentage.", + "readOnly": true + }, + "meanResTime": { + "type": "number", + "format": "double", + "description": "Mean response time.", + "readOnly": true + }, + "medianResTime": { + "type": "number", + "format": "double", + "description": "Median response time.", + "readOnly": true + }, + "maxResTime": { + "type": "number", + "format": "double", + "description": "Max response time.", + "readOnly": true + }, + "minResTime": { + "type": "number", + "format": "double", + "description": "Minimum response time.", + "readOnly": true + }, + "pct1ResTime": { + "type": "number", + "format": "double", + "description": "90 percentile response time.", + "readOnly": true + }, + "pct2ResTime": { + "type": "number", + "format": "double", + "description": "95 percentile response time.", + "readOnly": true + }, + "pct3ResTime": { + "type": "number", + "format": "double", + "description": "99 percentile response time.", + "readOnly": true + }, + "throughput": { + "type": "number", + "format": "double", + "description": "Throughput.", + "readOnly": true + }, + "receivedKBytesPerSec": { + "type": "number", + "format": "double", + "description": "Received network bytes.", + "readOnly": true + }, + "sentKBytesPerSec": { + "type": "number", + "format": "double", + "description": "Send network bytes.", + "readOnly": true + } + }, + "description": "Test run statistics." + }, + "TestServerMetricConfig": { + "type": "object", + "required": [ + "metrics" + ], + "properties": { + "testId": { + "type": "string", + "description": "Test identifier", + "readOnly": true + }, + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetric" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + }, + "createdDateTime": { + "type": "string", + "format": "date-time", + "description": "The creation datetime(RFC 3339 literal format).", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "The user that created.", + "readOnly": true + }, + "lastModifiedDateTime": { + "type": "string", + "format": "date-time", + "description": "The last Modified datetime(RFC 3339 literal format).", + "readOnly": true + }, + "lastModifiedBy": { + "type": "string", + "description": "The user that last modified.", + "readOnly": true + } + }, + "description": "Test server metrics configuration" + }, + "TestServerMetricConfigUpdate": { + "type": "object", + "properties": { + "metrics": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ResourceMetricUpdate" + }, + "description": "Azure resource metrics collection {metric id : metrics object} (Refer :\nhttps://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition\nfor metric id)." + } + }, + "description": "Test server metrics configuration" + }, + "TimeGrain": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "enum": [ + "PT5S", + "PT10S", + "PT1M", + "PT5M", + "PT1H" + ] + } + ], + "description": "Time Grain" + }, + "TimeSeriesElement": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MetricValue" + }, + "description": "An array of data points representing the metric values." + }, + "dimensionValues": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DimensionValue" + }, + "description": "The dimension values " + } + }, + "description": "The time series returned when a data query is performed." + } + }, + "securitySchemes": { + "Oauth2": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", + "scopes": { + "https://cnt-prod.loadtesting.azure.com/.default": "" + } + } + }, + "description": "OAuth 2.0 Flow with Microsoft Entra ID." + } + } + }, + "servers": [ + { + "url": "https://{endpoint}", + "description": "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", + "variables": { + "endpoint": { + "default": "" + } + } + } + ] +} diff --git a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml index 180c5d487a..bffc1bfd71 100644 --- a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml +++ b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml @@ -3,6 +3,7 @@ emit: # Uncomment this line and add "@azure-tools/typespec-python" to your package.json to generate Python code # - "@azure-tools/typespec-python" - "@azure-tools/typespec-ts" + - "@typespec/openapi3" options: "@azure-tools/typespec-ts": "emitter-output-dir": "{project-root}/generated/typespec-ts" @@ -16,3 +17,6 @@ options: name: "@azure/load-testing" description: This package contains Microsoft Azure LoadTestingClient client library. version: 1.0.1 + "@typespec/openapi3": + "emitter-output-dir": "{project-root}/generated/openapi" + "file-type": "json" From e0e6427981cf36b9f08b1b0a5b88e6e19c3a7846 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 3 Jul 2024 22:06:19 +0800 Subject: [PATCH 05/18] Merge to main --- packages/typespec-test/package.json | 22 +- .../generated/typespec-ts/package.json | 8 +- .../review/arm-networkanalytics.api.md | 254 +- .../typespec-ts/src/api/dataProducts/index.ts | 128 +- .../src/api/dataProductsCatalogs/index.ts | 6 +- .../typespec-ts/src/api/dataTypes/index.ts | 28 +- .../src/api/networkAnalyticsContext.ts | 1 + .../typespec-ts/src/api/operations/index.ts | 4 +- .../src/classic/dataProducts/index.ts | 47 +- .../src/classic/dataProductsCatalogs/index.ts | 18 +- .../src/classic/dataTypes/index.ts | 35 +- .../src/classic/operations/index.ts | 2 + .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 16 +- .../generated/typespec-ts/src/models/index.ts | 16 +- .../typespec-ts/src/models/models.ts | 534 +- .../typespec-ts/src/models/options.ts | 22 + .../typespec-ts/src/networkAnalyticsClient.ts | 10 +- .../generated/typespec-ts/src/rest/models.ts | 190 +- .../src/rest/networkAnalyticsClient.ts | 29 +- .../typespec-ts/src/rest/outputModels.ts | 214 +- .../typespec-ts/src/rest/pollingHelper.ts | 4 +- .../typespec-ts/src/rest/responses.ts | 8 +- .../typespec-ts/src/restorePollerHelpers.ts | 3 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../tspconfig.yaml | 1 + .../generated/openapi/v1.1/openapi.json | 8 +- .../generated/typespec-ts/package.json | 4 +- .../review/ai-anomaly-detector.api.md | 62 +- .../src/api/anomalyDetectorContext.ts | 1 + .../typespec-ts/src/api/multivariate/index.ts | 54 +- .../typespec-ts/src/api/univariate/index.ts | 16 +- .../src/classic/multivariate/index.ts | 34 + .../src/classic/univariate/index.ts | 12 + .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 1 - .../generated/typespec-ts/src/models/index.ts | 1 - .../typespec-ts/src/models/models.ts | 166 +- .../typespec-ts/src/models/options.ts | 10 + .../src/rest/anomalyDetectorClient.ts | 12 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../openapi/2022-05-15-preview/openapi.json | 24 + .../generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/authoring.api.md | 9 +- .../typespec-ts/src/authoringClient.ts | 30 +- .../generated/typespec-ts/src/outputModels.ts | 9 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../generated/typespec-ts/review/batch.api.md | 330 +- .../typespec-ts/src/api/batchContext.ts | 1 + .../typespec-ts/src/api/operations.ts | 16433 +++++----------- .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 13 - .../generated/typespec-ts/src/models/index.ts | 13 - .../typespec-ts/src/models/models.ts | 1410 +- .../typespec-ts/src/models/options.ts | 76 + .../typespec-ts/src/rest/batchClient.ts | 7 +- .../typespec-ts/src/rest/responses.ts | 2 + .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../review/ai-chat-protocol.api.md | 12 +- .../src/api/chatProtocolContext.ts | 1 + .../typespec-ts/src/api/operations.ts | 22 +- .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 45 +- .../typespec-ts/src/models/options.ts | 2 + .../src/rest/chatProtocolClient.ts | 7 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 2 +- .../review/confidential-ledger.api.md | 7 +- .../src/confidentialLedgerClient.ts | 30 +- .../generated/typespec-ts/package.json | 2 +- .../review/ai-content-safety.api.md | 44 +- .../src/api/contentSafetyContext.ts | 1 + .../typespec-ts/src/api/operations.ts | 26 +- .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 2 - .../generated/typespec-ts/src/models/index.ts | 2 - .../typespec-ts/src/models/models.ts | 87 +- .../typespec-ts/src/models/options.ts | 10 + .../src/rest/contentSafetyClient.ts | 27 +- .../openapi/2022-11-01-preview/openapi.json | 6 + .../generated/typespec-ts/package.json | 8 +- .../review/contosowidgetmanager-rest.api.md | 9 +- .../generated/typespec-ts/src/outputModels.ts | 9 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../typespec-ts/src/widgetManagerClient.ts | 30 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../typespec-ts/review/customWrapper.api.md | 7 +- .../typespec-ts/src/authoringClient.ts | 30 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../typespec-ts/review/eventgrid.api.md | 16 +- .../typespec-ts/src/api/eventGridContext.ts | 1 + .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 52 +- .../typespec-ts/src/models/options.ts | 6 + .../typespec-ts/src/rest/eventGridClient.ts | 30 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../faceai/generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/ai-face-rest.api.md | 43 +- .../generated/typespec-ts/src/faceClient.ts | 12 +- .../generated/typespec-ts/src/models.ts | 33 +- .../generated/typespec-ts/src/outputModels.ts | 74 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 8 +- .../health-insights-radiologyinsights.api.md | 7 +- .../src/azureHealthInsightsClient.ts | 30 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 8 +- .../health-insights-clinicalmatching.api.md | 7 +- .../src/healthInsightsClinicalMatching.ts | 31 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../review/hierarchy-generic.api.md | 22 +- .../typespec-ts/src/api/fooContext.ts | 1 + .../typespec-ts/src/classic/b/c/index.ts | 1 + .../typespec-ts/src/classic/b/e/c/index.ts | 1 + .../typespec-ts/src/classic/b/e/index.ts | 1 + .../typespec-ts/src/classic/b/index.ts | 1 + .../typespec-ts/src/classic/d/index.ts | 1 + .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 20 + .../typespec-ts/src/models/options.ts | 5 + .../typespec-ts/src/rest/fooClient.ts | 7 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/load-testing.api.md | 7 +- .../typespec-ts/src/azureLoadTesting.ts | 26 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/load-testing.api.md | 189 +- .../administrationOperationsClient.ts | 38 +- .../api/administrationOperationsContext.ts | 7 +- .../src/administrationOperations/api/index.ts | 2 +- .../api/operations.ts | 542 +- .../src/administrationOperations/index.ts | 13 +- .../administrationOperations/models/index.ts | 13 +- .../administrationOperations/models/models.ts | 618 +- .../models/options.ts | 30 +- .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 32 +- .../src/rest/azureLoadTestingClient.ts | 73 + .../typespec-ts/src/rest/clientDefinitions.ts | 115 +- .../generated/typespec-ts/src/rest/index.ts | 7 +- .../typespec-ts/src/rest/isUnexpected.ts | 89 +- .../generated/typespec-ts/src/rest/models.ts | 149 +- .../typespec-ts/src/rest/outputModels.ts | 239 +- .../typespec-ts/src/rest/parameters.ts | 81 +- .../typespec-ts/src/rest/pollingHelper.ts | 223 + .../typespec-ts/src/rest/responses.ts | 119 +- .../src/testRunOperations/api/index.ts | 4 +- .../src/testRunOperations/api/operations.ts | 1009 +- .../testRunOperations/api/pollingHelpers.ts | 139 + .../api/testRunOperationsContext.ts | 7 +- .../src/testRunOperations/index.ts | 16 +- .../src/testRunOperations/models/index.ts | 15 +- .../src/testRunOperations/models/models.ts | 618 +- .../src/testRunOperations/models/options.ts | 55 +- .../testRunOperations/restorePollerHelpers.ts | 156 + .../testRunOperationsClient.ts | 73 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../test/loadtesting_modular/spec/client.tsp | 77 +- .../test/loadtesting_modular/spec/main.tsp | 20 +- .../test/loadtesting_modular/spec/models.tsp | 820 +- .../test/loadtesting_modular/spec/routes.tsp | 486 +- .../test/loadtesting_modular/tspconfig.yaml | 4 - .../generated/openapi/2022-12-01/openapi.json | 6 +- .../generated/openapi/2023-05-15/openapi.json | 6 +- .../openapi/2023-06-01-preview/openapi.json | 14 +- .../openapi/2023-07-01-preview/openapi.json | 16 +- .../openapi/2023-08-01-preview/openapi.json | 20 +- .../openai/generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/openai.api.md | 7 +- .../generated/typespec-ts/src/openAIClient.ts | 27 +- .../typespec-ts/src/pollingHelper.ts | 4 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../typespec-ts/review/openai-generic.api.md | 95 +- .../src/api/chat/completions/index.ts | 25 +- .../typespec-ts/src/api/completions/index.ts | 5 +- .../typespec-ts/src/api/openAIContext.ts | 1 + .../typespec-ts/src/classic/audio/index.ts | 1 + .../src/classic/audio/transcriptions/index.ts | 1 + .../src/classic/audio/translations/index.ts | 1 + .../src/classic/chat/completions/index.ts | 1 + .../typespec-ts/src/classic/chat/index.ts | 1 + .../src/classic/completions/index.ts | 1 + .../typespec-ts/src/classic/edits/index.ts | 1 + .../src/classic/embeddings/index.ts | 1 + .../typespec-ts/src/classic/files/index.ts | 6 + .../src/classic/fineTunes/index.ts | 1 + .../src/classic/fineTuning/index.ts | 1 + .../src/classic/fineTuning/jobs/index.ts | 9 + .../typespec-ts/src/classic/images/index.ts | 1 + .../typespec-ts/src/classic/models/index.ts | 6 + .../src/classic/moderations/index.ts | 1 + .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 261 +- .../typespec-ts/src/models/options.ts | 28 + .../generated/typespec-ts/src/rest/models.ts | 40 +- .../typespec-ts/src/rest/openAIClient.ts | 6 +- .../typespec-ts/src/rest/outputModels.ts | 2 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 4 +- .../typespec-ts/review/openai_modular.api.md | 75 +- .../typespec-ts/src/api/openAIContext.ts | 1 + .../typespec-ts/src/api/operations.ts | 45 +- .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 1021 +- .../typespec-ts/src/models/options.ts | 9 + .../typespec-ts/src/rest/openAIClient.ts | 27 +- .../typespec-ts/src/rest/responses.ts | 18 + .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../spec/client/custom_visibility.tsp | 1 + .../review/openai-non-branded.api.md | 95 +- .../src/api/chat/completions/index.ts | 25 +- .../typespec-ts/src/api/completions/index.ts | 5 +- .../typespec-ts/src/api/openAIContext.ts | 1 + .../typespec-ts/src/classic/audio/index.ts | 1 + .../src/classic/audio/transcriptions/index.ts | 1 + .../src/classic/audio/translations/index.ts | 1 + .../src/classic/chat/completions/index.ts | 1 + .../typespec-ts/src/classic/chat/index.ts | 1 + .../src/classic/completions/index.ts | 1 + .../typespec-ts/src/classic/edits/index.ts | 1 + .../src/classic/embeddings/index.ts | 1 + .../typespec-ts/src/classic/files/index.ts | 6 + .../src/classic/fineTunes/index.ts | 1 + .../src/classic/fineTuning/index.ts | 1 + .../src/classic/fineTuning/jobs/index.ts | 9 + .../typespec-ts/src/classic/images/index.ts | 1 + .../typespec-ts/src/classic/models/index.ts | 6 + .../src/classic/moderations/index.ts | 1 + .../src/helpers/serializerHelpers.ts | 39 + .../typespec-ts/src/models/models.ts | 261 +- .../typespec-ts/src/models/options.ts | 28 + .../generated/typespec-ts/src/rest/models.ts | 40 +- .../typespec-ts/src/rest/openAIClient.ts | 6 +- .../typespec-ts/src/rest/outputModels.ts | 2 +- .../generated/typespec-ts/package.json | 4 +- .../review/overload_modular.api.md | 12 +- .../src/api/widgetManagerContext.ts | 1 + .../src/classic/fooOperations/index.ts | 3 + .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/models.ts | 1 - .../typespec-ts/src/models/options.ts | 2 + .../src/rest/widgetManagerClient.ts | 27 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 2 +- .../review/parametrized-host.api.md | 7 +- .../src/api/parametrizedHostContext.ts | 1 + .../src/classic/confidentialLedger/index.ts | 2 + .../src/helpers/serializerHelpers.ts | 40 + .../typespec-ts/src/models/options.ts | 1 + .../src/rest/parametrizedHostClient.ts | 15 +- .../generated/typespec-ts/package.json | 2 +- .../typespec-ts/review/schema-registry.api.md | 42 +- .../src/api/schemaOperations/index.ts | 8 +- .../src/api/schemaRegistryContext.ts | 1 + .../src/classic/schemaOperations/index.ts | 7 + .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 2 - .../generated/typespec-ts/src/models/index.ts | 2 - .../typespec-ts/src/models/models.ts | 25 +- .../typespec-ts/src/models/options.ts | 6 + .../src/rest/schemaRegistryClient.ts | 27 +- .../review/todo-non-branded.api.md | 6 +- .../generated/typespec-ts/src/todoClient.ts | 7 +- .../generated/typespec-ts/package.json | 4 +- .../cognitiveservices-translator.api.md | 7 +- .../typespec-ts/src/translatorClient.ts | 27 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../generated/typespec-ts/package.json | 8 +- .../typespec-ts/review/widget_dpg.api.md | 61 +- .../typespec-ts/src/api/budgets/index.ts | 65 +- .../src/api/widgetServiceContext.ts | 1 + .../typespec-ts/src/api/widgets/index.ts | 6 +- .../typespec-ts/src/classic/budgets/index.ts | 20 +- .../typespec-ts/src/classic/widgets/index.ts | 20 + .../src/helpers/serializerHelpers.ts | 40 + .../generated/typespec-ts/src/index.ts | 2 +- .../generated/typespec-ts/src/models/index.ts | 2 +- .../typespec-ts/src/models/models.ts | 36 +- .../typespec-ts/src/models/options.ts | 20 + .../typespec-ts/src/rest/clientDefinitions.ts | 20 + .../typespec-ts/src/rest/isUnexpected.ts | 22 +- .../typespec-ts/src/rest/parameters.ts | 26 + .../typespec-ts/src/rest/pollingHelper.ts | 20 +- .../typespec-ts/src/rest/responses.ts | 41 + .../src/rest/widgetServiceClient.ts | 7 +- .../typespec-ts/src/restorePollerHelpers.ts | 10 +- .../test/public/utils/recordedClient.ts | 21 +- .../typespec-ts/vitest.browser.config.ts | 1 + .../generated/typespec-ts/vitest.config.ts | 1 + .../test/widget_dpg/spec/main.tsp | 5 +- 340 files changed, 14728 insertions(+), 16650 deletions(-) create mode 100644 packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/batch_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts create mode 100644 packages/typespec-test/test/openai_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/openai_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/helpers/serializerHelpers.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/helpers/serializerHelpers.ts diff --git a/packages/typespec-test/package.json b/packages/typespec-test/package.json index 2244098898..7c61298d8d 100644 --- a/packages/typespec-test/package.json +++ b/packages/typespec-test/package.json @@ -3,17 +3,17 @@ "version": "1.0.0", "type": "module", "dependencies": { - "@azure-tools/typespec-ts": "workspace:^0.29.0", - "@typespec/openapi": ">=0.56.0 <1.0.0", - "@azure-tools/typespec-autorest": ">=0.42.1 <1.0.0", - "@typespec/openapi3": ">=0.56.0 <1.0.0", - "@azure-tools/typespec-azure-core": ">=0.42.0 <1.0.0", - "@azure-tools/typespec-client-generator-core": ">=0.42 <1.0.0", - "@azure-tools/typespec-azure-resource-manager":"0.42.0", - "@typespec/compiler": ">=0.56.0 <1.0.0", - "@typespec/http": ">=0.56.0 <1.0.0", - "@typespec/rest": ">=0.56.0 <1.0.0", - "@typespec/versioning": ">=0.56.0 <1.0.0", + "@azure-tools/typespec-ts": "workspace:^0.30.1", + "@typespec/openapi": ">=0.57.0 <1.0.0", + "@azure-tools/typespec-autorest": ">=0.43.0 <1.0.0", + "@typespec/openapi3": ">=0.57.0 <1.0.0", + "@azure-tools/typespec-azure-core": ">=0.43.0 <1.0.0", + "@azure-tools/typespec-client-generator-core": ">=0.43.0 <1.0.0", + "@azure-tools/typespec-azure-resource-manager": ">=0.43.0 <1.0.0", + "@typespec/compiler": ">=0.57.0 <1.0.0", + "@typespec/http": ">=0.57.0 <1.0.0", + "@typespec/rest": ">=0.57.0 <1.0.0", + "@typespec/versioning": ">=0.57.0 <1.0.0", "prettier": "^3.1.0" }, "devDependencies": { diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/package.json b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/package.json index 19a36b7b10..70319a4089 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/package.json @@ -46,13 +46,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -66,7 +66,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md index fb52a21ee6..281425cc29 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/review/arm-networkanalytics.api.md @@ -5,18 +5,12 @@ ```ts import { AbortSignalLike } from '@azure/abort-controller'; -import { Client } from '@azure-rest/core-client'; import { ClientOptions } from '@azure-rest/core-client'; -import { HttpResponse } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { OperationState } from '@azure/core-lro'; -import { Paged } from '@azure/core-paging'; import { PathUncheckedResponse } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { PollerLike } from '@azure/core-lro'; -import { RawHttpHeaders } from '@azure/core-rest-pipeline'; -import { RequestParameters } from '@azure-rest/core-client'; -import { StreamableMethod } from '@azure-rest/core-client'; import { TokenCredential } from '@azure/core-auth'; // @public @@ -34,16 +28,6 @@ export interface AccountSasToken { // @public export type ActionType = string; -// @public -export interface ArmOperationStatus { - readonly endTime?: Date; - readonly error?: ErrorDetail; - readonly name?: string; - readonly percentComplete?: number; - readonly startTime?: Date; - status: ResourceProvisioningState; -} - // @public export interface ConsumptionEndpointsProperties { readonly fileAccessResourceId?: string; @@ -90,12 +74,6 @@ export interface DataProductInformation { description: string; } -// @public -export interface DataProductListResult { - nextLink?: string; - value: DataProduct[]; -} - // @public export interface DataProductNetworkAcls { allowedQueryIpRangeList: string[]; @@ -128,7 +106,7 @@ export interface DataProductProperties { readonly resourceGuid?: string; } -// @public (undocumented) +// @public export interface DataProductsAddUserRoleOptionalParams extends OperationOptions { } @@ -137,105 +115,85 @@ export interface DataProductsCatalog extends ProxyResource { properties?: DataProductsCatalogProperties; } -// @public -export interface DataProductsCatalogListResult { - nextLink?: string; - value: DataProductsCatalog[]; -} - // @public export interface DataProductsCatalogProperties { readonly provisioningState?: ProvisioningState; publishers: PublisherInformation[]; } -// @public (undocumented) +// @public export interface DataProductsCatalogsGetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsCatalogsListByResourceGroupOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsCatalogsListBySubscriptionOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsCatalogsOperations { - // (undocumented) - get: (subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsGetOptionalParams) => Promise; - // (undocumented) - listByResourceGroup: (subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) - listBySubscription: (subscriptionId: string, options?: DataProductsCatalogsListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; + get: (resourceGroupName: string, options?: DataProductsCatalogsGetOptionalParams) => Promise; + listByResourceGroup: (resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; + listBySubscription: (options?: DataProductsCatalogsListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; } -// @public (undocumented) +// @public export interface DataProductsCreateOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface DataProductsDeleteOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface DataProductsGenerateStorageAccountSasTokenOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsGetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsListByResourceGroupOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsListBySubscriptionOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsListRolesAssignmentsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsOperations { - // (undocumented) - addUserRole: (subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentCommonProperties, options?: DataProductsAddUserRoleOptionalParams) => Promise; - // (undocumented) - create: (subscriptionId: string, resourceGroupName: string, dataProductName: string, resource: DataProduct, options?: DataProductsCreateOptionalParams) => PollerLike, DataProduct>; - // (undocumented) - delete: (subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsDeleteOptionalParams) => PollerLike, void>; - // (undocumented) - generateStorageAccountSasToken: (subscriptionId: string, resourceGroupName: string, dataProductName: string, body: AccountSas, options?: DataProductsGenerateStorageAccountSasTokenOptionalParams) => Promise; - // (undocumented) - get: (subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsGetOptionalParams) => Promise; - // (undocumented) - listByResourceGroup: (subscriptionId: string, resourceGroupName: string, options?: DataProductsListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) - listBySubscription: (subscriptionId: string, options?: DataProductsListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) - listRolesAssignments: (subscriptionId: string, resourceGroupName: string, dataProductName: string, body: Record, options?: DataProductsListRolesAssignmentsOptionalParams) => Promise; - // (undocumented) - removeUserRole: (subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentDetail, options?: DataProductsRemoveUserRoleOptionalParams) => Promise; - // (undocumented) - rotateKey: (subscriptionId: string, resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, options?: DataProductsRotateKeyOptionalParams) => Promise; - // (undocumented) - update: (subscriptionId: string, resourceGroupName: string, dataProductName: string, properties: DataProductUpdate, options?: DataProductsUpdateOptionalParams) => PollerLike, DataProduct>; + addUserRole: (resourceGroupName: string, dataProductName: string, body: RoleAssignmentCommonProperties, options?: DataProductsAddUserRoleOptionalParams) => Promise; + create: (resourceGroupName: string, dataProductName: string, resource: DataProduct, options?: DataProductsCreateOptionalParams) => PollerLike, DataProduct>; + delete: (resourceGroupName: string, dataProductName: string, options?: DataProductsDeleteOptionalParams) => PollerLike, void>; + generateStorageAccountSasToken: (resourceGroupName: string, dataProductName: string, body: AccountSas, options?: DataProductsGenerateStorageAccountSasTokenOptionalParams) => Promise; + get: (resourceGroupName: string, dataProductName: string, options?: DataProductsGetOptionalParams) => Promise; + listByResourceGroup: (resourceGroupName: string, options?: DataProductsListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; + listBySubscription: (options?: DataProductsListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; + listRolesAssignments: (resourceGroupName: string, dataProductName: string, body: Record, options?: DataProductsListRolesAssignmentsOptionalParams) => Promise; + removeUserRole: (resourceGroupName: string, dataProductName: string, body: RoleAssignmentDetail, options?: DataProductsRemoveUserRoleOptionalParams) => Promise; + rotateKey: (resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, options?: DataProductsRotateKeyOptionalParams) => Promise; + update: (resourceGroupName: string, dataProductName: string, properties: DataProductUpdate, options?: DataProductsUpdateOptionalParams) => PollerLike, DataProduct>; } -// @public (undocumented) +// @public export interface DataProductsRemoveUserRoleOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsRotateKeyOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataProductsUpdateOptionalParams extends OperationOptions { updateIntervalInMs?: number; } @@ -270,12 +228,6 @@ export interface DataType extends ProxyResource { properties?: DataTypeProperties; } -// @public -export interface DataTypeListResult { - nextLink?: string; - value: DataType[]; -} - // @public export interface DataTypeProperties { databaseCacheRetention?: number; @@ -287,55 +239,48 @@ export interface DataTypeProperties { readonly visualizationUrl?: string; } -// @public (undocumented) +// @public export interface DataTypesCreateOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface DataTypesDeleteDataOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface DataTypesDeleteOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface DataTypesGenerateStorageContainerSasTokenOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataTypesGetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataTypesListByDataProductOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DataTypesOperations { - // (undocumented) - create: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, resource: DataType, options?: DataTypesCreateOptionalParams) => PollerLike, DataType>; - // (undocumented) - delete: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesDeleteOptionalParams) => PollerLike, void>; - // (undocumented) - deleteData: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, body: Record, options?: DataTypesDeleteDataOptionalParams) => PollerLike, void>; - // (undocumented) - generateStorageContainerSasToken: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, body: ContainerSaS, options?: DataTypesGenerateStorageContainerSasTokenOptionalParams) => Promise; - // (undocumented) - get: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesGetOptionalParams) => Promise; - // (undocumented) - listByDataProduct: (subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataTypesListByDataProductOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) - update: (subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, properties: DataTypeUpdate, options?: DataTypesUpdateOptionalParams) => PollerLike, DataType>; + create: (resourceGroupName: string, dataProductName: string, dataTypeName: string, resource: DataType, options?: DataTypesCreateOptionalParams) => PollerLike, DataType>; + delete: (resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesDeleteOptionalParams) => PollerLike, void>; + deleteData: (resourceGroupName: string, dataProductName: string, dataTypeName: string, body: Record, options?: DataTypesDeleteDataOptionalParams) => PollerLike, void>; + generateStorageContainerSasToken: (resourceGroupName: string, dataProductName: string, dataTypeName: string, body: ContainerSaS, options?: DataTypesGenerateStorageContainerSasTokenOptionalParams) => Promise; + get: (resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesGetOptionalParams) => Promise; + listByDataProduct: (resourceGroupName: string, dataProductName: string, options?: DataTypesListByDataProductOptionalParams) => PagedAsyncIterableIterator; + update: (resourceGroupName: string, dataProductName: string, dataTypeName: string, properties: DataTypeUpdate, options?: DataTypesUpdateOptionalParams) => PollerLike, DataType>; } // @public export type DataTypeState = string; -// @public (undocumented) +// @public export interface DataTypesUpdateOptionalParams extends OperationOptions { updateIntervalInMs?: number; } @@ -395,6 +340,69 @@ export interface KeyVaultInfo { keyVaultUrl: string; } +// @public +export enum KnownActionType { + Internal = "Internal" +} + +// @public +export enum KnownControlState { + Disabled = "Disabled", + Enabled = "Enabled" +} + +// @public +export enum KnownCreatedByType { + Application = "Application", + Key = "Key", + ManagedIdentity = "ManagedIdentity", + User = "User" +} + +// @public +export enum KnownDataProductUserRole { + Reader = "Reader", + SensitiveReader = "SensitiveReader" +} + +// @public +export enum KnownDataTypeState { + Running = "Running", + Stopped = "Stopped" +} + +// @public +export enum KnownDefaultAction { + Allow = "Allow", + Deny = "Deny" +} + +// @public +export enum KnownManagedServiceIdentityType { + "SystemAssigned,UserAssigned" = "SystemAssigned,UserAssigned", + None = "None", + SystemAssigned = "SystemAssigned", + UserAssigned = "UserAssigned" +} + +// @public +export enum KnownOrigin { + "user,system" = "user,system", + system = "system", + user = "user" +} + +// @public +export enum KnownProvisioningState { + Accepted = "Accepted", + Canceled = "Canceled", + Deleting = "Deleting", + Failed = "Failed", + Provisioning = "Provisioning", + Succeeded = "Succeeded", + Updating = "Updating" +} + // @public export interface ListRoleAssignments { count: number; @@ -412,7 +420,7 @@ export interface ManagedServiceIdentity { readonly principalId?: string; readonly tenantId?: string; type: ManagedServiceIdentityType; - userAssignedIdentities?: UserAssignedIdentities; + userAssignedIdentities?: Record; } // @public @@ -420,7 +428,7 @@ export type ManagedServiceIdentityType = string; // @public (undocumented) export class NetworkAnalyticsClient { - constructor(credential: TokenCredential, options?: NetworkAnalyticsClientOptions); + constructor(credential: TokenCredential, subscriptionId: string, options?: NetworkAnalyticsClientOptions); readonly dataProducts: DataProductsOperations; readonly dataProductsCatalogs: DataProductsCatalogsOperations; readonly dataTypes: DataTypesOperations; @@ -428,7 +436,7 @@ export class NetworkAnalyticsClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface NetworkAnalyticsClientOptions extends ClientOptions { apiVersion?: string; } @@ -450,13 +458,12 @@ export interface OperationDisplay { resource?: string; } -// @public (undocumented) +// @public export interface OperationsListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface OperationsOperations { - // (undocumented) list: (options?: OperationsListOptionalParams) => PagedAsyncIterableIterator; } @@ -470,12 +477,6 @@ export interface PagedAsyncIterableIterator>; } -// @public -export interface PagedOperation { - nextLink?: string; - value: Operation[]; -} - // @public export interface PageSettings { continuationToken?: string; @@ -503,12 +504,7 @@ export interface Resource { } // @public -export type ResourceProvisioningState = string; - -// Warning: (ae-forgotten-export) The symbol "NetworkAnalyticsContext" needs to be exported by the entry point index.d.ts -// -// @public -export function restorePoller(client: NetworkAnalyticsContext | NetworkAnalyticsClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; +export function restorePoller(client: NetworkAnalyticsClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; // @public (undocumented) export interface RestorePollerOptions extends OperationOptions { @@ -540,12 +536,12 @@ export interface RoleAssignmentDetail { // @public export interface SystemData { - readonly createdAt?: Date; - readonly createdBy?: string; - readonly createdByType?: CreatedByType; - readonly lastModifiedAt?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedByType?: CreatedByType; + createdAt?: Date; + createdBy?: string; + createdByType?: CreatedByType; + lastModifiedAt?: Date; + lastModifiedBy?: string; + lastModifiedByType?: CreatedByType; } // @public @@ -554,17 +550,13 @@ export interface TrackedResource extends Resource { tags?: Record; } -// @public -export interface UserAssignedIdentities extends Record { -} - // @public export interface UserAssignedIdentity { - clientId?: string; - principalId?: string; + readonly clientId?: string; + readonly principalId?: string; } -// @public (undocumented) +// @public export type Versions = "2023-11-15"; // @public diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts index 6a682a1cc3..8b87e0777a 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProducts/index.ts @@ -4,6 +4,9 @@ import { getLongRunningPoller } from "../pollingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { + dataProductPropertiesSerializer, + managedServiceIdentitySerializer, + dataProductUpdatePropertiesSerializer, DataProduct, DataProductUpdate, AccountSas, @@ -12,7 +15,7 @@ import { RoleAssignmentCommonProperties, RoleAssignmentDetail, ListRoleAssignments, - DataProductListResult, + _DataProductListResult, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -53,6 +56,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { DataProductsCreateOptionalParams, DataProductsGetOptionalParams, @@ -90,76 +94,16 @@ export function _createSend( .put({ ...operationOptionsToRequestParameters(options), body: { + tags: !resource.tags + ? resource.tags + : (serializeRecord(resource.tags as any) as any), location: resource["location"], - tags: resource["tags"], properties: !resource.properties - ? undefined - : { - publisher: resource.properties?.["publisher"], - product: resource.properties?.["product"], - majorVersion: resource.properties?.["majorVersion"], - owners: resource.properties?.["owners"], - redundancy: resource.properties?.["redundancy"], - purviewAccount: resource.properties?.["purviewAccount"], - purviewCollection: resource.properties?.["purviewCollection"], - privateLinksEnabled: resource.properties?.["privateLinksEnabled"], - publicNetworkAccess: resource.properties?.["publicNetworkAccess"], - customerManagedKeyEncryptionEnabled: - resource.properties?.["customerManagedKeyEncryptionEnabled"], - customerEncryptionKey: !resource.properties?.customerEncryptionKey - ? undefined - : { - keyVaultUri: - resource.properties?.customerEncryptionKey?.[ - "keyVaultUri" - ], - keyName: - resource.properties?.customerEncryptionKey?.["keyName"], - keyVersion: - resource.properties?.customerEncryptionKey?.[ - "keyVersion" - ], - }, - networkacls: !resource.properties?.networkacls - ? undefined - : { - virtualNetworkRule: resource.properties?.networkacls?.[ - "virtualNetworkRule" - ].map((p) => ({ - id: p["id"], - action: p["action"], - state: p["state"], - })), - ipRules: resource.properties?.networkacls?.["ipRules"].map( - (p) => ({ value: p["value"], action: p["action"] }), - ), - allowedQueryIpRangeList: - resource.properties?.networkacls?.[ - "allowedQueryIpRangeList" - ], - defaultAction: - resource.properties?.networkacls?.["defaultAction"], - }, - managedResourceGroupConfiguration: !resource.properties - ?.managedResourceGroupConfiguration - ? undefined - : { - name: resource.properties - ?.managedResourceGroupConfiguration?.["name"], - location: - resource.properties?.managedResourceGroupConfiguration?.[ - "location" - ], - }, - currentMinorVersion: resource.properties?.["currentMinorVersion"], - }, + ? resource.properties + : dataProductPropertiesSerializer(resource.properties), identity: !resource.identity - ? undefined - : { - type: resource.identity?.["type"], - userAssignedIdentities: - resource.identity?.["userAssignedIdentities"], - }, + ? resource.identity + : managedServiceIdentitySerializer(resource.identity), }, }); } @@ -177,8 +121,8 @@ export async function _createDeserialize( result = result as DataProductsCreateLogicalResponse; return { - location: result.body["location"], tags: result.body["tags"], + location: result.body["location"], id: result.body["id"], name: result.body["name"], type: result.body["type"], @@ -292,8 +236,8 @@ export async function _createDeserialize( identity: !result.body.identity ? undefined : { - tenantId: result.body.identity?.["tenantId"], principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], type: result.body.identity?.["type"], userAssignedIdentities: result.body.identity?.["userAssignedIdentities"], @@ -352,8 +296,8 @@ export async function _getDeserialize( } return { - location: result.body["location"], tags: result.body["tags"], + location: result.body["location"], id: result.body["id"], name: result.body["name"], type: result.body["type"], @@ -467,8 +411,8 @@ export async function _getDeserialize( identity: !result.body.identity ? undefined : { - tenantId: result.body.identity?.["tenantId"], principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], type: result.body.identity?.["type"], userAssignedIdentities: result.body.identity?.["userAssignedIdentities"], @@ -518,24 +462,14 @@ export function _updateSend( ...operationOptionsToRequestParameters(options), body: { identity: !properties.identity - ? undefined - : { - type: properties.identity?.["type"], - userAssignedIdentities: - properties.identity?.["userAssignedIdentities"], - }, - tags: properties["tags"], + ? properties.identity + : managedServiceIdentitySerializer(properties.identity), + tags: !properties.tags + ? properties.tags + : (serializeRecord(properties.tags as any) as any), properties: !properties.properties - ? undefined - : { - owners: properties.properties?.["owners"], - purviewAccount: properties.properties?.["purviewAccount"], - purviewCollection: properties.properties?.["purviewCollection"], - privateLinksEnabled: - properties.properties?.["privateLinksEnabled"], - currentMinorVersion: - properties.properties?.["currentMinorVersion"], - }, + ? properties.properties + : dataProductUpdatePropertiesSerializer(properties.properties), }, }); } @@ -553,8 +487,8 @@ export async function _updateDeserialize( result = result as DataProductsUpdateLogicalResponse; return { - location: result.body["location"], tags: result.body["tags"], + location: result.body["location"], id: result.body["id"], name: result.body["name"], type: result.body["type"], @@ -668,8 +602,8 @@ export async function _updateDeserialize( identity: !result.body.identity ? undefined : { - tenantId: result.body.identity?.["tenantId"], principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], type: result.body.identity?.["type"], userAssignedIdentities: result.body.identity?.["userAssignedIdentities"], @@ -1112,15 +1046,15 @@ export async function _listByResourceGroupDeserialize( result: | DataProductsListByResourceGroup200Response | DataProductsListByResourceGroupDefaultResponse, -): Promise { +): Promise<_DataProductListResult> { if (isUnexpected(result)) { throw createRestError(result); } return { value: result.body["value"].map((p) => ({ - location: p["location"], tags: p["tags"], + location: p["location"], id: p["id"], name: p["name"], type: p["type"], @@ -1220,8 +1154,8 @@ export async function _listByResourceGroupDeserialize( identity: !p.identity ? undefined : { - tenantId: p.identity?.["tenantId"], principalId: p.identity?.["principalId"], + tenantId: p.identity?.["tenantId"], type: p.identity?.["type"], userAssignedIdentities: p.identity?.["userAssignedIdentities"], }, @@ -1275,15 +1209,15 @@ export async function _listBySubscriptionDeserialize( result: | DataProductsListBySubscription200Response | DataProductsListBySubscriptionDefaultResponse, -): Promise { +): Promise<_DataProductListResult> { if (isUnexpected(result)) { throw createRestError(result); } return { value: result.body["value"].map((p) => ({ - location: p["location"], tags: p["tags"], + location: p["location"], id: p["id"], name: p["name"], type: p["type"], @@ -1383,8 +1317,8 @@ export async function _listBySubscriptionDeserialize( identity: !p.identity ? undefined : { - tenantId: p.identity?.["tenantId"], principalId: p.identity?.["principalId"], + tenantId: p.identity?.["tenantId"], type: p.identity?.["type"], userAssignedIdentities: p.identity?.["userAssignedIdentities"], }, diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts index 1153d3e39c..f9f8c5158d 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataProductsCatalogs/index.ts @@ -3,7 +3,7 @@ import { DataProductsCatalog, - DataProductsCatalogListResult, + _DataProductsCatalogListResult, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -132,7 +132,7 @@ export async function _listByResourceGroupDeserialize( result: | DataProductsCatalogsListByResourceGroup200Response | DataProductsCatalogsListByResourceGroupDefaultResponse, -): Promise { +): Promise<_DataProductsCatalogListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -223,7 +223,7 @@ export async function _listBySubscriptionDeserialize( result: | DataProductsCatalogsListBySubscription200Response | DataProductsCatalogsListBySubscriptionDefaultResponse, -): Promise { +): Promise<_DataProductsCatalogListResult> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts index 74f6ce0228..c456278244 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/dataTypes/index.ts @@ -4,11 +4,13 @@ import { getLongRunningPoller } from "../pollingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { + dataTypePropertiesSerializer, + dataTypeUpdatePropertiesSerializer, DataType, DataTypeUpdate, ContainerSaS, ContainerSasToken, - DataTypeListResult, + _DataTypeListResult, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -79,15 +81,8 @@ export function _createSend( ...operationOptionsToRequestParameters(options), body: { properties: !resource.properties - ? undefined - : { - state: resource.properties?.["state"], - storageOutputRetention: - resource.properties?.["storageOutputRetention"], - databaseCacheRetention: - resource.properties?.["databaseCacheRetention"], - databaseRetention: resource.properties?.["databaseRetention"], - }, + ? resource.properties + : dataTypePropertiesSerializer(resource.properties), }, }); } @@ -274,15 +269,8 @@ export function _updateSend( ...operationOptionsToRequestParameters(options), body: { properties: !properties.properties - ? undefined - : { - state: properties.properties?.["state"], - storageOutputRetention: - properties.properties?.["storageOutputRetention"], - databaseCacheRetention: - properties.properties?.["databaseCacheRetention"], - databaseRetention: properties.properties?.["databaseRetention"], - }, + ? properties.properties + : dataTypeUpdatePropertiesSerializer(properties.properties), }, }); } @@ -589,7 +577,7 @@ export async function _listByDataProductDeserialize( result: | DataTypesListByDataProduct200Response | DataTypesListByDataProductDefaultResponse, -): Promise { +): Promise<_DataTypeListResult> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts index 3c21444f2d..12bb62b0e8 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/networkAnalyticsContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { NetworkAnalyticsContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface NetworkAnalyticsClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts index ae7bcb55cc..442cb6579c 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/api/operations/index.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { PagedOperation, Operation } from "../../models/models.js"; +import { Operation, _OperationListResult } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; import { @@ -28,7 +28,7 @@ export function _listSend( export async function _listDeserialize( result: OperationsList200Response | OperationsListDefaultResponse, -): Promise { +): Promise<_OperationListResult> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts index c6780397e8..64cd38d2e9 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProducts/index.ts @@ -41,83 +41,91 @@ import { DataProductsListBySubscriptionOptionalParams, } from "../../models/options.js"; +/** Interface representing a DataProducts operations. */ export interface DataProductsOperations { + /** Create data product resource. */ create: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, resource: DataProduct, options?: DataProductsCreateOptionalParams, ) => PollerLike, DataProduct>; + /** Retrieve data product resource. */ get: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsGetOptionalParams, ) => Promise; + /** Update data product resource. */ update: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, properties: DataProductUpdate, options?: DataProductsUpdateOptionalParams, ) => PollerLike, DataProduct>; + /** Delete data product resource. */ + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsDeleteOptionalParams, ) => PollerLike, void>; + /** Generate sas token for storage account. */ generateStorageAccountSasToken: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: AccountSas, options?: DataProductsGenerateStorageAccountSasTokenOptionalParams, ) => Promise; + /** Initiate key rotation on Data Product. */ rotateKey: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, options?: DataProductsRotateKeyOptionalParams, ) => Promise; + /** Assign role to the data product. */ addUserRole: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentCommonProperties, options?: DataProductsAddUserRoleOptionalParams, ) => Promise; + /** Remove role from the data product. */ removeUserRole: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentDetail, options?: DataProductsRemoveUserRoleOptionalParams, ) => Promise; + /** List user roles associated with the data product. */ listRolesAssignments: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: Record, options?: DataProductsListRolesAssignmentsOptionalParams, ) => Promise; + /** List data products by resource group. */ listByResourceGroup: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsListByResourceGroupOptionalParams, ) => PagedAsyncIterableIterator; + /** List data products by subscription. */ listBySubscription: ( - subscriptionId: string, options?: DataProductsListBySubscriptionOptionalParams, ) => PagedAsyncIterableIterator; } -export function getDataProducts(context: NetworkAnalyticsContext) { +export function getDataProducts( + context: NetworkAnalyticsContext, + subscriptionId: string, +) { return { create: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, resource: DataProduct, @@ -132,14 +140,12 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), get: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsGetOptionalParams, ) => get(context, subscriptionId, resourceGroupName, dataProductName, options), update: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, properties: DataProductUpdate, @@ -154,7 +160,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), delete: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataProductsDeleteOptionalParams, @@ -167,7 +172,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), generateStorageAccountSasToken: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: AccountSas, @@ -182,7 +186,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), rotateKey: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, @@ -197,7 +200,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), addUserRole: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentCommonProperties, @@ -212,7 +214,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), removeUserRole: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: RoleAssignmentDetail, @@ -227,7 +228,6 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), listRolesAssignments: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: Record, @@ -242,13 +242,11 @@ export function getDataProducts(context: NetworkAnalyticsContext) { options, ), listByResourceGroup: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsListByResourceGroupOptionalParams, ) => listByResourceGroup(context, subscriptionId, resourceGroupName, options), listBySubscription: ( - subscriptionId: string, options?: DataProductsListBySubscriptionOptionalParams, ) => listBySubscription(context, subscriptionId, options), }; @@ -256,8 +254,9 @@ export function getDataProducts(context: NetworkAnalyticsContext) { export function getDataProductsOperations( context: NetworkAnalyticsContext, + subscriptionId: string, ): DataProductsOperations { return { - ...getDataProducts(context), + ...getDataProducts(context, subscriptionId), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts index 017a35e7fd..45b70334c9 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataProductsCatalogs/index.ts @@ -15,38 +15,39 @@ import { DataProductsCatalogsListBySubscriptionOptionalParams, } from "../../models/options.js"; +/** Interface representing a DataProductsCatalogs operations. */ export interface DataProductsCatalogsOperations { + /** Retrieve data type resource. */ get: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsGetOptionalParams, ) => Promise; + /** List data catalog by resource group. */ listByResourceGroup: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams, ) => PagedAsyncIterableIterator; + /** List data catalog by subscription. */ listBySubscription: ( - subscriptionId: string, options?: DataProductsCatalogsListBySubscriptionOptionalParams, ) => PagedAsyncIterableIterator; } -export function getDataProductsCatalogs(context: NetworkAnalyticsContext) { +export function getDataProductsCatalogs( + context: NetworkAnalyticsContext, + subscriptionId: string, +) { return { get: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsGetOptionalParams, ) => get(context, subscriptionId, resourceGroupName, options), listByResourceGroup: ( - subscriptionId: string, resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams, ) => listByResourceGroup(context, subscriptionId, resourceGroupName, options), listBySubscription: ( - subscriptionId: string, options?: DataProductsCatalogsListBySubscriptionOptionalParams, ) => listBySubscription(context, subscriptionId, options), }; @@ -54,8 +55,9 @@ export function getDataProductsCatalogs(context: NetworkAnalyticsContext) { export function getDataProductsCatalogsOperations( context: NetworkAnalyticsContext, + subscriptionId: string, ): DataProductsCatalogsOperations { return { - ...getDataProductsCatalogs(context), + ...getDataProductsCatalogs(context, subscriptionId), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts index 7a5bed98f5..fac5453937 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/dataTypes/index.ts @@ -29,65 +29,73 @@ import { DataTypesListByDataProductOptionalParams, } from "../../models/options.js"; +/** Interface representing a DataTypes operations. */ export interface DataTypesOperations { + /** Create data type resource. */ create: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, resource: DataType, options?: DataTypesCreateOptionalParams, ) => PollerLike, DataType>; + /** Retrieve data type resource. */ get: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesGetOptionalParams, ) => Promise; + /** Update data type resource. */ update: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, properties: DataTypeUpdate, options?: DataTypesUpdateOptionalParams, ) => PollerLike, DataType>; + /** Delete data type resource. */ + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, options?: DataTypesDeleteOptionalParams, ) => PollerLike, void>; + /** Delete data for data type. */ deleteData: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, body: Record, options?: DataTypesDeleteDataOptionalParams, ) => PollerLike, void>; + /** Generate sas token for storage container. */ generateStorageContainerSasToken: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, body: ContainerSaS, options?: DataTypesGenerateStorageContainerSasTokenOptionalParams, ) => Promise; + /** List data type by parent resource. */ listByDataProduct: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataTypesListByDataProductOptionalParams, ) => PagedAsyncIterableIterator; } -export function getDataTypes(context: NetworkAnalyticsContext) { +export function getDataTypes( + context: NetworkAnalyticsContext, + subscriptionId: string, +) { return { create: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -104,7 +112,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), get: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -119,7 +126,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), update: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -136,7 +142,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), delete: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -151,7 +156,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), deleteData: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -168,7 +172,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), generateStorageContainerSasToken: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -185,7 +188,6 @@ export function getDataTypes(context: NetworkAnalyticsContext) { options, ), listByDataProduct: ( - subscriptionId: string, resourceGroupName: string, dataProductName: string, options?: DataTypesListByDataProductOptionalParams, @@ -202,8 +204,9 @@ export function getDataTypes(context: NetworkAnalyticsContext) { export function getDataTypesOperations( context: NetworkAnalyticsContext, + subscriptionId: string, ): DataTypesOperations { return { - ...getDataTypes(context), + ...getDataTypes(context, subscriptionId), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts index 2ea697a9d6..93aa25b4f1 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/classic/operations/index.ts @@ -7,7 +7,9 @@ import { list } from "../../api/operations/index.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { OperationsListOptionalParams } from "../../models/options.js"; +/** Interface representing a Operations operations. */ export interface OperationsOperations { + /** List the operations for the provider */ list: ( options?: OperationsListOptionalParams, ) => PagedAsyncIterableIterator; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts index 582a7364da..2d58a157b0 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/index.ts @@ -9,57 +9,59 @@ export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Resource, SystemData, + KnownCreatedByType, CreatedByType, TrackedResource, DataProduct, DataProductProperties, + KnownProvisioningState, ProvisioningState, + KnownControlState, ControlState, EncryptionKeyDetails, DataProductNetworkAcls, VirtualNetworkRule, IPRules, + KnownDefaultAction, DefaultAction, ManagedResourceGroupConfiguration, ConsumptionEndpointsProperties, ManagedServiceIdentity, + KnownManagedServiceIdentityType, ManagedServiceIdentityType, UserAssignedIdentity, - UserAssignedIdentities, ErrorResponse, ErrorDetail, ErrorAdditionalInfo, DataProductUpdate, DataProductUpdateProperties, - ArmOperationStatus, - ResourceProvisioningState, AccountSas, AccountSasToken, KeyVaultInfo, RoleAssignmentCommonProperties, + KnownDataProductUserRole, DataProductUserRole, RoleAssignmentDetail, ListRoleAssignments, - DataProductListResult, ProxyResource, DataType, DataTypeProperties, + KnownDataTypeState, DataTypeState, DataTypeUpdate, DataTypeUpdateProperties, ContainerSaS, ContainerSasToken, - DataTypeListResult, DataProductsCatalog, DataProductsCatalogProperties, PublisherInformation, DataProductInformation, DataProductVersion, - DataProductsCatalogListResult, - PagedOperation, Operation, OperationDisplay, + KnownOrigin, Origin, + KnownActionType, ActionType, Versions, OperationsListOptionalParams, diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts index 55b6b705ea..9b9cad862f 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/index.ts @@ -4,57 +4,59 @@ export { Resource, SystemData, + KnownCreatedByType, CreatedByType, TrackedResource, DataProduct, DataProductProperties, + KnownProvisioningState, ProvisioningState, + KnownControlState, ControlState, EncryptionKeyDetails, DataProductNetworkAcls, VirtualNetworkRule, IPRules, + KnownDefaultAction, DefaultAction, ManagedResourceGroupConfiguration, ConsumptionEndpointsProperties, ManagedServiceIdentity, + KnownManagedServiceIdentityType, ManagedServiceIdentityType, UserAssignedIdentity, - UserAssignedIdentities, ErrorResponse, ErrorDetail, ErrorAdditionalInfo, DataProductUpdate, DataProductUpdateProperties, - ArmOperationStatus, - ResourceProvisioningState, AccountSas, AccountSasToken, KeyVaultInfo, RoleAssignmentCommonProperties, + KnownDataProductUserRole, DataProductUserRole, RoleAssignmentDetail, ListRoleAssignments, - DataProductListResult, ProxyResource, DataType, DataTypeProperties, + KnownDataTypeState, DataTypeState, DataTypeUpdate, DataTypeUpdateProperties, ContainerSaS, ContainerSasToken, - DataTypeListResult, DataProductsCatalog, DataProductsCatalogProperties, PublisherInformation, DataProductInformation, DataProductVersion, - DataProductsCatalogListResult, - PagedOperation, Operation, OperationDisplay, + KnownOrigin, Origin, + KnownActionType, ActionType, Versions, } from "./models.js"; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts index 5af6ebdf45..7f0eb70416 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/models.ts @@ -1,7 +1,31 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Common properties for all Azure Resource Manager resources. */ +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { + TrackedResource as TrackedResourceRest, + DataProduct as DataProductRest, + DataProductProperties as DataProductPropertiesRest, + EncryptionKeyDetails as EncryptionKeyDetailsRest, + DataProductNetworkAcls as DataProductNetworkAclsRest, + VirtualNetworkRule as VirtualNetworkRuleRest, + IPRules as IPRulesRest, + ManagedResourceGroupConfiguration as ManagedResourceGroupConfigurationRest, + ManagedServiceIdentity as ManagedServiceIdentityRest, + DataProductUpdate as DataProductUpdateRest, + DataProductUpdateProperties as DataProductUpdatePropertiesRest, + AccountSas as AccountSasRest, + KeyVaultInfo as KeyVaultInfoRest, + RoleAssignmentCommonProperties as RoleAssignmentCommonPropertiesRest, + RoleAssignmentDetail as RoleAssignmentDetailRest, + DataType as DataTypeRest, + DataTypeProperties as DataTypePropertiesRest, + DataTypeUpdate as DataTypeUpdateRest, + DataTypeUpdateProperties as DataTypeUpdatePropertiesRest, + ContainerSaS as ContainerSaSRest, +} from "../rest/index.js"; + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource { /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ readonly id?: string; @@ -13,32 +37,65 @@ export interface Resource { readonly systemData?: SystemData; } +export function resourceSerializer(item: Resource) { + return item as any; +} + /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ - readonly createdBy?: string; + createdBy?: string; /** The type of identity that created the resource. */ - readonly createdByType?: CreatedByType; - /** The type of identity that created the resource. */ - readonly createdAt?: Date; + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date; /** The identity that last modified the resource. */ - readonly lastModifiedBy?: string; + lastModifiedBy?: string; /** The type of identity that last modified the resource. */ - readonly lastModifiedByType?: CreatedByType; + lastModifiedByType?: CreatedByType; /** The timestamp of resource last modification (UTC) */ - readonly lastModifiedAt?: Date; -} - -/** The kind of entity that created the resource. */ -/** "User", "Application", "ManagedIdentity", "Key" */ + lastModifiedAt?: Date; +} + +/** Known values of {@link CreatedByType} that the service accepts. */ +export enum KnownCreatedByType { + /** User */ + User = "User", + /** Application */ + Application = "Application", + /** ManagedIdentity */ + ManagedIdentity = "ManagedIdentity", + /** Key */ + Key = "Key", +} + +/** + * The kind of entity that created the resource. \ + * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **User** \ + * **Application** \ + * **ManagedIdentity** \ + * **Key** + */ export type CreatedByType = string; /** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ export interface TrackedResource extends Resource { - /** The geo-location where the resource lives */ - location: string; /** Resource tags. */ tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +export function trackedResourceSerializer( + item: TrackedResource, +): TrackedResourceRest { + return { + tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + location: item["location"], + }; } /** The data product resource. */ @@ -49,6 +106,19 @@ export interface DataProduct extends TrackedResource { identity?: ManagedServiceIdentity; } +export function dataProductSerializer(item: DataProduct): DataProductRest { + return { + tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + location: item["location"], + properties: !item.properties + ? item.properties + : dataProductPropertiesSerializer(item.properties), + identity: !item.identity + ? item.identity + : managedServiceIdentitySerializer(item.identity), + }; +} + /** The data product properties. */ export interface DataProductProperties { /** The resource GUID property of the data product resource. */ @@ -93,11 +163,85 @@ export interface DataProductProperties { readonly keyVaultUrl?: string; } -/** The status of the current operation. */ -/** "Succeeded", "Failed", "Canceled", "Provisioning", "Updating", "Deleting", "Accepted" */ +export function dataProductPropertiesSerializer( + item: DataProductProperties, +): DataProductPropertiesRest { + return { + publisher: item["publisher"], + product: item["product"], + majorVersion: item["majorVersion"], + owners: item["owners"], + redundancy: item["redundancy"], + purviewAccount: item["purviewAccount"], + purviewCollection: item["purviewCollection"], + privateLinksEnabled: item["privateLinksEnabled"], + publicNetworkAccess: item["publicNetworkAccess"], + customerManagedKeyEncryptionEnabled: + item["customerManagedKeyEncryptionEnabled"], + customerEncryptionKey: !item.customerEncryptionKey + ? item.customerEncryptionKey + : encryptionKeyDetailsSerializer(item.customerEncryptionKey), + networkacls: !item.networkacls + ? item.networkacls + : dataProductNetworkAclsSerializer(item.networkacls), + managedResourceGroupConfiguration: !item.managedResourceGroupConfiguration + ? item.managedResourceGroupConfiguration + : managedResourceGroupConfigurationSerializer( + item.managedResourceGroupConfiguration, + ), + currentMinorVersion: item["currentMinorVersion"], + }; +} + +/** Known values of {@link ProvisioningState} that the service accepts. */ +export enum KnownProvisioningState { + /** Succeeded */ + Succeeded = "Succeeded", + /** Failed */ + Failed = "Failed", + /** Canceled */ + Canceled = "Canceled", + /** Provisioning */ + Provisioning = "Provisioning", + /** Updating */ + Updating = "Updating", + /** Deleting */ + Deleting = "Deleting", + /** Accepted */ + Accepted = "Accepted", +} + +/** + * The status of the current operation. \ + * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Succeeded** \ + * **Failed** \ + * **Canceled** \ + * **Provisioning** \ + * **Updating** \ + * **Deleting** \ + * **Accepted** + */ export type ProvisioningState = string; -/** The data type state */ -/** "Enabled", "Disabled" */ + +/** Known values of {@link ControlState} that the service accepts. */ +export enum KnownControlState { + /** Enabled */ + Enabled = "Enabled", + /** Disabled */ + Disabled = "Disabled", +} + +/** + * The data type state \ + * {@link KnownControlState} can be used interchangeably with ControlState, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Enabled** \ + * **Disabled** + */ export type ControlState = string; /** Encryption key details. */ @@ -110,6 +254,16 @@ export interface EncryptionKeyDetails { keyVersion: string; } +export function encryptionKeyDetailsSerializer( + item: EncryptionKeyDetails, +): EncryptionKeyDetailsRest { + return { + keyVaultUri: item["keyVaultUri"], + keyName: item["keyName"], + keyVersion: item["keyVersion"], + }; +} + /** Data Product Network rule set */ export interface DataProductNetworkAcls { /** Virtual Network Rule */ @@ -122,6 +276,19 @@ export interface DataProductNetworkAcls { defaultAction: DefaultAction; } +export function dataProductNetworkAclsSerializer( + item: DataProductNetworkAcls, +): DataProductNetworkAclsRest { + return { + virtualNetworkRule: item["virtualNetworkRule"].map( + virtualNetworkRuleSerializer, + ), + ipRules: item["ipRules"].map(iPRulesSerializer), + allowedQueryIpRangeList: item["allowedQueryIpRangeList"], + defaultAction: item["defaultAction"], + }; +} + /** Virtual Network Rule */ export interface VirtualNetworkRule { /** Resource ID of a subnet */ @@ -132,6 +299,16 @@ export interface VirtualNetworkRule { state?: string; } +export function virtualNetworkRuleSerializer( + item: VirtualNetworkRule, +): VirtualNetworkRuleRest { + return { + id: item["id"], + action: item["action"], + state: item["state"], + }; +} + /** IP rule with specific IP or IP range in CIDR format. */ export interface IPRules { /** IP Rules Value */ @@ -140,8 +317,29 @@ export interface IPRules { action: string; } -/** Specifies the default action of allow or deny when no other rules match. */ -/** "Allow", "Deny" */ +export function iPRulesSerializer(item: IPRules): IPRulesRest { + return { + value: item["value"], + action: item["action"], + }; +} + +/** Known values of {@link DefaultAction} that the service accepts. */ +export enum KnownDefaultAction { + /** Allow */ + Allow = "Allow", + /** Deny */ + Deny = "Deny", +} + +/** + * Specifies the default action of allow or deny when no other rules match. \ + * {@link KnownDefaultAction} can be used interchangeably with DefaultAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Allow** \ + * **Deny** + */ export type DefaultAction = string; /** ManagedResourceGroup related properties */ @@ -152,6 +350,15 @@ export interface ManagedResourceGroupConfiguration { location: string; } +export function managedResourceGroupConfigurationSerializer( + item: ManagedResourceGroupConfiguration, +): ManagedResourceGroupConfigurationRest { + return { + name: item["name"], + location: item["location"], + }; +} + /** Details of Consumption Properties */ export interface ConsumptionEndpointsProperties { /** Ingestion url to upload the data. */ @@ -168,33 +375,67 @@ export interface ConsumptionEndpointsProperties { readonly queryResourceId?: string; } -/** The properties of the managed service identities assigned to this resource. */ +/** Managed service identity (system assigned and/or user assigned identities) */ export interface ManagedServiceIdentity { - /** The Active Directory tenant id of the principal. */ - readonly tenantId?: string; - /** The active directory identifier of this principal. */ + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; /** The type of managed identity assigned to this resource. */ type: ManagedServiceIdentityType; /** The identities assigned to this resource by the user. */ - userAssignedIdentities?: UserAssignedIdentities; -} - -/** The kind of managed identity assigned to this resource. */ -/** "None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned" */ + userAssignedIdentities?: Record; +} + +export function managedServiceIdentitySerializer( + item: ManagedServiceIdentity, +): ManagedServiceIdentityRest { + return { + type: item["type"], + userAssignedIdentities: !item.userAssignedIdentities + ? item.userAssignedIdentities + : (serializeRecord( + item.userAssignedIdentities as any, + userAssignedIdentitySerializer, + ) as any), + }; +} + +/** Known values of {@link ManagedServiceIdentityType} that the service accepts. */ +export enum KnownManagedServiceIdentityType { + /** None */ + None = "None", + /** SystemAssigned */ + SystemAssigned = "SystemAssigned", + /** UserAssigned */ + UserAssigned = "UserAssigned", + /** SystemAssigned,UserAssigned */ + "SystemAssigned,UserAssigned" = "SystemAssigned,UserAssigned", +} + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). \ + * {@link KnownManagedServiceIdentityType} can be used interchangeably with ManagedServiceIdentityType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **None** \ + * **SystemAssigned** \ + * **UserAssigned** \ + * **SystemAssigned,UserAssigned** + */ export type ManagedServiceIdentityType = string; -/** A managed identity assigned by the user. */ +/** User assigned identity properties */ export interface UserAssignedIdentity { - /** The active directory client identifier for this principal. */ - clientId?: string; - /** The active directory identifier for this principal. */ - principalId?: string; + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; } -/** The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests.", */ -export interface UserAssignedIdentities - extends Record {} +export function userAssignedIdentitySerializer(item: UserAssignedIdentity) { + return item as any; +} /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. */ export interface ErrorResponse { @@ -233,6 +474,20 @@ export interface DataProductUpdate { properties?: DataProductUpdateProperties; } +export function dataProductUpdateSerializer( + item: DataProductUpdate, +): DataProductUpdateRest { + return { + identity: !item.identity + ? item.identity + : managedServiceIdentitySerializer(item.identity), + tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + properties: !item.properties + ? item.properties + : dataProductUpdatePropertiesSerializer(item.properties), + }; +} + /** The updatable properties of the DataProduct. */ export interface DataProductUpdateProperties { /** List of name or email associated with data product resource deployment. */ @@ -247,26 +502,18 @@ export interface DataProductUpdateProperties { currentMinorVersion?: string; } -/** Standard Azure Resource Manager operation status response */ -export interface ArmOperationStatus { - /** The operation status */ - status: ResourceProvisioningState; - /** The name of the operationStatus resource */ - readonly name?: string; - /** Operation start time */ - readonly startTime?: Date; - /** Operation complete time */ - readonly endTime?: Date; - /** The progress made toward completing the operation */ - readonly percentComplete?: number; - /** Errors that occurred if the operation ended with Canceled or Failed status */ - readonly error?: ErrorDetail; +export function dataProductUpdatePropertiesSerializer( + item: DataProductUpdateProperties, +): DataProductUpdatePropertiesRest { + return { + owners: item["owners"], + purviewAccount: item["purviewAccount"], + purviewCollection: item["purviewCollection"], + privateLinksEnabled: item["privateLinksEnabled"], + currentMinorVersion: item["currentMinorVersion"], + }; } -/** The provisioning state of a resource type. */ -/** "Succeeded", "Failed", "Canceled" */ -export type ResourceProvisioningState = string; - /** The details for storage account sas creation. */ export interface AccountSas { /** Sas token start timestamp. */ @@ -277,6 +524,14 @@ export interface AccountSas { ipAddress: string; } +export function accountSasSerializer(item: AccountSas): AccountSasRest { + return { + startTimeStamp: item["startTimeStamp"].toISOString(), + expiryTimeStamp: item["expiryTimeStamp"].toISOString(), + ipAddress: item["ipAddress"], + }; +} + /** Details of storage account sas token . */ export interface AccountSasToken { /** Field to specify storage account sas token. */ @@ -289,6 +544,12 @@ export interface KeyVaultInfo { keyVaultUrl: string; } +export function keyVaultInfoSerializer(item: KeyVaultInfo): KeyVaultInfoRest { + return { + keyVaultUrl: item["keyVaultUrl"], + }; +} + /** The details for role assignment common properties. */ export interface RoleAssignmentCommonProperties { /** Role Id of the Built-In Role */ @@ -305,8 +566,35 @@ export interface RoleAssignmentCommonProperties { role: DataProductUserRole; } -/** The data type state */ -/** "Reader", "SensitiveReader" */ +export function roleAssignmentCommonPropertiesSerializer( + item: RoleAssignmentCommonProperties, +): RoleAssignmentCommonPropertiesRest { + return { + roleId: item["roleId"], + principalId: item["principalId"], + userName: item["userName"], + dataTypeScope: item["dataTypeScope"], + principalType: item["principalType"], + role: item["role"], + }; +} + +/** Known values of {@link DataProductUserRole} that the service accepts. */ +export enum KnownDataProductUserRole { + /** Reader */ + Reader = "Reader", + /** SensitiveReader */ + SensitiveReader = "SensitiveReader", +} + +/** + * The data type state \ + * {@link KnownDataProductUserRole} can be used interchangeably with DataProductUserRole, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Reader** \ + * **SensitiveReader** + */ export type DataProductUserRole = string; /** The details for role assignment response. */ @@ -327,6 +615,20 @@ export interface RoleAssignmentDetail { roleAssignmentId: string; } +export function roleAssignmentDetailSerializer( + item: RoleAssignmentDetail, +): RoleAssignmentDetailRest { + return { + roleId: item["roleId"], + principalId: item["principalId"], + userName: item["userName"], + dataTypeScope: item["dataTypeScope"], + principalType: item["principalType"], + role: item["role"], + roleAssignmentId: item["roleAssignmentId"], + }; +} + /** list role assignments. */ export interface ListRoleAssignments { /** Count of role assignments. */ @@ -336,22 +638,34 @@ export interface ListRoleAssignments { } /** The response of a DataProduct list operation. */ -export interface DataProductListResult { +export interface _DataProductListResult { /** The DataProduct items on this page */ value: DataProduct[]; /** The link to the next page of items */ nextLink?: string; } -/** The base proxy resource. */ +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ export interface ProxyResource extends Resource {} +export function proxyResourceSerializer(item: ProxyResource) { + return item as any; +} + /** The data type resource. */ export interface DataType extends ProxyResource { /** The resource-specific properties for this resource. */ properties?: DataTypeProperties; } +export function dataTypeSerializer(item: DataType): DataTypeRest { + return { + properties: !item.properties + ? item.properties + : dataTypePropertiesSerializer(item.properties), + }; +} + /** The data type properties */ export interface DataTypeProperties { /** Latest provisioning state of data product. */ @@ -370,8 +684,33 @@ export interface DataTypeProperties { readonly visualizationUrl?: string; } -/** The data type state */ -/** "Stopped", "Running" */ +export function dataTypePropertiesSerializer( + item: DataTypeProperties, +): DataTypePropertiesRest { + return { + state: item["state"], + storageOutputRetention: item["storageOutputRetention"], + databaseCacheRetention: item["databaseCacheRetention"], + databaseRetention: item["databaseRetention"], + }; +} + +/** Known values of {@link DataTypeState} that the service accepts. */ +export enum KnownDataTypeState { + /** Stopped */ + Stopped = "Stopped", + /** Running */ + Running = "Running", +} + +/** + * The data type state \ + * {@link KnownDataTypeState} can be used interchangeably with DataTypeState, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Stopped** \ + * **Running** + */ export type DataTypeState = string; /** The type used for update operations of the DataType. */ @@ -379,6 +718,16 @@ export interface DataTypeUpdate { properties?: DataTypeUpdateProperties; } +export function dataTypeUpdateSerializer( + item: DataTypeUpdate, +): DataTypeUpdateRest { + return { + properties: !item.properties + ? item.properties + : dataTypeUpdatePropertiesSerializer(item.properties), + }; +} + /** The updatable properties of the DataType. */ export interface DataTypeUpdateProperties { /** State of data type. */ @@ -391,6 +740,17 @@ export interface DataTypeUpdateProperties { databaseRetention?: number; } +export function dataTypeUpdatePropertiesSerializer( + item: DataTypeUpdateProperties, +): DataTypeUpdatePropertiesRest { + return { + state: item["state"], + storageOutputRetention: item["storageOutputRetention"], + databaseCacheRetention: item["databaseCacheRetention"], + databaseRetention: item["databaseRetention"], + }; +} + /** The details for container sas creation. */ export interface ContainerSaS { /** Sas token start timestamp. */ @@ -401,6 +761,14 @@ export interface ContainerSaS { ipAddress: string; } +export function containerSaSSerializer(item: ContainerSaS): ContainerSaSRest { + return { + startTimeStamp: item["startTimeStamp"].toISOString(), + expiryTimeStamp: item["expiryTimeStamp"].toISOString(), + ipAddress: item["ipAddress"], + }; +} + /** Details of storage container account sas token . */ export interface ContainerSasToken { /** Field to specify storage container sas token. */ @@ -408,7 +776,7 @@ export interface ContainerSasToken { } /** The response of a DataType list operation. */ -export interface DataTypeListResult { +export interface _DataTypeListResult { /** The DataType items on this page */ value: DataType[]; /** The link to the next page of items */ @@ -454,7 +822,7 @@ export interface DataProductVersion { } /** The response of a DataProductsCatalog list operation. */ -export interface DataProductsCatalogListResult { +export interface _DataProductsCatalogListResult { /** The DataProductsCatalog items on this page */ value: DataProductsCatalog[]; /** The link to the next page of items */ @@ -462,7 +830,7 @@ export interface DataProductsCatalogListResult { } /** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */ -export interface PagedOperation { +export interface _OperationListResult { /** The Operation items on this page */ value: Operation[]; /** The link to the next page of items */ @@ -495,12 +863,40 @@ export interface OperationDisplay { description?: string; } -/** The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" */ -/** "user", "system", "user,system" */ +/** Known values of {@link Origin} that the service accepts. */ +export enum KnownOrigin { + /** user */ + user = "user", + /** system */ + system = "system", + /** user,system */ + "user,system" = "user,system", +} + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" \ + * {@link KnownOrigin} can be used interchangeably with Origin, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **user** \ + * **system** \ + * **user,system** + */ export type Origin = string; -/** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ -/** "Internal" */ + +/** Known values of {@link ActionType} that the service accepts. */ +export enum KnownActionType { + /** Internal */ + Internal = "Internal", +} + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. \ + * {@link KnownActionType} can be used interchangeably with ActionType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Internal** + */ export type ActionType = string; /** The available API versions for the Microsoft.NetworkAnalytics RP. */ -/** */ export type Versions = "2023-11-15"; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts index b9822bea3d..1bdac786f2 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/models/options.ts @@ -3,78 +3,100 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface OperationsListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsCatalogsGetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsCatalogsListByResourceGroupOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsCatalogsListBySubscriptionOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataTypesCreateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataTypesGetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataTypesUpdateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataTypesDeleteOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataTypesDeleteDataOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataTypesGenerateStorageContainerSasTokenOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataTypesListByDataProductOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsCreateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataProductsGetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsUpdateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataProductsDeleteOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } +/** Optional parameters. */ export interface DataProductsGenerateStorageAccountSasTokenOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsRotateKeyOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsAddUserRoleOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsRemoveUserRoleOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsListRolesAssignmentsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsListByResourceGroupOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DataProductsListBySubscriptionOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts index d8b59e1340..7a911a9eb5 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/networkAnalyticsClient.ts @@ -34,14 +34,18 @@ export class NetworkAnalyticsClient { constructor( credential: TokenCredential, + subscriptionId: string, options: NetworkAnalyticsClientOptions = {}, ) { this._client = createNetworkAnalytics(credential, options); this.pipeline = this._client.pipeline; this.operations = getOperationsOperations(this._client); - this.dataProductsCatalogs = getDataProductsCatalogsOperations(this._client); - this.dataTypes = getDataTypesOperations(this._client); - this.dataProducts = getDataProductsOperations(this._client); + this.dataProductsCatalogs = getDataProductsCatalogsOperations( + this._client, + subscriptionId, + ); + this.dataTypes = getDataTypesOperations(this._client, subscriptionId); + this.dataProducts = getDataProductsOperations(this._client, subscriptionId); } /** The operation groups for Operations */ diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/models.ts index 570b5f0aa6..03766464ae 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/models.ts @@ -37,21 +37,34 @@ export interface DataProductVersion { version: string; } -/** The base proxy resource. */ +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ export interface ProxyResource extends Resource {} -/** Common properties for all Azure Resource Manager resources. */ +/** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface Resource {} /** Metadata pertaining to creation and last modification of the resource. */ -export interface SystemData {} +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** The type of identity that created the resource. */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date | string; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** The type of identity that last modified the resource. */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date | string; +} /** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ export interface TrackedResource extends Resource { - /** The geo-location where the resource lives */ - location: string; /** Resource tags. */ tags?: Record; + /** The geo-location where the resource lives */ + location: string; } /** The data product resource. */ @@ -145,24 +158,72 @@ export interface ManagedResourceGroupConfiguration { /** Details of Consumption Properties */ export interface ConsumptionEndpointsProperties {} -/** The properties of the managed service identities assigned to this resource. */ +/** Managed service identity (system assigned and/or user assigned identities) */ export interface ManagedServiceIdentity { /** The type of managed identity assigned to this resource. */ type: ManagedServiceIdentityType; /** The identities assigned to this resource by the user. */ - userAssignedIdentities?: UserAssignedIdentities; -} - -/** The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests.", */ -export interface UserAssignedIdentities - extends Record {} - -/** A managed identity assigned by the user. */ -export interface UserAssignedIdentity { - /** The active directory client identifier for this principal. */ - clientId?: string; - /** The active directory identifier for this principal. */ - principalId?: string; + userAssignedIdentities?: Record; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentity {} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySet extends TrackedResource { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: Identity; + sku?: Sku; + plan?: Plan; +} + +/** Identity for the resource. */ +export interface Identity { + /** The identity type. */ + type?: ResourceIdentityType; +} + +/** The resource model definition representing SKU */ +export interface Sku { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTier; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface Plan { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; } /** The base extension resource. */ @@ -171,27 +232,34 @@ export interface ExtensionResource extends Resource {} /** The resource model definition for an Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource {} +/** A private link resource. */ +export interface PrivateLinkResource extends Resource { + /** Resource properties. */ + properties?: PrivateLinkResourceProperties; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourceProperties { + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; +} + /** The private endpoint connection resource */ -export interface PrivateEndpointConnection extends ProxyResource { +export interface PrivateEndpointConnection extends Resource { /** The private endpoint connection properties */ properties?: PrivateEndpointConnectionProperties; } -/** Properties of he private endpoint connection resource */ +/** Properties of the private endpoint connection. */ export interface PrivateEndpointConnectionProperties { - /** The private endpoint resource */ + /** The private endpoint resource. */ privateEndpoint?: PrivateEndpoint; /** A collection of information about the state of the connection between service consumer and provider. */ privateLinkServiceConnectionState: PrivateLinkServiceConnectionState; - /** The provisioning state of the private endpoint connection resource. */ - provisioningState?: PrivateEndpointConnectionProvisioningState; } -/** The private endpoint resource */ -export interface PrivateEndpoint { - /** The resource identifier for private endpoint */ - id?: string; -} +/** The Private Endpoint resource. */ +export interface PrivateEndpoint {} /** A collection of information about the state of the connection between service consumer and provider. */ export interface PrivateLinkServiceConnectionState { @@ -203,17 +271,6 @@ export interface PrivateLinkServiceConnectionState { actionsRequired?: string; } -export interface PrivateLinkResource extends ProxyResource { - /** Properties of the private link resource. */ - properties?: PrivateLinkResourceProperties; -} - -/** Properties of a private link resource. */ -export interface PrivateLinkResourceProperties { - /** The private link resource private link DNS zone name. */ - requiredZoneNames?: string[]; -} - /** The data type resource. */ export interface DataType extends ProxyResource { /** The resource-specific properties for this resource. */ @@ -333,51 +390,24 @@ export interface RoleAssignmentDetail { } /** Alias for ProvisioningState */ -export type ProvisioningState = - | string - | "Succeeded" - | "Failed" - | "Canceled" - | "Provisioning" - | "Updating" - | "Deleting" - | "Accepted"; +export type ProvisioningState = string; /** Alias for CreatedByType */ -export type CreatedByType = - | "User" - | "Application" - | "ManagedIdentity" - | "Key" - | string; +export type CreatedByType = string; /** Alias for ControlState */ -export type ControlState = string | "Enabled" | "Disabled"; +export type ControlState = string; /** Alias for DefaultAction */ -export type DefaultAction = string | "Allow" | "Deny"; +export type DefaultAction = string; /** Alias for ManagedServiceIdentityType */ -export type ManagedServiceIdentityType = - | "None" - | "SystemAssigned" - | "UserAssigned" - | "SystemAssigned, UserAssigned" - | string; +export type ManagedServiceIdentityType = string; +/** Alias for ResourceIdentityType */ +export type ResourceIdentityType = "SystemAssigned"; +/** Alias for SkuTier */ +export type SkuTier = "Free" | "Basic" | "Standard" | "Premium"; /** Alias for PrivateEndpointServiceConnectionStatus */ -export type PrivateEndpointServiceConnectionStatus = - | "Pending" - | "Approved" - | "Rejected" - | string; -/** Alias for ResourceProvisioningState */ -export type ResourceProvisioningState = - | "Succeeded" - | "Failed" - | "Canceled" - | string; +export type PrivateEndpointServiceConnectionStatus = string; /** Alias for PrivateEndpointConnectionProvisioningState */ -export type PrivateEndpointConnectionProvisioningState = - | ResourceProvisioningState - | "Creating" - | "Deleting"; +export type PrivateEndpointConnectionProvisioningState = string; /** Alias for DataTypeState */ -export type DataTypeState = string | "Stopped" | "Running"; +export type DataTypeState = string; /** Alias for DataProductUserRole */ -export type DataProductUserRole = string | "Reader" | "SensitiveReader"; +export type DataProductUserRole = string; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/networkAnalyticsClient.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/networkAnalyticsClient.ts index 18f17548d5..51f673ab7e 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/networkAnalyticsClient.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/networkAnalyticsClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; import { NetworkAnalyticsContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface NetworkAnalyticsContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `NetworkAnalyticsContext` * @param credentials - uniquely identify client credential @@ -13,11 +19,13 @@ import { NetworkAnalyticsContext } from "./clientDefinitions.js"; */ export default function createClient( credentials: TokenCredential, - options: ClientOptions = {}, + { + apiVersion = "2023-11-15", + ...options + }: NetworkAnalyticsContextOptions = {}, ): NetworkAnalyticsContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; - options.apiVersion = options.apiVersion ?? "2023-11-15"; const userAgentInfo = `azsdk-js-arm-networkanalytics-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -35,12 +43,27 @@ export default function createClient( scopes: options.credentials?.scopes ?? [`${endpointUrl}/.default`], }, }; - const client = getClient( endpointUrl, credentials, options, ) as NetworkAnalyticsContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); return client; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/outputModels.ts index c63010bf15..7ef3cec54d 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/outputModels.ts @@ -95,10 +95,10 @@ export interface DataProductVersionOutput { version: string; } -/** The base proxy resource. */ +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ export interface ProxyResourceOutput extends ResourceOutput {} -/** Common properties for all Azure Resource Manager resources. */ +/** Common fields that are returned in the response for all Azure Resource Manager resources */ export interface ResourceOutput { /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ readonly id?: string; @@ -113,25 +113,25 @@ export interface ResourceOutput { /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemDataOutput { /** The identity that created the resource. */ - readonly createdBy?: string; + createdBy?: string; /** The type of identity that created the resource. */ - readonly createdByType?: CreatedByTypeOutput; - /** The type of identity that created the resource. */ - readonly createdAt?: string; + createdByType?: CreatedByTypeOutput; + /** The timestamp of resource creation (UTC). */ + createdAt?: string; /** The identity that last modified the resource. */ - readonly lastModifiedBy?: string; + lastModifiedBy?: string; /** The type of identity that last modified the resource. */ - readonly lastModifiedByType?: CreatedByTypeOutput; + lastModifiedByType?: CreatedByTypeOutput; /** The timestamp of resource last modification (UTC) */ - readonly lastModifiedAt?: string; + lastModifiedAt?: string; } /** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ export interface TrackedResourceOutput extends ResourceOutput { - /** The geo-location where the resource lives */ - location: string; /** Resource tags. */ tags?: Record; + /** The geo-location where the resource lives */ + location: string; } /** The data product resource. */ @@ -250,28 +250,86 @@ export interface ConsumptionEndpointsPropertiesOutput { readonly queryResourceId?: string; } -/** The properties of the managed service identities assigned to this resource. */ +/** Managed service identity (system assigned and/or user assigned identities) */ export interface ManagedServiceIdentityOutput { - /** The Active Directory tenant id of the principal. */ - readonly tenantId?: string; - /** The active directory identifier of this principal. */ + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; /** The type of managed identity assigned to this resource. */ type: ManagedServiceIdentityTypeOutput; /** The identities assigned to this resource by the user. */ - userAssignedIdentities?: UserAssignedIdentitiesOutput; + userAssignedIdentities?: Record; } -/** The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests.", */ -export interface UserAssignedIdentitiesOutput - extends Record {} - -/** A managed identity assigned by the user. */ +/** User assigned identity properties */ export interface UserAssignedIdentityOutput { - /** The active directory client identifier for this principal. */ - clientId?: string; - /** The active directory identifier for this principal. */ - principalId?: string; + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; +} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySetOutput + extends TrackedResourceOutput { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: IdentityOutput; + sku?: SkuOutput; + plan?: PlanOutput; +} + +/** Identity for the resource. */ +export interface IdentityOutput { + /** The principal ID of resource identity. The value must be an UUID. */ + readonly principalId?: string; + /** The tenant ID of resource. The value must be an UUID. */ + readonly tenantId?: string; + /** The identity type. */ + type?: ResourceIdentityTypeOutput; +} + +/** The resource model definition representing SKU */ +export interface SkuOutput { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTierOutput; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface PlanOutput { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; } /** The base extension resource. */ @@ -280,31 +338,45 @@ export interface ExtensionResourceOutput extends ResourceOutput {} /** The resource model definition for an Azure Resource Manager resource with an etag. */ export interface AzureEntityResourceOutput extends ResourceOutput { /** Resource Etag. */ - readonly etag: string; + readonly etag?: string; +} + +/** A private link resource. */ +export interface PrivateLinkResourceOutput extends ResourceOutput { + /** Resource properties. */ + properties?: PrivateLinkResourcePropertiesOutput; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourcePropertiesOutput { + /** The private link resource group id. */ + readonly groupId?: string; + /** The private link resource required member names. */ + readonly requiredMembers?: string[]; + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; } /** The private endpoint connection resource */ -export interface PrivateEndpointConnectionOutput extends ProxyResourceOutput { +export interface PrivateEndpointConnectionOutput extends ResourceOutput { /** The private endpoint connection properties */ properties?: PrivateEndpointConnectionPropertiesOutput; } -/** Properties of he private endpoint connection resource */ +/** Properties of the private endpoint connection. */ export interface PrivateEndpointConnectionPropertiesOutput { - /** The group identifiers for the private endpoint resource */ - readonly groupIds?: string[]; - /** The private endpoint resource */ + /** The private endpoint resource. */ privateEndpoint?: PrivateEndpointOutput; /** A collection of information about the state of the connection between service consumer and provider. */ privateLinkServiceConnectionState: PrivateLinkServiceConnectionStateOutput; /** The provisioning state of the private endpoint connection resource. */ - provisioningState?: PrivateEndpointConnectionProvisioningStateOutput; + readonly provisioningState?: PrivateEndpointConnectionProvisioningStateOutput; } -/** The private endpoint resource */ +/** The Private Endpoint resource. */ export interface PrivateEndpointOutput { /** The resource identifier for private endpoint */ - id?: string; + readonly id?: string; } /** A collection of information about the state of the connection between service consumer and provider. */ @@ -317,21 +389,6 @@ export interface PrivateLinkServiceConnectionStateOutput { actionsRequired?: string; } -export interface PrivateLinkResourceOutput extends ProxyResourceOutput { - /** Properties of the private link resource. */ - properties?: PrivateLinkResourcePropertiesOutput; -} - -/** Properties of a private link resource. */ -export interface PrivateLinkResourcePropertiesOutput { - /** The private link resource group id. */ - readonly groupId?: string; - /** The private link resource required member names. */ - readonly requiredMembers?: string[]; - /** The private link resource private link DNS zone name. */ - requiredZoneNames?: string[]; -} - /** The data type resource. */ export interface DataTypeOutput extends ProxyResourceOutput { /** The resource-specific properties for this resource. */ @@ -395,64 +452,37 @@ export interface ListRoleAssignmentsOutput { } /** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */ -export type PagedOperationOutput = Paged; +export type OperationListResultOutput = Paged; /** Alias for OriginOutput */ -export type OriginOutput = "user" | "system" | "user,system" | string; +export type OriginOutput = string; /** Alias for ActionTypeOutput */ -export type ActionTypeOutput = "Internal" | string; +export type ActionTypeOutput = string; /** Alias for ProvisioningStateOutput */ -export type ProvisioningStateOutput = - | string - | "Succeeded" - | "Failed" - | "Canceled" - | "Provisioning" - | "Updating" - | "Deleting" - | "Accepted"; +export type ProvisioningStateOutput = string; /** Alias for CreatedByTypeOutput */ -export type CreatedByTypeOutput = - | "User" - | "Application" - | "ManagedIdentity" - | "Key" - | string; +export type CreatedByTypeOutput = string; /** Alias for ControlStateOutput */ -export type ControlStateOutput = string | "Enabled" | "Disabled"; +export type ControlStateOutput = string; /** Alias for DefaultActionOutput */ -export type DefaultActionOutput = string | "Allow" | "Deny"; +export type DefaultActionOutput = string; /** Alias for ManagedServiceIdentityTypeOutput */ -export type ManagedServiceIdentityTypeOutput = - | "None" - | "SystemAssigned" - | "UserAssigned" - | "SystemAssigned, UserAssigned" - | string; +export type ManagedServiceIdentityTypeOutput = string; +/** Alias for ResourceIdentityTypeOutput */ +export type ResourceIdentityTypeOutput = "SystemAssigned"; +/** Alias for SkuTierOutput */ +export type SkuTierOutput = "Free" | "Basic" | "Standard" | "Premium"; /** Alias for PrivateEndpointServiceConnectionStatusOutput */ -export type PrivateEndpointServiceConnectionStatusOutput = - | "Pending" - | "Approved" - | "Rejected" - | string; -/** Alias for ResourceProvisioningStateOutput */ -export type ResourceProvisioningStateOutput = - | "Succeeded" - | "Failed" - | "Canceled" - | string; +export type PrivateEndpointServiceConnectionStatusOutput = string; /** Alias for PrivateEndpointConnectionProvisioningStateOutput */ -export type PrivateEndpointConnectionProvisioningStateOutput = - | ResourceProvisioningStateOutput - | "Creating" - | "Deleting"; +export type PrivateEndpointConnectionProvisioningStateOutput = string; /** Alias for DataTypeStateOutput */ -export type DataTypeStateOutput = string | "Stopped" | "Running"; +export type DataTypeStateOutput = string; /** The response of a DataProductsCatalog list operation. */ export type DataProductsCatalogListResultOutput = Paged; /** The response of a DataType list operation. */ export type DataTypeListResultOutput = Paged; /** Alias for DataProductUserRoleOutput */ -export type DataProductUserRoleOutput = string | "Reader" | "SensitiveReader"; +export type DataProductUserRoleOutput = string; /** The response of a DataProduct list operation. */ export type DataProductListResultOutput = Paged; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/pollingHelper.ts index 6146930477..e6f2560975 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/pollingHelper.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/pollingHelper.ts @@ -219,7 +219,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -228,7 +228,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/responses.ts index 050b71813b..a64d35150f 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/rest/responses.ts @@ -4,7 +4,7 @@ import { RawHttpHeaders } from "@azure/core-rest-pipeline"; import { HttpResponse } from "@azure-rest/core-client"; import { - PagedOperationOutput, + OperationListResultOutput, ErrorResponseOutput, DataProductsCatalogOutput, DataProductsCatalogListResultOutput, @@ -21,7 +21,7 @@ import { /** Azure operation completed successfully. */ export interface OperationsList200Response extends HttpResponse { status: "200"; - body: PagedOperationOutput; + body: OperationListResultOutput; } export interface OperationsListDefaultResponse extends HttpResponse { @@ -73,6 +73,8 @@ export interface DataTypesCreate200Response extends HttpResponse { } export interface DataTypesCreate201Headers { + /** A link to the status monitor */ + "azure-asyncoperation"?: string; /** The Retry-After header can indicate how long the client should wait before polling the operation status. */ "retry-after"?: number; } @@ -224,6 +226,8 @@ export interface DataProductsCreate200Response extends HttpResponse { } export interface DataProductsCreate201Headers { + /** A link to the status monitor */ + "azure-asyncoperation"?: string; /** The Retry-After header can indicate how long the client should wait before polling the operation status. */ "retry-after"?: number; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/restorePollerHelpers.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/restorePollerHelpers.ts index a5023d0806..2b4e008435 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/src/restorePollerHelpers.ts @@ -7,7 +7,6 @@ import { deserializeState, ResourceLocationConfig, } from "@azure/core-lro"; -import { NetworkAnalyticsContext } from "./api/networkAnalyticsContext.js"; import { NetworkAnalyticsClient } from "./networkAnalyticsClient.js"; import { getLongRunningPoller } from "./api/pollingHelpers.js"; import { @@ -47,7 +46,7 @@ export interface RestorePollerOptions< * needs to be constructed after the original one is not in scope. */ export function restorePoller( - client: NetworkAnalyticsContext | NetworkAnalyticsClient, + client: NetworkAnalyticsClient, serializedState: string, sourceOperation: ( ...args: any[] diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/tspconfig.yaml b/packages/typespec-test/test/NetworkAnalytics.Management/tspconfig.yaml index d76b043103..dd3b9ae633 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/tspconfig.yaml +++ b/packages/typespec-test/test/NetworkAnalytics.Management/tspconfig.yaml @@ -8,6 +8,7 @@ options: generateSample: true isModularLibrary: true azureSdkForJs: false + experimentalExtensibleEnums: true "emitter-output-dir": "{project-root}/generated/typespec-ts" packageDetails: name: "@azure/arm-networkanalytics" \ No newline at end of file diff --git a/packages/typespec-test/test/anomalyDetector/generated/openapi/v1.1/openapi.json b/packages/typespec-test/test/anomalyDetector/generated/openapi/v1.1/openapi.json index e711b82c89..6991cbb2e2 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/openapi/v1.1/openapi.json +++ b/packages/typespec-test/test/anomalyDetector/generated/openapi/v1.1/openapi.json @@ -658,7 +658,7 @@ ], "x-ms-enum": { "name": "DataSchema", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "OneTable", @@ -721,7 +721,7 @@ ], "x-ms-enum": { "name": "FillNAMethod", - "modelAsString": true + "modelAsString": false } }, "Multivariate.ModelInfo": { @@ -1167,7 +1167,7 @@ ], "x-ms-enum": { "name": "AnomalyDetectorErrorCodes", - "modelAsString": true + "modelAsString": false } }, "Univariate.ImputeMode": { @@ -1182,7 +1182,7 @@ ], "x-ms-enum": { "name": "ImputeMode", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Auto", diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json index a8a50b3889..b959c6cdaf 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json @@ -44,7 +44,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -62,7 +62,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md index 90a9933bbb..595e79838d 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/review/ai-anomaly-detector.api.md @@ -9,7 +9,7 @@ import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -// @public (undocumented) +// @public export type AlignMode = "Inner" | "Outer"; // @public (undocumented) @@ -20,12 +20,12 @@ export class AnomalyDetectorClient { readonly univariate: UnivariateOperations; } -// @public (undocumented) +// @public export interface AnomalyDetectorClientOptions extends ClientOptions { apiVersion?: string; } -// @public (undocumented) +// @public export type AnomalyDetectorErrorCodes = "InvalidCustomInterval" | "BadArgument" | "InvalidGranularity" | "InvalidPeriod" | "InvalidModelArgument" | "InvalidSeries" | "InvalidJsonFormat" | "RequiredGranularity" | "RequiredSeries" | "InvalidImputeMode" | "InvalidImputeFixedValue"; // @public @@ -33,16 +33,16 @@ export type ContinuablePage = TPage & { continuationToken?: string; }; -// @public (undocumented) +// @public export type DataSchema = "OneTable" | "MultiTable"; -// @public (undocumented) +// @public export type FillNAMethod = "Previous" | "Subsequent" | "Linear" | "Zero" | "Fixed"; -// @public (undocumented) +// @public export type ImputeMode = "auto" | "previous" | "linear" | "fixed" | "zero" | "notFill"; -// @public (undocumented) +// @public export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; // @public @@ -82,7 +82,7 @@ export interface MultivariateAnomalyValue { severity: number; } -// @public (undocumented) +// @public export type MultivariateBatchDetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; // @public @@ -90,15 +90,15 @@ export interface MultivariateCorrelationChanges { changedVariables?: string[]; } -// @public (undocumented) +// @public export interface MultivariateDeleteMultivariateModelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface MultivariateDetectMultivariateBatchAnomalyOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface MultivariateDetectMultivariateLastAnomalyOptionalParams extends OperationOptions { } @@ -114,15 +114,15 @@ export interface MultivariateErrorResponse { message: string; } -// @public (undocumented) +// @public export interface MultivariateGetMultivariateBatchDetectionResultOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface MultivariateGetMultivariateModelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface MultivariateListMultivariateModelsOptionalParams extends OperationOptions { skip?: number; top?: number; @@ -142,14 +142,6 @@ export interface MultivariateModelInfo { status?: ModelStatus; } -// @public -export interface MultivariateModelList { - currentCount: number; - maxCount: number; - models: MultivariateAnomalyDetectionModel[]; - nextLink?: string; -} - // @public export interface MultivariateModelState { epochIds?: number[]; @@ -193,25 +185,18 @@ export interface MultivariateMultivariateLastDetectionResult { variableStates?: MultivariateVariableState[]; } -// @public (undocumented) +// @public export interface MultivariateOperations { - // (undocumented) deleteMultivariateModel: (modelId: string, options?: MultivariateDeleteMultivariateModelOptionalParams) => Promise; - // (undocumented) detectMultivariateBatchAnomaly: (modelId: string, options: MultivariateMultivariateBatchDetectionOptions, optionalParams?: MultivariateDetectMultivariateBatchAnomalyOptionalParams) => Promise; - // (undocumented) detectMultivariateLastAnomaly: (modelId: string, options: MultivariateMultivariateLastDetectionOptions, optionalParams?: MultivariateDetectMultivariateLastAnomalyOptionalParams) => Promise; - // (undocumented) getMultivariateBatchDetectionResult: (resultId: string, options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams) => Promise; - // (undocumented) getMultivariateModel: (modelId: string, options?: MultivariateGetMultivariateModelOptionalParams) => Promise; - // (undocumented) listMultivariateModels: (options?: MultivariateListMultivariateModelsOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) trainMultivariateModel: (modelInfo: MultivariateModelInfo, options?: MultivariateTrainMultivariateModelOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface MultivariateTrainMultivariateModelOptionalParams extends OperationOptions { } @@ -243,7 +228,7 @@ export interface PageSettings { continuationToken?: string; } -// @public (undocumented) +// @public export type TimeGranularity = "yearly" | "monthly" | "weekly" | "daily" | "hourly" | "minutely" | "secondly" | "microsecond" | "none"; // @public @@ -252,25 +237,22 @@ export interface UnivariateAnomalyDetectorError { message?: string; } -// @public (undocumented) +// @public export interface UnivariateDetectUnivariateChangePointOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface UnivariateDetectUnivariateEntireSeriesOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface UnivariateDetectUnivariateLastPointOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface UnivariateOperations { - // (undocumented) detectUnivariateChangePoint: (options: UnivariateUnivariateChangePointDetectionOptions, optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams) => Promise; - // (undocumented) detectUnivariateEntireSeries: (options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateEntireSeriesOptionalParams) => Promise; - // (undocumented) detectUnivariateLastPoint: (options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams) => Promise; } @@ -334,7 +316,7 @@ export interface UnivariateUnivariateLastDetectionResult { upperMargin: number; } -// @public (undocumented) +// @public export type Versions = "v1.1"; // (No @packageDocumentation comment for this package) diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts index 6c764378b7..6707244079 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { AnomalyDetectorContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface AnomalyDetectorClientOptions extends ClientOptions { /** Api Version */ apiVersion?: string; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts index 30d080cf87..96bf4c89b9 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts @@ -2,13 +2,16 @@ // Licensed under the MIT license. import { + multivariateAlignPolicySerializer, + multivariateDiagnosticsInfoSerializer, + multivariateVariableValuesSerializer, MultivariateMultivariateDetectionResult, MultivariateMultivariateBatchDetectionOptions, MultivariateModelInfo, MultivariateAnomalyDetectionModel, - MultivariateModelList, MultivariateMultivariateLastDetectionOptions, MultivariateMultivariateLastDetectionResult, + _MultivariateModelList, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -177,43 +180,12 @@ export function _trainMultivariateModelSend( displayName: modelInfo["displayName"], slidingWindow: modelInfo["slidingWindow"], alignPolicy: !modelInfo.alignPolicy - ? undefined - : { - alignMode: modelInfo.alignPolicy?.["alignMode"], - fillNAMethod: modelInfo.alignPolicy?.["fillNAMethod"], - paddingValue: modelInfo.alignPolicy?.["paddingValue"], - }, + ? modelInfo.alignPolicy + : multivariateAlignPolicySerializer(modelInfo.alignPolicy), status: modelInfo["status"], diagnosticsInfo: !modelInfo.diagnosticsInfo - ? undefined - : { - modelState: !modelInfo.diagnosticsInfo?.modelState - ? undefined - : { - epochIds: - modelInfo.diagnosticsInfo?.modelState?.["epochIds"], - trainLosses: - modelInfo.diagnosticsInfo?.modelState?.["trainLosses"], - validationLosses: - modelInfo.diagnosticsInfo?.modelState?.[ - "validationLosses" - ], - latenciesInSeconds: - modelInfo.diagnosticsInfo?.modelState?.[ - "latenciesInSeconds" - ], - }, - variableStates: - modelInfo.diagnosticsInfo?.["variableStates"] === undefined - ? modelInfo.diagnosticsInfo?.["variableStates"] - : modelInfo.diagnosticsInfo?.["variableStates"].map((p) => ({ - variable: p["variable"], - filledNARatio: p["filledNARatio"], - effectiveCount: p["effectiveCount"], - firstTimestamp: p["firstTimestamp"]?.toISOString(), - lastTimestamp: p["lastTimestamp"]?.toISOString(), - })), - }, + ? modelInfo.diagnosticsInfo + : multivariateDiagnosticsInfoSerializer(modelInfo.diagnosticsInfo), }, }); } @@ -344,7 +316,7 @@ export async function _listMultivariateModelsDeserialize( result: | ListMultivariateModels200Response | ListMultivariateModelsDefaultResponse, -): Promise { +): Promise<_MultivariateModelList> { if (isUnexpected(result)) { throw createRestError(result); } @@ -737,11 +709,9 @@ export function _detectMultivariateLastAnomalySend( .post({ ...operationOptionsToRequestParameters(optionalParams), body: { - variables: options["variables"].map((p) => ({ - variable: p["variable"], - timestamps: p["timestamps"], - values: p["values"], - })), + variables: options["variables"].map( + multivariateVariableValuesSerializer, + ), topContributorCount: options["topContributorCount"], }, }); diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts index e15afbda0c..9f5f41463b 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + univariateTimeSeriesPointSerializer, UnivariateUnivariateDetectionOptions, UnivariateUnivariateEntireDetectionResult, UnivariateUnivariateLastDetectionResult, @@ -44,10 +45,7 @@ export function _detectUnivariateEntireSeriesSend( .post({ ...operationOptionsToRequestParameters(optionalParams), body: { - series: options["series"].map((p) => ({ - timestamp: p["timestamp"]?.toISOString(), - value: p["value"], - })), + series: options["series"].map(univariateTimeSeriesPointSerializer), granularity: options["granularity"], customInterval: options["customInterval"], period: options["period"], @@ -116,10 +114,7 @@ export function _detectUnivariateLastPointSend( .post({ ...operationOptionsToRequestParameters(optionalParams), body: { - series: options["series"].map((p) => ({ - timestamp: p["timestamp"]?.toISOString(), - value: p["value"], - })), + series: options["series"].map(univariateTimeSeriesPointSerializer), granularity: options["granularity"], customInterval: options["customInterval"], period: options["period"], @@ -187,10 +182,7 @@ export function _detectUnivariateChangePointSend( .post({ ...operationOptionsToRequestParameters(optionalParams), body: { - series: options["series"].map((p) => ({ - timestamp: p["timestamp"]?.toISOString(), - value: p["value"], - })), + series: options["series"].map(univariateTimeSeriesPointSerializer), granularity: options["granularity"], customInterval: options["customInterval"], period: options["period"], diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts index 0f0a7c209c..aad8be0984 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts @@ -30,31 +30,65 @@ import { MultivariateDetectMultivariateLastAnomalyOptionalParams, } from "../../models/options.js"; +/** Interface representing a Multivariate operations. */ export interface MultivariateOperations { + /** + * For asynchronous inference, get multivariate anomaly detection result based on + * resultId returned by the BatchDetectAnomaly api. + */ getMultivariateBatchDetectionResult: ( resultId: string, options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams, ) => Promise; + /** + * Create and train a multivariate anomaly detection model. The request must + * include a source parameter to indicate an externally accessible Azure blob + * storage URI.There are two types of data input: An URI pointed to an Azure blob + * storage folder which contains multiple CSV files, and each CSV file contains + * two columns, timestamp and variable. Another type of input is an URI pointed to + * a CSV file in Azure blob storage, which contains all the variables and a + * timestamp column. + */ trainMultivariateModel: ( modelInfo: MultivariateModelInfo, options?: MultivariateTrainMultivariateModelOptionalParams, ) => Promise; + /** List models of a resource. */ listMultivariateModels: ( options?: MultivariateListMultivariateModelsOptionalParams, ) => PagedAsyncIterableIterator; + /** Delete an existing multivariate model according to the modelId */ deleteMultivariateModel: ( modelId: string, options?: MultivariateDeleteMultivariateModelOptionalParams, ) => Promise; + /** + * Get detailed information of multivariate model, including the training status + * and variables used in the model. + */ getMultivariateModel: ( modelId: string, options?: MultivariateGetMultivariateModelOptionalParams, ) => Promise; + /** + * Submit multivariate anomaly detection task with the modelId of trained model + * and inference data, the input schema should be the same with the training + * request. The request will complete asynchronously and return a resultId to + * query the detection result.The request should be a source link to indicate an + * externally accessible Azure storage Uri, either pointed to an Azure blob + * storage folder, or pointed to a CSV file in Azure blob storage. + */ detectMultivariateBatchAnomaly: ( modelId: string, options: MultivariateMultivariateBatchDetectionOptions, optionalParams?: MultivariateDetectMultivariateBatchAnomalyOptionalParams, ) => Promise; + /** + * Submit multivariate anomaly detection task with the modelId of trained model + * and inference data, and the inference data should be put into request body in a + * JSON format. The request will complete synchronously and return the detection + * immediately in the response body. + */ detectMultivariateLastAnomaly: ( modelId: string, options: MultivariateMultivariateLastDetectionOptions, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts index 26ced34240..da3ad81513 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts @@ -20,15 +20,27 @@ import { UnivariateDetectUnivariateChangePointOptionalParams, } from "../../models/options.js"; +/** Interface representing a Univariate operations. */ export interface UnivariateOperations { + /** + * This operation generates a model with an entire series, each point is detected + * with the same model. With this method, points before and after a certain point + * are used to determine whether it is an anomaly. The entire detection can give + * user an overall status of the time series. + */ detectUnivariateEntireSeries: ( options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateEntireSeriesOptionalParams, ) => Promise; + /** + * This operation generates a model using the points that you sent into the API, + * and based on all data to determine whether the last point is anomalous. + */ detectUnivariateLastPoint: ( options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams, ) => Promise; + /** Evaluate change point score of every series point */ detectUnivariateChangePoint: ( options: UnivariateUnivariateChangePointDetectionOptions, optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts index 233f37a811..313ce7c011 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts @@ -25,7 +25,6 @@ export { MultivariateDiagnosticsInfo, MultivariateModelState, MultivariateAnomalyDetectionModel, - MultivariateModelList, MultivariateMultivariateLastDetectionOptions, MultivariateVariableValues, MultivariateMultivariateLastDetectionResult, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts index f909593e3e..133a6b264d 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/index.ts @@ -21,7 +21,6 @@ export { MultivariateDiagnosticsInfo, MultivariateModelState, MultivariateAnomalyDetectionModel, - MultivariateModelList, MultivariateMultivariateLastDetectionOptions, MultivariateVariableValues, MultivariateMultivariateLastDetectionResult, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts index aee9e3b90a..9181fd7443 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,20 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { + MultivariateVariableState as MultivariateVariableStateRest, + MultivariateMultivariateBatchDetectionOptions as MultivariateMultivariateBatchDetectionOptionsRest, + MultivariateModelInfo as MultivariateModelInfoRest, + MultivariateAlignPolicy as MultivariateAlignPolicyRest, + MultivariateDiagnosticsInfo as MultivariateDiagnosticsInfoRest, + MultivariateModelState as MultivariateModelStateRest, + MultivariateMultivariateLastDetectionOptions as MultivariateMultivariateLastDetectionOptionsRest, + MultivariateVariableValues as MultivariateVariableValuesRest, + UnivariateUnivariateDetectionOptions as UnivariateUnivariateDetectionOptionsRest, + UnivariateTimeSeriesPoint as UnivariateTimeSeriesPointRest, + UnivariateUnivariateChangePointDetectionOptions as UnivariateUnivariateChangePointDetectionOptionsRest, +} from "../rest/index.js"; + /** Detection results for the given resultId. */ export interface MultivariateMultivariateDetectionResult { /** Result identifier, which is used to fetch the results of an inference call. */ @@ -26,7 +40,7 @@ export interface MultivariateMultivariateBatchDetectionResultSummary { setupInfo: MultivariateMultivariateBatchDetectionOptions; } -/** */ +/** Type of MultivariateBatchDetectionStatus */ export type MultivariateBatchDetectionStatus = | "CREATED" | "RUNNING" @@ -55,6 +69,18 @@ export interface MultivariateVariableState { lastTimestamp?: Date; } +export function multivariateVariableStateSerializer( + item: MultivariateVariableState, +): MultivariateVariableStateRest { + return { + variable: item["variable"], + filledNARatio: item["filledNARatio"], + effectiveCount: item["effectiveCount"], + firstTimestamp: item["firstTimestamp"]?.toISOString(), + lastTimestamp: item["lastTimestamp"]?.toISOString(), + }; +} + /** * Detection request for batch inference. This is an asynchronous inference which * will need another API to get detection results. @@ -85,6 +111,17 @@ export interface MultivariateMultivariateBatchDetectionOptions { endTime: Date; } +export function multivariateMultivariateBatchDetectionOptionsSerializer( + item: MultivariateMultivariateBatchDetectionOptions, +): MultivariateMultivariateBatchDetectionOptionsRest { + return { + dataSource: item["dataSource"], + topContributorCount: item["topContributorCount"], + startTime: item["startTime"].toISOString(), + endTime: item["endTime"].toISOString(), + }; +} + /** Anomaly status and information. */ export interface MultivariateAnomalyState { /** The timestamp for this anomaly. */ @@ -178,8 +215,27 @@ export interface MultivariateModelInfo { diagnosticsInfo?: MultivariateDiagnosticsInfo; } +export function multivariateModelInfoSerializer( + item: MultivariateModelInfo, +): MultivariateModelInfoRest { + return { + dataSource: item["dataSource"], + dataSchema: item["dataSchema"], + startTime: item["startTime"].toISOString(), + endTime: item["endTime"].toISOString(), + displayName: item["displayName"], + slidingWindow: item["slidingWindow"], + alignPolicy: !item.alignPolicy + ? item.alignPolicy + : multivariateAlignPolicySerializer(item.alignPolicy), + status: item["status"], + diagnosticsInfo: !item.diagnosticsInfo + ? item.diagnosticsInfo + : multivariateDiagnosticsInfoSerializer(item.diagnosticsInfo), + }; +} + /** Data schema of input data source: OneTable or MultiTable. The default DataSchema is OneTable. */ -/** */ export type DataSchema = "OneTable" | "MultiTable"; /** An optional field, indicating the manner to align multiple variables. */ @@ -198,17 +254,26 @@ export interface MultivariateAlignPolicy { paddingValue?: number; } -/** */ +export function multivariateAlignPolicySerializer( + item: MultivariateAlignPolicy, +): MultivariateAlignPolicyRest { + return { + alignMode: item["alignMode"], + fillNAMethod: item["fillNAMethod"], + paddingValue: item["paddingValue"], + }; +} + +/** Type of AlignMode */ export type AlignMode = "Inner" | "Outer"; /** An optional field, indicating how missing values will be filled. One of Previous, Subsequent, Linear, Zero, Fixed. */ -/** */ export type FillNAMethod = | "Previous" | "Subsequent" | "Linear" | "Zero" | "Fixed"; -/** */ +/** Type of ModelStatus */ export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; /** Diagnostics information to help inspect the states of model or variable. */ @@ -219,6 +284,20 @@ export interface MultivariateDiagnosticsInfo { variableStates?: MultivariateVariableState[]; } +export function multivariateDiagnosticsInfoSerializer( + item: MultivariateDiagnosticsInfo, +): MultivariateDiagnosticsInfoRest { + return { + modelState: !item.modelState + ? item.modelState + : multivariateModelStateSerializer(item.modelState), + variableStates: + item["variableStates"] === undefined + ? item["variableStates"] + : item["variableStates"].map(multivariateVariableStateSerializer), + }; +} + /** Model status. */ export interface MultivariateModelState { /** @@ -240,6 +319,17 @@ export interface MultivariateModelState { latenciesInSeconds?: number[]; } +export function multivariateModelStateSerializer( + item: MultivariateModelState, +): MultivariateModelStateRest { + return { + epochIds: item["epochIds"], + trainLosses: item["trainLosses"], + validationLosses: item["validationLosses"], + latenciesInSeconds: item["latenciesInSeconds"], + }; +} + /** Response of getting a model. */ export interface MultivariateAnomalyDetectionModel { /** Model identifier. */ @@ -256,7 +346,7 @@ export interface MultivariateAnomalyDetectionModel { } /** Response of listing models. */ -export interface MultivariateModelList { +export interface _MultivariateModelList { /** List of models. */ models: MultivariateAnomalyDetectionModel[]; /** Number of trained multivariate models. */ @@ -282,6 +372,15 @@ export interface MultivariateMultivariateLastDetectionOptions { topContributorCount: number; } +export function multivariateMultivariateLastDetectionOptionsSerializer( + item: MultivariateMultivariateLastDetectionOptions, +): MultivariateMultivariateLastDetectionOptionsRest { + return { + variables: item["variables"].map(multivariateVariableValuesSerializer), + topContributorCount: item["topContributorCount"], + }; +} + /** Variable values. */ export interface MultivariateVariableValues { /** Variable name of last detection request. */ @@ -292,6 +391,16 @@ export interface MultivariateVariableValues { values: number[]; } +export function multivariateVariableValuesSerializer( + item: MultivariateVariableValues, +): MultivariateVariableValuesRest { + return { + variable: item["variable"], + timestamps: item["timestamps"], + values: item["values"], + }; +} + /** Results of last detection. */ export interface MultivariateMultivariateLastDetectionResult { /** Variable Status. */ @@ -347,6 +456,21 @@ export interface UnivariateUnivariateDetectionOptions { imputeFixedValue?: number; } +export function univariateUnivariateDetectionOptionsSerializer( + item: UnivariateUnivariateDetectionOptions, +): UnivariateUnivariateDetectionOptionsRest { + return { + series: item["series"].map(univariateTimeSeriesPointSerializer), + granularity: item["granularity"], + customInterval: item["customInterval"], + period: item["period"], + maxAnomalyRatio: item["maxAnomalyRatio"], + sensitivity: item["sensitivity"], + imputeMode: item["imputeMode"], + imputeFixedValue: item["imputeFixedValue"], + }; +} + /** The definition of input timeseries points. */ export interface UnivariateTimeSeriesPoint { /** Optional argument, timestamp of a data point (ISO8601 format). */ @@ -355,7 +479,16 @@ export interface UnivariateTimeSeriesPoint { value: number; } -/** */ +export function univariateTimeSeriesPointSerializer( + item: UnivariateTimeSeriesPoint, +): UnivariateTimeSeriesPointRest { + return { + timestamp: item["timestamp"]?.toISOString(), + value: item["value"], + }; +} + +/** Type of TimeGranularity */ export type TimeGranularity = | "yearly" | "monthly" @@ -366,7 +499,7 @@ export type TimeGranularity = | "secondly" | "microsecond" | "none"; -/** */ +/** Type of ImputeMode */ export type ImputeMode = | "auto" | "previous" @@ -439,7 +572,7 @@ export interface UnivariateAnomalyDetectorError { message?: string; } -/** */ +/** Type of AnomalyDetectorErrorCodes */ export type AnomalyDetectorErrorCodes = | "InvalidCustomInterval" | "BadArgument" @@ -536,6 +669,19 @@ export interface UnivariateUnivariateChangePointDetectionOptions { threshold?: number; } +export function univariateUnivariateChangePointDetectionOptionsSerializer( + item: UnivariateUnivariateChangePointDetectionOptions, +): UnivariateUnivariateChangePointDetectionOptionsRest { + return { + series: item["series"].map(univariateTimeSeriesPointSerializer), + granularity: item["granularity"], + customInterval: item["customInterval"], + period: item["period"], + stableTrendWindow: item["stableTrendWindow"], + threshold: item["threshold"], + }; +} + /** The response of change point detection. */ export interface UnivariateUnivariateChangePointDetectionResult { /** @@ -553,5 +699,5 @@ export interface UnivariateUnivariateChangePointDetectionResult { confidenceScores?: number[]; } -/** */ +/** Type of Versions */ export type Versions = "v1.1"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts index b46700fcb8..3c213ff0df 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/options.ts @@ -3,21 +3,27 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface UnivariateDetectUnivariateEntireSeriesOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface UnivariateDetectUnivariateLastPointOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface UnivariateDetectUnivariateChangePointOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateGetMultivariateBatchDetectionResultOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateTrainMultivariateModelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateListMultivariateModelsOptionalParams extends OperationOptions { /** Skip indicates how many models will be skipped. */ @@ -26,14 +32,18 @@ export interface MultivariateListMultivariateModelsOptionalParams top?: number; } +/** Optional parameters. */ export interface MultivariateDeleteMultivariateModelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateGetMultivariateModelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateDetectMultivariateBatchAnomalyOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface MultivariateDetectMultivariateLastAnomalyOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/rest/anomalyDetectorClient.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/rest/anomalyDetectorClient.ts index 395dca27bb..152618a043 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/rest/anomalyDetectorClient.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/rest/anomalyDetectorClient.ts @@ -6,7 +6,9 @@ import { logger } from "../logger.js"; import { KeyCredential } from "@azure/core-auth"; import { AnomalyDetectorContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ export interface AnomalyDetectorContextOptions extends ClientOptions { + /** Api Version */ apiVersion?: string; } @@ -20,14 +22,12 @@ export interface AnomalyDetectorContextOptions extends ClientOptions { export default function createClient( endpointParam: string, credentials: KeyCredential, - options: AnomalyDetectorContextOptions = {}, + { apiVersion = "v1.1", ...options }: AnomalyDetectorContextOptions = {}, ): AnomalyDetectorContext { - const apiVersion = options.apiVersion ?? "v1.1"; const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/anomalydetector/${apiVersion}`; - const userAgentInfo = `azsdk-js-ai-anomaly-detector-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -46,7 +46,6 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, @@ -54,11 +53,6 @@ export default function createClient( ) as AnomalyDetectorContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - if (options.apiVersion) { - logger.warning( - "This client does not support client api-version, please change it at the operation level", - ); - } return client; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/authoring/generated/openapi/2022-05-15-preview/openapi.json b/packages/typespec-test/test/authoring/generated/openapi/2022-05-15-preview/openapi.json index a1c71301fc..de8d628bec 100644 --- a/packages/typespec-test/test/authoring/generated/openapi/2022-05-15-preview/openapi.json +++ b/packages/typespec-test/test/authoring/generated/openapi/2022-05-15-preview/openapi.json @@ -183,6 +183,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true }, "delete": { @@ -246,6 +249,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, @@ -292,6 +298,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, @@ -335,6 +344,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, @@ -387,6 +399,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, @@ -546,6 +561,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "original-uri" + }, "x-ms-long-running-operation": true }, "delete": { @@ -616,6 +634,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, @@ -766,6 +787,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/package.json b/packages/typespec-test/test/authoring/generated/typespec-ts/package.json index ffe75d7931..76e02514ae 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -60,7 +60,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/review/authoring.api.md b/packages/typespec-test/test/authoring/generated/typespec-ts/review/authoring.api.md index 0bbc0cd23c..69a4944c1a 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/review/authoring.api.md +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/review/authoring.api.md @@ -27,7 +27,12 @@ export type AuthoringClient = Client & { }; // @public -function createClient(endpointParam: string, credentials: KeyCredential, options?: ClientOptions): AuthoringClient; +export interface AuthoringClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +function createClient(endpointParam: string, credentials: KeyCredential, { apiVersion, ...options }?: AuthoringClientOptions): AuthoringClient; export default createClient; // @public (undocumented) @@ -724,7 +729,7 @@ export interface ListTrainingConfigVersionsQueryParamProperties { } // @public -export type OperationStateOutput = "NotStarted" | "Running" | "Succeeded" | "Failed" | "Canceled"; +export type OperationStateOutput = string; // @public export interface OperationStatusOutput { diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/src/authoringClient.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/src/authoringClient.ts index 5d3f80e061..98894eae89 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/src/authoringClient.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/src/authoringClient.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { KeyCredential } from "@azure/core-auth"; import { AuthoringClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface AuthoringClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `AuthoringClient` * @param endpointParam - The endpoint to use. @@ -15,11 +21,13 @@ import { AuthoringClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + { + apiVersion = "2022-05-15-preview", + ...options + }: AuthoringClientOptions = {}, ): AuthoringClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/language`; - options.apiVersion = options.apiVersion ?? "2022-05-15-preview"; const userAgentInfo = `azsdk-js-authoring-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -38,12 +46,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as AuthoringClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/src/outputModels.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/src/outputModels.ts index dc386a6e5c..9631598084 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/src/outputModels.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/src/outputModels.ts @@ -118,13 +118,8 @@ export type ProjectKindOutput = | "CustomSingleLabelClassification" | "CustomMultiLabelClassification" | "CustomEntityRecognition"; -/** Enum describing allowed operation states. */ -export type OperationStateOutput = - | "NotStarted" - | "Running" - | "Succeeded" - | "Failed" - | "Canceled"; +/** Alias for OperationStateOutput */ +export type OperationStateOutput = string; /** Paged collection of Project items */ export type PagedProjectOutput = Paged; /** Paged collection of Deployment items */ diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/src/pollingHelper.ts index 80ee819c55..30fdbd54af 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/src/pollingHelper.ts @@ -201,7 +201,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -210,7 +210,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/authoring/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json index 6ea1e4d9a9..47f6bb8ee9 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json @@ -42,7 +42,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -60,7 +60,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md index b579922d03..0281696077 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md @@ -9,28 +9,16 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public (undocumented) -export type AccessScope = "job"; - // @public -export interface AccountListSupportedImagesResult { - "odata.nextLink"?: string; - value?: ImageInformation[]; -} +export type AccessScope = "job"; // @public export interface AffinityInformation { affinityId: string; } -// @public (undocumented) -export type AllocationState = "steady" | "resizing" | "stopping"; - // @public -export interface ApplicationListResult { - "odata.nextLink"?: string; - value?: BatchApplication[]; -} +export type AllocationState = "steady" | "resizing" | "stopping"; // @public export interface ApplicationPackageReference { @@ -65,7 +53,7 @@ export interface AutoScaleRunError { values?: NameValuePair[]; } -// @public (undocumented) +// @public export type AutoUserScope = "task" | "pool"; // @public @@ -199,7 +187,7 @@ export class BatchClient { uploadNodeLogs(poolId: string, nodeId: string, body: UploadBatchServiceLogsOptions, options?: UploadNodeLogsOptionalParams): Promise; } -// @public (undocumented) +// @public export interface BatchClientOptions extends ClientOptions { } @@ -271,18 +259,6 @@ export interface BatchJobDisableOptions { disableTasks: DisableJobOption; } -// @public -export interface BatchJobListPreparationAndReleaseTaskStatusResult { - "odata.nextLink"?: string; - value?: JobPreparationAndReleaseTaskExecutionInformation[]; -} - -// @public -export interface BatchJobListResult { - "odata.nextLink"?: string; - value?: BatchJob[]; -} - // @public export interface BatchJobSchedule { readonly creationTime?: Date; @@ -311,12 +287,6 @@ export interface BatchJobScheduleCreateOptions { schedule: Schedule; } -// @public -export interface BatchJobScheduleListResult { - "odata.nextLink"?: string; - value?: BatchJobSchedule[]; -} - // @public export interface BatchJobScheduleUpdateOptions { jobSpecification?: JobSpecification; @@ -367,7 +337,7 @@ export interface BatchNode { vmSize?: string; } -// @public (undocumented) +// @public export type BatchNodeDeallocationOption = "requeue" | "terminate" | "taskcompletion" | "retaineddata"; // @public @@ -382,7 +352,7 @@ export interface BatchNodeError { message?: string; } -// @public (undocumented) +// @public export type BatchNodeFillType = "spread" | "pack"; // @public @@ -401,15 +371,9 @@ export interface BatchNodeInformation { } // @public -export interface BatchNodeListResult { - "odata.nextLink"?: string; - value?: BatchNode[]; -} - -// @public (undocumented) export type BatchNodeRebootOption = "requeue" | "terminate" | "taskcompletion" | "retaineddata"; -// @public (undocumented) +// @public export type BatchNodeReimageOption = "requeue" | "terminate" | "taskcompletion" | "retaineddata"; // @public @@ -418,7 +382,7 @@ export interface BatchNodeRemoteLoginSettingsResult { remoteLoginPort: number; } -// @public (undocumented) +// @public export type BatchNodeState = "idle" | "rebooting" | "reimaging" | "running" | "unusable" | "creating" | "starting" | "waitingforstarttask" | "starttaskfailed" | "unknown" | "leavingpool" | "offline" | "preempted"; // @public @@ -523,12 +487,6 @@ export interface BatchPoolIdentity { userAssignedIdentities?: UserAssignedIdentity[]; } -// @public -export interface BatchPoolListResult { - "odata.nextLink"?: string; - value?: BatchPool[]; -} - // @public export interface BatchPoolReplaceOptions { applicationPackageReferences: ApplicationPackageReference[]; @@ -611,34 +569,22 @@ export interface BatchTaskCreateOptions { userIdentity?: UserIdentity; } -// @public -export interface BatchTaskListResult { - "odata.nextLink"?: string; - value?: BatchTask[]; -} - // @public export interface BatchTaskListSubtasksResult { value?: SubtaskInformation[]; } -// @public (undocumented) +// @public export type CachingType = "none" | "readonly" | "readwrite"; -// @public (undocumented) +// @public export interface CancelCertificateDeletionOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) -export type CertificateFormat = "pfx" | "cer"; - // @public -export interface CertificateListResult { - "odata.nextLink"?: string; - value?: BatchCertificate[]; -} +export type CertificateFormat = "pfx" | "cer"; // @public export interface CertificateReference { @@ -649,13 +595,13 @@ export interface CertificateReference { visibility?: CertificateVisibility[]; } -// @public (undocumented) +// @public export type CertificateState = "active" | "deleting" | "deletefailed"; -// @public (undocumented) +// @public export type CertificateStoreLocation = "currentuser" | "localmachine"; -// @public (undocumented) +// @public export type CertificateVisibility = "starttask" | "task" | "remoteuser"; // @public @@ -688,10 +634,10 @@ export interface ContainerRegistry { username?: string; } -// @public (undocumented) +// @public export type ContainerType = "dockerCompatible" | "criCompatible"; -// @public (undocumented) +// @public export type ContainerWorkingDirectory = "taskWorkingDirectory" | "containerImageDefault"; // @public @@ -699,49 +645,49 @@ export type ContinuablePage = TPage & { continuationToken?: string; }; -// @public (undocumented) +// @public export interface CreateCertificateOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreateJobOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreateJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreateNodeUserOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreatePoolOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreateTaskCollectionOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface CreateTaskOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -763,13 +709,13 @@ export interface DeleteCertificateError { values?: NameValuePair[]; } -// @public (undocumented) +// @public export interface DeleteCertificateOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteJobOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -779,7 +725,7 @@ export interface DeleteJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -789,20 +735,20 @@ export interface DeleteJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteNodeFileOptionalParams extends OperationOptions { apiVersion?: string; recursive?: boolean; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteNodeUserOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeletePoolOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -812,14 +758,14 @@ export interface DeletePoolOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteTaskFileOptionalParams extends OperationOptions { apiVersion?: string; recursive?: boolean; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DeleteTaskOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -829,10 +775,10 @@ export interface DeleteTaskOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export type DependencyAction = "satisfy" | "block"; -// @public (undocumented) +// @public export type DiffDiskPlacement = "cachedisk"; // @public @@ -840,13 +786,13 @@ export interface DiffDiskSettings { placement?: DiffDiskPlacement; } -// @public (undocumented) +// @public export type DisableBatchNodeSchedulingOption = "requeue" | "terminate" | "taskcompletion"; -// @public (undocumented) +// @public export type DisableJobOption = "requeue" | "terminate" | "wait"; -// @public (undocumented) +// @public export interface DisableJobOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -857,7 +803,7 @@ export interface DisableJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DisableJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -867,14 +813,14 @@ export interface DisableJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DisableNodeSchedulingOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; @@ -885,16 +831,16 @@ export interface DiskEncryptionConfiguration { targets?: DiskEncryptionTarget[]; } -// @public (undocumented) +// @public export type DiskEncryptionTarget = "osdisk" | "temporarydisk"; -// @public (undocumented) +// @public export type DynamicVNetAssignmentScope = "none" | "job"; -// @public (undocumented) +// @public export type ElevationLevel = "nonadmin" | "admin"; -// @public (undocumented) +// @public export interface EnableJobOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -904,7 +850,7 @@ export interface EnableJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface EnableJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -914,13 +860,13 @@ export interface EnableJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface EnableNodeSchedulingOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -937,7 +883,7 @@ export interface EnvironmentSetting { value?: string; } -// @public (undocumented) +// @public export type ErrorCategory = "usererror" | "servererror"; // @public @@ -946,7 +892,7 @@ export interface ErrorMessage { value?: string; } -// @public (undocumented) +// @public export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -990,20 +936,20 @@ export interface FileProperties { lastModified: Date; } -// @public (undocumented) +// @public export interface GetApplicationOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetCertificateOptionalParams extends OperationOptions { $select?: string[]; apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetJobOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; @@ -1015,7 +961,7 @@ export interface GetJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetJobScheduleOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; @@ -1027,20 +973,20 @@ export interface GetJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetJobTaskCountsOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeExtensionOptionalParams extends OperationOptions { $select?: string[]; apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeFileOptionalParams extends OperationOptions { apiVersion?: string; ifModifiedSince?: Date; @@ -1049,7 +995,7 @@ export interface GetNodeFileOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { apiVersion?: string; ifModifiedSince?: Date; @@ -1057,26 +1003,26 @@ export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeOptionalParams extends OperationOptions { $select?: string[]; apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeRemoteDesktopFileOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetNodeRemoteLoginSettingsOptionalParams extends OperationOptions { apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetPoolOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; @@ -1088,7 +1034,7 @@ export interface GetPoolOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetTaskFileOptionalParams extends OperationOptions { apiVersion?: string; ifModifiedSince?: Date; @@ -1097,7 +1043,7 @@ export interface GetTaskFileOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { apiVersion?: string; ifModifiedSince?: Date; @@ -1105,7 +1051,7 @@ export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface GetTaskOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; @@ -1153,7 +1099,7 @@ export interface InboundEndpoint { publicIpAddress?: string; } -// @public (undocumented) +// @public export type InboundEndpointProtocol = "tcp" | "udp"; // @public @@ -1175,10 +1121,10 @@ export interface InstanceViewStatus { time?: string; } -// @public (undocumented) +// @public export type IpAddressProvisioningType = "batchmanaged" | "usermanaged" | "nopublicipaddresses"; -// @public (undocumented) +// @public export type JobAction = "none" | "disable" | "terminate"; // @public @@ -1257,7 +1203,7 @@ export interface JobPreparationTaskExecutionInformation { taskRootDirectoryUrl?: string; } -// @public (undocumented) +// @public export type JobPreparationTaskState = "running" | "completed"; // @public @@ -1285,7 +1231,7 @@ export interface JobReleaseTaskExecutionInformation { taskRootDirectoryUrl?: string; } -// @public (undocumented) +// @public export type JobReleaseTaskState = "running" | "completed"; // @public @@ -1295,7 +1241,7 @@ export interface JobScheduleExecutionInformation { recentJob?: RecentJob; } -// @public (undocumented) +// @public export interface JobScheduleExistsOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -1305,7 +1251,7 @@ export interface JobScheduleExistsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export type JobScheduleState = "active" | "completed" | "disabled" | "terminating" | "deleting"; // @public @@ -1353,7 +1299,7 @@ export interface JobSpecification { usesTaskDependencies?: boolean; } -// @public (undocumented) +// @public export type JobState = "active" | "disabling" | "disabled" | "enabling" | "terminating" | "completed" | "deleting"; // @public @@ -1381,14 +1327,14 @@ export interface LinuxUserConfiguration { uid?: number; } -// @public (undocumented) +// @public export interface ListApplicationsOptionalParams extends OperationOptions { apiVersion?: string; maxresults?: number; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListCertificatesOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; @@ -1397,7 +1343,7 @@ export interface ListCertificatesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListJobPreparationAndReleaseTaskStatusOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; @@ -1405,7 +1351,7 @@ export interface ListJobPreparationAndReleaseTaskStatusOptionalParams extends Op timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListJobSchedulesOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; @@ -1415,7 +1361,7 @@ export interface ListJobSchedulesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListJobsFromScheduleOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; @@ -1425,7 +1371,7 @@ export interface ListJobsFromScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListJobsOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; @@ -1435,14 +1381,14 @@ export interface ListJobsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListNodeExtensionsOptionalParams extends OperationOptions { $select?: string[]; maxresults?: number; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListNodeFilesOptionalParams extends OperationOptions { $filter?: string; apiVersion?: string; @@ -1451,7 +1397,7 @@ export interface ListNodeFilesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListNodesOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; @@ -1460,7 +1406,7 @@ export interface ListNodesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListPoolNodeCountsOptionalParams extends OperationOptions { $filter?: string; apiVersion?: string; @@ -1468,7 +1414,7 @@ export interface ListPoolNodeCountsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListPoolsOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; @@ -1478,7 +1424,7 @@ export interface ListPoolsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { $filter?: string; apiVersion?: string; @@ -1488,21 +1434,21 @@ export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListSubTasksOptionalParams extends OperationOptions { $select?: string[]; apiVersion?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListSupportedImagesOptionalParams extends OperationOptions { $filter?: string; maxresults?: number; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListTaskFilesOptionalParams extends OperationOptions { $filter?: string; apiVersion?: string; @@ -1511,7 +1457,7 @@ export interface ListTaskFilesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ListTasksOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; @@ -1521,7 +1467,7 @@ export interface ListTasksOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export type LoginMode = "batch" | "interactive"; // @public @@ -1568,7 +1514,7 @@ export interface NetworkSecurityGroupRule { sourcePortRanges?: string[]; } -// @public (undocumented) +// @public export type NetworkSecurityGroupRuleAccess = "allow" | "deny"; // @public @@ -1584,7 +1530,7 @@ export interface NodeAgentInformation { version: string; } -// @public (undocumented) +// @public export type NodeCommunicationMode = "default" | "classic" | "simplified"; // @public @@ -1618,18 +1564,12 @@ export interface NodeFile { url?: string; } -// @public -export interface NodeFileListResult { - "odata.nextLink"?: string; - value?: NodeFile[]; -} - // @public export interface NodePlacementConfiguration { policy?: NodePlacementPolicyType; } -// @public (undocumented) +// @public export type NodePlacementPolicyType = "regional" | "zonal"; // @public @@ -1657,15 +1597,9 @@ export interface NodeVMExtension { } // @public -export interface NodeVMExtensionList { - "odata.nextLink"?: string; - value?: NodeVMExtension[]; -} - -// @public (undocumented) export type OnAllTasksComplete = "noaction" | "terminatejob"; -// @public (undocumented) +// @public export type OnTaskFailure = "noaction" | "performexitoptionsjobaction"; // @public @@ -1673,7 +1607,7 @@ export interface OSDisk { ephemeralOSDiskSettings?: DiffDiskSettings; } -// @public (undocumented) +// @public export type OSType = "linux" | "windows"; // @public @@ -1696,7 +1630,7 @@ export interface OutputFileDestination { container?: OutputFileBlobContainerDestination; } -// @public (undocumented) +// @public export type OutputFileUploadCondition = "tasksuccess" | "taskfailure" | "taskcompletion"; // @public @@ -1721,7 +1655,7 @@ export interface PoolEndpointConfiguration { inboundNatPools: InboundNATPool[]; } -// @public (undocumented) +// @public export interface PoolExistsOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -1731,7 +1665,7 @@ export interface PoolExistsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export type PoolIdentityType = "UserAssigned" | "None"; // @public @@ -1740,14 +1674,8 @@ export interface PoolInformation { poolId?: string; } -// @public (undocumented) -export type PoolLifetimeOption = "jobschedule" | "job"; - // @public -export interface PoolListUsageMetricsResult { - "odata.nextLink"?: string; - value?: PoolUsageMetrics[]; -} +export type PoolLifetimeOption = "jobschedule" | "job"; // @public export interface PoolNodeCounts { @@ -1756,12 +1684,6 @@ export interface PoolNodeCounts { poolId: string; } -// @public -export interface PoolNodeCountsListResult { - "odata.nextLink"?: string; - value?: PoolNodeCounts[]; -} - // @public export interface PoolSpecification { applicationLicenses?: string[]; @@ -1788,7 +1710,7 @@ export interface PoolSpecification { vmSize: string; } -// @public (undocumented) +// @public export type PoolState = "active" | "deleting"; // @public @@ -1815,7 +1737,7 @@ export interface PublicIpAddressConfiguration { ipAddressProvisioningType?: IpAddressProvisioningType; } -// @public (undocumented) +// @public export interface ReactivateTaskOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -1825,7 +1747,7 @@ export interface ReactivateTaskOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface RebootNodeOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1838,14 +1760,14 @@ export interface RecentJob { url?: string; } -// @public (undocumented) +// @public export interface ReimageNodeOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface RemoveNodesOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1856,7 +1778,7 @@ export interface RemoveNodesOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ReplaceJobOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1867,7 +1789,7 @@ export interface ReplaceJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ReplaceJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1878,21 +1800,21 @@ export interface ReplaceJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ReplaceNodeUserOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface ReplaceTaskOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1910,7 +1832,7 @@ export interface ResizeError { values?: NameValuePair[]; } -// @public (undocumented) +// @public export interface ResizePoolOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -1957,7 +1879,7 @@ export interface Schedule { startWindow?: string; } -// @public (undocumented) +// @public export type SchedulingState = "enabled" | "disabled"; // @public @@ -1984,13 +1906,13 @@ export interface StartTaskInformation { state: StartTaskState; } -// @public (undocumented) +// @public export type StartTaskState = "running" | "completed"; -// @public (undocumented) +// @public export type StatusLevelTypes = "Error" | "Info" | "Warning"; -// @public (undocumented) +// @public export interface StopPoolResizeOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -2000,7 +1922,7 @@ export interface StopPoolResizeOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export type StorageAccountType = "standard_lrs" | "premium_lrs"; // @public @@ -2019,7 +1941,7 @@ export interface SubtaskInformation { stateTransitionTime?: Date; } -// @public (undocumented) +// @public export type SubtaskState = "preparing" | "running" | "completed"; // @public @@ -2037,7 +1959,7 @@ export interface TaskAddResult { taskId: string; } -// @public (undocumented) +// @public export type TaskAddStatus = "Success" | "clienterror" | "servererror"; // @public @@ -2097,7 +2019,7 @@ export interface TaskExecutionInformation { startTime?: Date; } -// @public (undocumented) +// @public export type TaskExecutionResult = "success" | "failure"; // @public @@ -2138,7 +2060,7 @@ export interface TaskSlotCounts { succeeded: number; } -// @public (undocumented) +// @public export type TaskState = "active" | "preparing" | "running" | "completed"; // @public @@ -2156,7 +2078,7 @@ export interface TaskStatistics { writeIOps: number; } -// @public (undocumented) +// @public export interface TerminateJobOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -2167,7 +2089,7 @@ export interface TerminateJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface TerminateJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -2177,7 +2099,7 @@ export interface TerminateJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface TerminateTaskOptionalParams extends OperationOptions { apiVersion?: string; ifMatch?: string; @@ -2187,7 +2109,7 @@ export interface TerminateTaskOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface UpdateJobOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -2198,7 +2120,7 @@ export interface UpdateJobOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface UpdateJobScheduleOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -2209,7 +2131,7 @@ export interface UpdateJobScheduleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } -// @public (undocumented) +// @public export interface UpdatePoolOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -2234,7 +2156,7 @@ export interface UploadBatchServiceLogsResult { virtualDirectoryName: string; } -// @public (undocumented) +// @public export interface UploadNodeLogsOptionalParams extends OperationOptions { apiVersion?: string; contentType?: string; @@ -2270,10 +2192,10 @@ export interface UserIdentity { username?: string; } -// @public (undocumented) +// @public export type VerificationType = "verified" | "unverified"; -// @public (undocumented) +// @public export type Versions = "2023-05-01.17.0"; // @public diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts index f5bc92bd2d..df158ccd83 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { BatchContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface BatchClientOptions extends ClientOptions {} export { BatchContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts index fa22a6ad86..1c387bd4e9 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts @@ -2,6 +2,37 @@ // Licensed under the MIT license. import { + startTaskSerializer, + taskContainerSettingsSerializer, + batchNodeIdentityReferenceSerializer, + resourceFileSerializer, + environmentSettingSerializer, + userIdentitySerializer, + certificateReferenceSerializer, + batchTaskCreateOptionsSerializer, + exitConditionsSerializer, + outputFileSerializer, + affinityInformationSerializer, + taskConstraintsSerializer, + multiInstanceSettingsSerializer, + taskDependenciesSerializer, + applicationPackageReferenceSerializer, + authenticationTokenSettingsSerializer, + scheduleSerializer, + jobSpecificationSerializer, + jobNetworkConfigurationSerializer, + jobConstraintsSerializer, + jobManagerTaskSerializer, + jobPreparationTaskSerializer, + jobReleaseTaskSerializer, + poolInformationSerializer, + cloudServiceConfigurationSerializer, + virtualMachineConfigurationSerializer, + taskSchedulingPolicySerializer, + networkConfigurationSerializer, + userAccountSerializer, + metadataItemSerializer, + mountConfigurationSerializer, BatchNodeUserCreateOptions, BatchNodeUserUpdateOptions, BatchNode, @@ -11,13 +42,9 @@ import { BatchNodeRemoteLoginSettingsResult, UploadBatchServiceLogsOptions, UploadBatchServiceLogsResult, - BatchNodeListResult, NodeVMExtension, - NodeVMExtensionList, - NodeFileListResult, NodeFile, BatchTaskCreateOptions, - BatchTaskListResult, BatchTask, BatchTaskCollection, TaskAddCollectionResult, @@ -25,26 +52,18 @@ import { BatchJobSchedule, BatchJobScheduleUpdateOptions, BatchJobScheduleCreateOptions, - BatchJobScheduleListResult, BatchCertificate, - CertificateListResult, BatchJob, BatchJobUpdateOptions, BatchJobDisableOptions, BatchJobTerminateOptions, BatchJobCreateOptions, - BatchJobListResult, - BatchJobListPreparationAndReleaseTaskStatusResult, JobPreparationAndReleaseTaskExecutionInformation, TaskCountsResult, - AccountListSupportedImagesResult, ImageInformation, - PoolNodeCountsListResult, PoolNodeCounts, - PoolListUsageMetricsResult, PoolUsageMetrics, BatchPoolCreateOptions, - BatchPoolListResult, BatchPool, AutoScaleRun, BatchPoolUpdateOptions, @@ -53,8 +72,20 @@ import { BatchPoolResizeOptions, BatchPoolReplaceOptions, NodeRemoveOptions, - ApplicationListResult, BatchApplication, + _AccountListSupportedImagesResult, + _ApplicationListResult, + _BatchJobListPreparationAndReleaseTaskStatusResult, + _BatchJobListResult, + _BatchJobScheduleListResult, + _BatchNodeListResult, + _BatchPoolListResult, + _BatchTaskListResult, + _CertificateListResult, + _NodeFileListResult, + _NodeVMExtensionList, + _PoolListUsageMetricsResult, + _PoolNodeCountsListResult, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; @@ -321,7 +352,7 @@ export function _listApplicationsSend( export async function _listApplicationsDeserialize( result: ListApplications200Response | ListApplicationsDefaultResponse, -): Promise { +): Promise<_ApplicationListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -427,7 +458,7 @@ export function _listPoolUsageMetricsSend( export async function _listPoolUsageMetricsDeserialize( result: ListPoolUsageMetrics200Response | ListPoolUsageMetricsDefaultResponse, -): Promise { +): Promise<_PoolListUsageMetricsResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -488,124 +519,13 @@ export function _createPoolSend( displayName: body["displayName"], vmSize: body["vmSize"], cloudServiceConfiguration: !body.cloudServiceConfiguration - ? undefined - : { - osFamily: body.cloudServiceConfiguration?.["osFamily"], - osVersion: body.cloudServiceConfiguration?.["osVersion"], - }, + ? body.cloudServiceConfiguration + : cloudServiceConfigurationSerializer(body.cloudServiceConfiguration), virtualMachineConfiguration: !body.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.virtualMachineConfiguration?.imageReference["publisher"], - offer: - body.virtualMachineConfiguration?.imageReference["offer"], - sku: body.virtualMachineConfiguration?.imageReference["sku"], - version: - body.virtualMachineConfiguration?.imageReference["version"], - virtualMachineImageId: - body.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.virtualMachineConfiguration?.["nodeAgentSkuId"], - windowsConfiguration: !body.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.virtualMachineConfiguration?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.virtualMachineConfiguration?.["dataDisks"] === undefined - ? body.virtualMachineConfiguration?.["dataDisks"] - : body.virtualMachineConfiguration?.["dataDisks"].map( - (p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: p["storageAccountType"], - }), - ), - licenseType: body.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.virtualMachineConfiguration - ?.containerConfiguration?.["containerImageNames"], - containerRegistries: - body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] === - undefined - ? body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] - : body.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !body.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !body.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - body.virtualMachineConfiguration?.["extensions"] === undefined - ? body.virtualMachineConfiguration?.["extensions"] - : body.virtualMachineConfiguration?.["extensions"].map( - (p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: p["provisionAfterExtensions"], - }), - ), - osDisk: !body.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, - }, + ? body.virtualMachineConfiguration + : virtualMachineConfigurationSerializer( + body.virtualMachineConfiguration, + ), resizeTimeout: body["resizeTimeout"], targetDedicatedNodes: body["targetDedicatedNodes"], targetLowPriorityNodes: body["targetLowPriorityNodes"], @@ -614,241 +534,38 @@ export function _createPoolSend( autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], enableInterNodeCommunication: body["enableInterNodeCommunication"], networkConfiguration: !body.networkConfiguration - ? undefined - : { - subnetId: body.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !body.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.networkConfiguration?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.networkConfiguration?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.networkConfiguration?.["enableAcceleratedNetworking"], - }, + ? body.networkConfiguration + : networkConfigurationSerializer(body.networkConfiguration), startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.startTask?.["resourceFiles"] === undefined - ? body.startTask?.["resourceFiles"] - : body.startTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.startTask?.["environmentSettings"] === undefined - ? body.startTask?.["environmentSettings"] - : body.startTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, + ? body.startTask + : startTaskSerializer(body.startTask), certificateReferences: body["certificateReferences"] === undefined ? body["certificateReferences"] - : body["certificateReferences"].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), + : body["certificateReferences"].map(certificateReferenceSerializer), applicationPackageReferences: body["applicationPackageReferences"] === undefined ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), + : body["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), applicationLicenses: body["applicationLicenses"], taskSlotsPerNode: body["taskSlotsPerNode"], taskSchedulingPolicy: !body.taskSchedulingPolicy - ? undefined - : { nodeFillType: body.taskSchedulingPolicy?.["nodeFillType"] }, + ? body.taskSchedulingPolicy + : taskSchedulingPolicySerializer(body.taskSchedulingPolicy), userAccounts: body["userAccounts"] === undefined ? body["userAccounts"] - : body["userAccounts"].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, - })), + : body["userAccounts"].map(userAccountSerializer), metadata: body["metadata"] === undefined ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + : body["metadata"].map(metadataItemSerializer), mountConfiguration: body["mountConfiguration"] === undefined ? body["mountConfiguration"] - : body["mountConfiguration"].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.["accountName"], - containerName: - p.azureBlobFileSystemConfiguration?.["containerName"], - accountKey: - p.azureBlobFileSystemConfiguration?.["accountKey"], - sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p.azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.["relativeMountPath"], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], - }, - })), + : body["mountConfiguration"].map(mountConfigurationSerializer), targetNodeCommunicationMode: body["targetNodeCommunicationMode"], }, }); @@ -899,7 +616,7 @@ export function _listPoolsSend( export async function _listPoolsDeserialize( result: ListPools200Response | ListPoolsDefaultResponse, -): Promise { +): Promise<_BatchPoolListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -2121,107 +1838,22 @@ export function _updatePoolSend( }, body: { startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.startTask?.["resourceFiles"] === undefined - ? body.startTask?.["resourceFiles"] - : body.startTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.startTask?.["environmentSettings"] === undefined - ? body.startTask?.["environmentSettings"] - : body.startTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, + ? body.startTask + : startTaskSerializer(body.startTask), certificateReferences: body["certificateReferences"] === undefined ? body["certificateReferences"] - : body["certificateReferences"].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), + : body["certificateReferences"].map(certificateReferenceSerializer), applicationPackageReferences: body["applicationPackageReferences"] === undefined ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), + : body["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), metadata: body["metadata"] === undefined ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + : body["metadata"].map(metadataItemSerializer), targetNodeCommunicationMode: body["targetNodeCommunicationMode"], }, }); @@ -2577,97 +2209,15 @@ export function _replacePoolPropertiesSend( }, body: { startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.startTask?.["resourceFiles"] === undefined - ? body.startTask?.["resourceFiles"] - : body.startTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.startTask?.["environmentSettings"] === undefined - ? body.startTask?.["environmentSettings"] - : body.startTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, - certificateReferences: body["certificateReferences"].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), + ? body.startTask + : startTaskSerializer(body.startTask), + certificateReferences: body["certificateReferences"].map( + certificateReferenceSerializer, + ), applicationPackageReferences: body["applicationPackageReferences"].map( - (p) => ({ applicationId: p["applicationId"], version: p["version"] }), + applicationPackageReferenceSerializer, ), - metadata: body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + metadata: body["metadata"].map(metadataItemSerializer), targetNodeCommunicationMode: body["targetNodeCommunicationMode"], }, }); @@ -2789,7 +2339,7 @@ export function _listSupportedImagesSend( export async function _listSupportedImagesDeserialize( result: ListSupportedImages200Response | ListSupportedImagesDefaultResponse, -): Promise { +): Promise<_AccountListSupportedImagesResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -2854,7 +2404,7 @@ export function _listPoolNodeCountsSend( export async function _listPoolNodeCountsDeserialize( result: ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse, -): Promise { +): Promise<_PoolNodeCountsListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -4114,8460 +3664,1703 @@ export function _updateJobSend( allowTaskPreemption: body["allowTaskPreemption"], maxParallelTasks: body["maxParallelTasks"], constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, + ? body.constraints + : jobConstraintsSerializer(body.constraints), poolInfo: !body.poolInfo - ? undefined - : { - poolId: body.poolInfo?.["poolId"], - autoPoolSpecification: !body.poolInfo?.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo?.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.poolInfo?.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.poolInfo?.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo?.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.poolInfo?.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo - ?.autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo?.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.poolInfo?.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.poolInfo?.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.poolInfo?.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo?.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - ?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : body.poolInfo?.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : body.poolInfo?.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool?.[ - "metadata" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? body.poolInfo?.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : body.poolInfo?.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _updateJobDeserialize( - result: UpdateJob200Response | UpdateJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * This replaces only the Job properties specified in the request. For example, if - * the Job has constraints, and a request does not specify the constraints - * element, then the Job keeps the existing constraints. - */ -export async function updateJob( - context: Client, - jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateJobSend(context, jobId, body, options); - return _updateJobDeserialize(result); -} - -export function _replaceJobSend( - context: Client, - jobId: string, - body: BatchJob, - options: ReplaceJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs/{jobId}", jobId) - .put({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] === - undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }), - ), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _replaceJobDeserialize( - result: ReplaceJob200Response | ReplaceJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * This fully replaces all the updatable properties of the Job. For example, if - * the Job has constraints associated with it and if constraints is not specified - * with this request, then the Batch service will remove the existing constraints. - */ -export async function replaceJob( - context: Client, - jobId: string, - body: BatchJob, - options: ReplaceJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _replaceJobSend(context, jobId, body, options); - return _replaceJobDeserialize(result); -} - -export function _disableJobSend( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs/{jobId}/disable", jobId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { disableTasks: body["disableTasks"] }, - }); -} - -export async function _disableJobDeserialize( - result: DisableJob202Response | DisableJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * The Batch Service immediately moves the Job to the disabling state. Batch then - * uses the disableTasks parameter to determine what to do with the currently - * running Tasks of the Job. The Job remains in the disabling state until the - * disable operation is completed and all Tasks have been dealt with according to - * the disableTasks option; the Job then moves to the disabled state. No new Tasks - * are started under the Job until it moves back to active state. If you try to - * disable a Job that is in any state other than active, disabling, or disabled, - * the request fails with status code 409. - */ -export async function disableJob( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _disableJobSend(context, jobId, body, options); - return _disableJobDeserialize(result); -} - -export function _enableJobSend( - context: Client, - jobId: string, - options: EnableJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs/{jobId}/enable", jobId) - .post({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _enableJobDeserialize( - result: EnableJob202Response | EnableJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * When you call this API, the Batch service sets a disabled Job to the enabling - * state. After the this operation is completed, the Job moves to the active - * state, and scheduling of new Tasks under the Job resumes. The Batch service - * does not allow a Task to remain in the active state for more than 180 days. - * Therefore, if you enable a Job containing active Tasks which were added more - * than 180 days ago, those Tasks will not run. - */ -export async function enableJob( - context: Client, - jobId: string, - options: EnableJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _enableJobSend(context, jobId, options); - return _enableJobDeserialize(result); -} - -export function _terminateJobSend( - context: Client, - jobId: string, - body?: BatchJobTerminateOptions, - options: TerminateJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs/{jobId}/terminate", jobId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: - body === undefined - ? body - : { terminateReason: body["terminateReason"] }, - }); -} - -export async function _terminateJobDeserialize( - result: TerminateJob202Response | TerminateJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * When a Terminate Job request is received, the Batch service sets the Job to the - * terminating state. The Batch service then terminates any running Tasks - * associated with the Job and runs any required Job release Tasks. Then the Job - * moves into the completed state. If there are any Tasks in the Job in the active - * state, they will remain in the active state. Once a Job is terminated, new - * Tasks cannot be added and any remaining active Tasks will not be scheduled. - */ -export async function terminateJob( - context: Client, - jobId: string, - body?: BatchJobTerminateOptions, - options: TerminateJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _terminateJobSend(context, jobId, body, options); - return _terminateJobDeserialize(result); -} - -export function _createJobSend( - context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { - id: body["id"], - displayName: body["displayName"], - usesTaskDependencies: body["usesTaskDependencies"], - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobManagerTask - ? undefined - : { - id: body.jobManagerTask?.["id"], - displayName: body.jobManagerTask?.["displayName"], - commandLine: body.jobManagerTask?.["commandLine"], - containerSettings: !body.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobManagerTask?.containerSettings?.["imageName"], - registry: !body.jobManagerTask?.containerSettings?.registry - ? undefined - : { - username: - body.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.jobManagerTask?.["resourceFiles"] === undefined - ? body.jobManagerTask?.["resourceFiles"] - : body.jobManagerTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: - body.jobManagerTask?.["outputFiles"] === undefined - ? body.jobManagerTask?.["outputFiles"] - : body.jobManagerTask?.["outputFiles"].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - body.jobManagerTask?.["environmentSettings"] === undefined - ? body.jobManagerTask?.["environmentSettings"] - : body.jobManagerTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - constraints: !body.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: body.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: body.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobManagerTask?.userIdentity - ? undefined - : { - username: body.jobManagerTask?.userIdentity?.["username"], - autoUser: !body.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: body.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - body.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? body.jobManagerTask?.["applicationPackageReferences"] - : body.jobManagerTask?.["applicationPackageReferences"].map( - (p) => ({ - applicationId: p["applicationId"], - version: p["version"], - }), - ), - authenticationTokenSettings: !body.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - body.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - body.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !body.jobPreparationTask - ? undefined - : { - id: body.jobPreparationTask?.["id"], - commandLine: body.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobPreparationTask?.containerSettings?.["imageName"], - registry: !body.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - body.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.jobPreparationTask?.["resourceFiles"] === undefined - ? body.jobPreparationTask?.["resourceFiles"] - : body.jobPreparationTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobPreparationTask?.["environmentSettings"] === undefined - ? body.jobPreparationTask?.["environmentSettings"] - : body.jobPreparationTask?.["environmentSettings"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - constraints: !body.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: body.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobPreparationTask?.userIdentity - ? undefined - : { - username: - body.jobPreparationTask?.userIdentity?.["username"], - autoUser: !body.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !body.jobReleaseTask - ? undefined - : { - id: body.jobReleaseTask?.["id"], - commandLine: body.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobReleaseTask?.containerSettings?.["imageName"], - registry: !body.jobReleaseTask?.containerSettings?.registry - ? undefined - : { - username: - body.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobReleaseTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.jobReleaseTask?.["resourceFiles"] === undefined - ? body.jobReleaseTask?.["resourceFiles"] - : body.jobReleaseTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobReleaseTask?.["environmentSettings"] === undefined - ? body.jobReleaseTask?.["environmentSettings"] - : body.jobReleaseTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - maxWallClockTime: body.jobReleaseTask?.["maxWallClockTime"], - retentionTime: body.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobReleaseTask?.userIdentity - ? undefined - : { - username: body.jobReleaseTask?.userIdentity?.["username"], - autoUser: !body.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - body["commonEnvironmentSettings"] === undefined - ? body["commonEnvironmentSettings"] - : body["commonEnvironmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] === - undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }), - ), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : body.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - onTaskFailure: body["onTaskFailure"], - networkConfiguration: !body.networkConfiguration - ? undefined - : { subnetId: body.networkConfiguration?.["subnetId"] }, - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _createJobDeserialize( - result: CreateJob201Response | CreateJobDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * The Batch service supports two ways to control the work done as part of a Job. - * In the first approach, the user specifies a Job Manager Task. The Batch service - * launches this Task when it is ready to start the Job. The Job Manager Task - * controls all other Tasks that run under this Job, by using the Task APIs. In - * the second approach, the user directly controls the execution of Tasks under an - * active Job, by using the Task APIs. Also note: when naming Jobs, avoid - * including sensitive information such as user names or secret project names. - * This information may appear in telemetry logs accessible to Microsoft Support - * engineers. - */ -export async function createJob( - context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createJobSend(context, body, options); - return _createJobDeserialize(result); -} - -export function _listJobsSend( - context: Client, - options: ListJobsOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _listJobsDeserialize( - result: ListJobs200Response | ListJobsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p) => ({ - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobManagerTask?.["resourceFiles"] === undefined - ? p.jobManagerTask?.["resourceFiles"] - : p.jobManagerTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - outputFiles: - p.jobManagerTask?.["outputFiles"] === undefined - ? p.jobManagerTask?.["outputFiles"] - : p.jobManagerTask?.["outputFiles"].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - p.jobManagerTask?.["environmentSettings"] === undefined - ? p.jobManagerTask?.["environmentSettings"] - : p.jobManagerTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - constraints: !p.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity - ? undefined - : { - username: p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: p.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - p.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? p.jobManagerTask?.["applicationPackageReferences"] - : p.jobManagerTask?.["applicationPackageReferences"].map( - (p) => ({ - applicationId: p["applicationId"], - version: p["version"], - }), - ), - authenticationTokenSettings: !p.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - p.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - p.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !p.jobPreparationTask - ? undefined - : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !p.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - p.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobPreparationTask?.["resourceFiles"] === undefined - ? p.jobPreparationTask?.["resourceFiles"] - : p.jobPreparationTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - p.jobPreparationTask?.["environmentSettings"] === undefined - ? p.jobPreparationTask?.["environmentSettings"] - : p.jobPreparationTask?.["environmentSettings"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - constraints: !p.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - p.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity - ? undefined - : { - username: - p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !p.jobReleaseTask - ? undefined - : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobReleaseTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobReleaseTask?.["resourceFiles"] === undefined - ? p.jobReleaseTask?.["resourceFiles"] - : p.jobReleaseTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - p.jobReleaseTask?.["environmentSettings"] === undefined - ? p.jobReleaseTask?.["environmentSettings"] - : p.jobReleaseTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity - ? undefined - : { - username: p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - p["commonEnvironmentSettings"] === undefined - ? p["commonEnvironmentSettings"] - : p["commonEnvironmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - p.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["exactVersion"], - }, - nodeAgentSkuId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - p.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIpAddressConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: - p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: p.executionInfo?.schedulingError?.["message"], - details: - p.executionInfo?.schedulingError?.["details"] === - undefined - ? p.executionInfo?.schedulingError?.["details"] - : p.executionInfo?.schedulingError?.["details"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists all of the Jobs in the specified Account. */ -export function listJobs( - context: Client, - options: ListJobsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobsSend(context, options), - _listJobsDeserialize, - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); -} - -export function _listJobsFromScheduleSend( - context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _listJobsFromScheduleDeserialize( - result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p) => ({ - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobManagerTask?.["resourceFiles"] === undefined - ? p.jobManagerTask?.["resourceFiles"] - : p.jobManagerTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - outputFiles: - p.jobManagerTask?.["outputFiles"] === undefined - ? p.jobManagerTask?.["outputFiles"] - : p.jobManagerTask?.["outputFiles"].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - p.jobManagerTask?.["environmentSettings"] === undefined - ? p.jobManagerTask?.["environmentSettings"] - : p.jobManagerTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - constraints: !p.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity - ? undefined - : { - username: p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: p.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - p.jobManagerTask?.["applicationPackageReferences"] === - undefined - ? p.jobManagerTask?.["applicationPackageReferences"] - : p.jobManagerTask?.["applicationPackageReferences"].map( - (p) => ({ - applicationId: p["applicationId"], - version: p["version"], - }), - ), - authenticationTokenSettings: !p.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - p.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - p.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !p.jobPreparationTask - ? undefined - : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !p.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - p.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - p.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobPreparationTask?.["resourceFiles"] === undefined - ? p.jobPreparationTask?.["resourceFiles"] - : p.jobPreparationTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - p.jobPreparationTask?.["environmentSettings"] === undefined - ? p.jobPreparationTask?.["environmentSettings"] - : p.jobPreparationTask?.["environmentSettings"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - constraints: !p.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - p.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity - ? undefined - : { - username: - p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !p.jobReleaseTask - ? undefined - : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobReleaseTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.jobReleaseTask?.["resourceFiles"] === undefined - ? p.jobReleaseTask?.["resourceFiles"] - : p.jobReleaseTask?.["resourceFiles"].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - p.jobReleaseTask?.["environmentSettings"] === undefined - ? p.jobReleaseTask?.["environmentSettings"] - : p.jobReleaseTask?.["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity - ? undefined - : { - username: p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - p["commonEnvironmentSettings"] === undefined - ? p["commonEnvironmentSettings"] - : p["commonEnvironmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - p.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["exactVersion"], - }, - nodeAgentSkuId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.poolInfo.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - p.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNatPools: - p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIpAddressConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] === undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] === - undefined - ? p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: - p["metadata"] === undefined - ? p["metadata"] - : p["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: - p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: p.executionInfo?.schedulingError?.["message"], - details: - p.executionInfo?.schedulingError?.["details"] === - undefined - ? p.executionInfo?.schedulingError?.["details"] - : p.executionInfo?.schedulingError?.["details"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists the Jobs that have been created under the specified Job Schedule. */ -export function listJobsFromSchedule( - context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobsFromScheduleSend(context, jobScheduleId, options), - _listJobsFromScheduleDeserialize, - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); -} - -export function _listJobPreparationAndReleaseTaskStatusSend( - context: Client, - jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { - requestOptions: {}, - }, -): StreamableMethod< - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse -> { - return context - .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - }, - }); -} - -export async function _listJobPreparationAndReleaseTaskStatusDeserialize( - result: - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p) => ({ - poolId: p["poolId"], - nodeId: p["nodeId"], - nodeUrl: p["nodeUrl"], - jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo - ? undefined - : { - startTime: new Date( - p.jobPreparationTaskExecutionInfo?.["startTime"], - ), - endTime: - p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobPreparationTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobPreparationTaskExecutionInfo - ?.containerInfo - ? undefined - : { - containerId: - p.jobPreparationTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobPreparationTaskExecutionInfo?.containerInfo?.[ - "state" - ], - error: - p.jobPreparationTaskExecutionInfo?.containerInfo?.[ - "error" - ], - }, - failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo - ? undefined - : { - category: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "code" - ], - message: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "message" - ], - details: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ] === undefined - ? p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ] - : p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], - lastRetryTime: - p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== - undefined - ? new Date( - p.jobPreparationTaskExecutionInfo?.["lastRetryTime"], - ) - : undefined, - result: p.jobPreparationTaskExecutionInfo?.["result"], - }, - jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo - ? undefined - : { - startTime: new Date( - p.jobReleaseTaskExecutionInfo?.["startTime"], - ), - endTime: - p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobReleaseTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo - ? undefined - : { - containerId: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "state" - ], - error: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "error" - ], - }, - failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo - ? undefined - : { - category: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "code" - ], - message: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "message" - ], - details: - p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ] === undefined - ? p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ] - : p.jobReleaseTaskExecutionInfo?.failureInfo?.[ - "details" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - result: p.jobReleaseTaskExecutionInfo?.["result"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** - * This API returns the Job Preparation and Job Release Task status on all Compute - * Nodes that have run the Job Preparation or Job Release Task. This includes - * Compute Nodes which have since been removed from the Pool. If this API is - * invoked on a Job which has no Job Preparation or Job Release Task, the Batch - * service returns HTTP status code 409 (Conflict) with an error code of - * JobPreparationTaskNotSpecified. - */ -export function listJobPreparationAndReleaseTaskStatus( - context: Client, - jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { - requestOptions: {}, - }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), - _listJobPreparationAndReleaseTaskStatusDeserialize, - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); -} - -export function _getJobTaskCountsSend( - context: Client, - jobId: string, - options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, -): StreamableMethod< - GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse -> { - return context - .path("/jobs/{jobId}/taskcounts", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _getJobTaskCountsDeserialize( - result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - taskCounts: { - active: result.body.taskCounts["active"], - running: result.body.taskCounts["running"], - completed: result.body.taskCounts["completed"], - succeeded: result.body.taskCounts["succeeded"], - failed: result.body.taskCounts["failed"], - }, - taskSlotCounts: { - active: result.body.taskSlotCounts["active"], - running: result.body.taskSlotCounts["running"], - completed: result.body.taskSlotCounts["completed"], - succeeded: result.body.taskSlotCounts["succeeded"], - failed: result.body.taskSlotCounts["failed"], - }, - }; -} - -/** - * Task counts provide a count of the Tasks by active, running or completed Task - * state, and a count of Tasks which succeeded or failed. Tasks in the preparing - * state are counted as running. Note that the numbers returned may not always be - * up to date. If you need exact task counts, use a list query. - */ -export async function getJobTaskCounts( - context: Client, - jobId: string, - options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getJobTaskCountsSend(context, jobId, options); - return _getJobTaskCountsDeserialize(result); -} - -export function _createCertificateSend( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptionalParams = { requestOptions: {} }, -): StreamableMethod< - CreateCertificate201Response | CreateCertificateDefaultResponse -> { - return context - .path("/certificates") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { - thumbprint: body["thumbprint"], - thumbprintAlgorithm: body["thumbprintAlgorithm"], - data: uint8ArrayToString(body["data"], "base64"), - certificateFormat: body["certificateFormat"], - password: body["password"], - }, - }); -} - -export async function _createCertificateDeserialize( - result: CreateCertificate201Response | CreateCertificateDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** Creates a Certificate to the specified Account. */ -export async function createCertificate( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createCertificateSend(context, body, options); - return _createCertificateDeserialize(result); -} - -export function _listCertificatesSend( - context: Client, - options: ListCertificatesOptionalParams = { requestOptions: {} }, -): StreamableMethod< - ListCertificates200Response | ListCertificatesDefaultResponse -> { - return context - .path("/certificates") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: options?.$select, - }, - }); -} - -export async function _listCertificatesDeserialize( - result: ListCertificates200Response | ListCertificatesDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - value: - result.body["value"] === undefined - ? result.body["value"] - : result.body["value"].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - url: p["url"], - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - publicData: - typeof p["publicData"] === "string" - ? stringToUint8Array(p["publicData"], "base64") - : p["publicData"], - deleteCertificateError: !p.deleteCertificateError - ? undefined - : { - code: p.deleteCertificateError?.["code"], - message: p.deleteCertificateError?.["message"], - values: - p.deleteCertificateError?.["values"] === undefined - ? p.deleteCertificateError?.["values"] - : p.deleteCertificateError?.["values"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - data: - typeof p["data"] === "string" - ? stringToUint8Array(p["data"], "base64") - : p["data"], - certificateFormat: p["certificateFormat"], - password: p["password"], - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists all of the Certificates that have been added to the specified Account. */ -export function listCertificates( - context: Client, - options: ListCertificatesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listCertificatesSend(context, options), - _listCertificatesDeserialize, - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); -} - -export function _cancelCertificateDeletionSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, -): StreamableMethod< - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse -> { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", - thumbprintAlgorithm, - thumbprint, - ) - .post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _cancelCertificateDeletionDeserialize( - result: - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * If you try to delete a Certificate that is being used by a Pool or Compute - * Node, the status of the Certificate changes to deleteFailed. If you decide that - * you want to continue using the Certificate, you can use this operation to set - * the status of the Certificate back to active. If you intend to delete the - * Certificate, you do not need to run this operation after the deletion failed. - * You must make sure that the Certificate is not being used by any resources, and - * then you can try again to delete the Certificate. - */ -export async function cancelCertificateDeletion( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _cancelCertificateDeletionSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _cancelCertificateDeletionDeserialize(result); -} - -export function _deleteCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptionalParams = { requestOptions: {} }, -): StreamableMethod< - DeleteCertificate202Response | DeleteCertificateDefaultResponse -> { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint, - ) - .delete({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _deleteCertificateDeserialize( - result: DeleteCertificate202Response | DeleteCertificateDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * You cannot delete a Certificate if a resource (Pool or Compute Node) is using - * it. Before you can delete a Certificate, you must therefore make sure that the - * Certificate is not associated with any existing Pools, the Certificate is not - * installed on any Nodes (even if you remove a Certificate from a Pool, it is not - * removed from existing Compute Nodes in that Pool until they restart), and no - * running Tasks depend on the Certificate. If you try to delete a Certificate - * that is in use, the deletion fails. The Certificate status changes to - * deleteFailed. You can use Cancel Delete Certificate to set the status back to - * active if you decide that you want to continue using the Certificate. - */ -export async function deleteCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _deleteCertificateDeserialize(result); -} - -export function _getCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint, - ) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - }, - }); -} - -export async function _getCertificateDeserialize( - result: GetCertificate200Response | GetCertificateDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - thumbprint: result.body["thumbprint"], - thumbprintAlgorithm: result.body["thumbprintAlgorithm"], - url: result.body["url"], - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - publicData: - typeof result.body["publicData"] === "string" - ? stringToUint8Array(result.body["publicData"], "base64") - : result.body["publicData"], - deleteCertificateError: !result.body.deleteCertificateError - ? undefined - : { - code: result.body.deleteCertificateError?.["code"], - message: result.body.deleteCertificateError?.["message"], - values: - result.body.deleteCertificateError?.["values"] === undefined - ? result.body.deleteCertificateError?.["values"] - : result.body.deleteCertificateError?.["values"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - data: - typeof result.body["data"] === "string" - ? stringToUint8Array(result.body["data"], "base64") - : result.body["data"], - certificateFormat: result.body["certificateFormat"], - password: result.body["password"], - }; -} - -/** Gets information about the specified Certificate. */ -export async function getCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _getCertificateDeserialize(result); -} - -export function _jobScheduleExistsSend( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptionalParams = { requestOptions: {} }, -): StreamableMethod< - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .head({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _jobScheduleExistsDeserialize( - result: - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** Checks the specified Job Schedule exists. */ -export async function jobScheduleExists( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _jobScheduleExistsSend(context, jobScheduleId, options); - return _jobScheduleExistsDeserialize(result); -} - -export function _deleteJobScheduleSend( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .delete({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _deleteJobScheduleDeserialize( - result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; -} - -/** - * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that - * schedule. When Tasks are deleted, all the files in their working directories on - * the Compute Nodes are also deleted (the retention period is ignored). The Job - * Schedule statistics are no longer accessible once the Job Schedule is deleted, - * though they are still counted towards Account lifetime statistics. - */ -export async function deleteJobSchedule( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteJobScheduleSend(context, jobScheduleId, options); - return _deleteJobScheduleDeserialize(result); -} - -export function _getJobScheduleSend( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _getJobScheduleDeserialize( - result: GetJobSchedule200Response | GetJobScheduleDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - schedule: { - doNotRunUntil: - result.body.schedule["doNotRunUntil"] !== undefined - ? new Date(result.body.schedule["doNotRunUntil"]) - : undefined, - doNotRunAfter: - result.body.schedule["doNotRunAfter"] !== undefined - ? new Date(result.body.schedule["doNotRunAfter"]) - : undefined, - startWindow: result.body.schedule["startWindow"], - recurrenceInterval: result.body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: result.body.jobSpecification["priority"], - allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], - displayName: result.body.jobSpecification["displayName"], - usesTaskDependencies: - result.body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], - onTaskFailure: result.body.jobSpecification["onTaskFailure"], - networkConfiguration: !result.body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !result.body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - result.body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !result.body.jobSpecification.jobManagerTask - ? undefined - : { - id: result.body.jobSpecification.jobManagerTask?.["id"], - displayName: - result.body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - result.body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobManagerTask?.["resourceFiles"] === - undefined - ? result.body.jobSpecification.jobManagerTask?.["resourceFiles"] - : result.body.jobSpecification.jobManagerTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: - result.body.jobSpecification.jobManagerTask?.["outputFiles"] === - undefined - ? result.body.jobSpecification.jobManagerTask?.["outputFiles"] - : result.body.jobSpecification.jobManagerTask?.[ - "outputFiles" - ].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - result.body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobSpecification.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !result.body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - result.body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] - : result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !result.body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - result.body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - result.body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !result.body.jobSpecification.jobPreparationTask - ? undefined - : { - id: result.body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - result.body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] - : result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !result.body.jobSpecification.jobReleaseTask - ? undefined - : { - id: result.body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - result.body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] === - undefined - ? result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] - : result.body.jobSpecification.jobReleaseTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - }, - commonEnvironmentSettings: - result.body.jobSpecification["commonEnvironmentSettings"] === undefined - ? result.body.jobSpecification["commonEnvironmentSettings"] - : result.body.jobSpecification["commonEnvironmentSettings"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - poolInfo: { - poolId: result.body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !result.body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool - ? undefined - : { - displayName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSkuId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGb: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["enableAutoScale"], - autoScaleFormula: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNatPools: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p["networkSecurityGroupRules"].map( - (p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - }), - ), - })), - }, - publicIpAddressConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - ipAddressProvisioningType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification - .poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["applicationLicenses"], - userAccounts: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] === undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] === - undefined - ? result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] - : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - metadata: - result.body.jobSpecification["metadata"] === undefined - ? result.body.jobSpecification["metadata"] - : result.body.jobSpecification["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - executionInfo: !result.body.executionInfo - ? undefined - : { - nextRunTime: - result.body.executionInfo?.["nextRunTime"] !== undefined - ? new Date(result.body.executionInfo?.["nextRunTime"]) - : undefined, - recentJob: !result.body.executionInfo?.recentJob - ? undefined - : { - id: result.body.executionInfo?.recentJob?.["id"], - url: result.body.executionInfo?.recentJob?.["url"], - }, - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - }, - metadata: - result.body["metadata"] === undefined - ? result.body["metadata"] - : result.body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], - }, - }; -} - -/** Gets information about the specified Job Schedule. */ -export async function getJobSchedule( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getJobScheduleSend(context, jobScheduleId, options); - return _getJobScheduleDeserialize(result); -} - -export function _updateJobScheduleSend( - context: Client, - jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .patch({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { - schedule: !body.schedule - ? undefined - : { - doNotRunUntil: body.schedule?.["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule?.["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule?.["startWindow"], - recurrenceInterval: body.schedule?.["recurrenceInterval"], - }, - jobSpecification: !body.jobSpecification - ? undefined - : { - priority: body.jobSpecification?.["priority"], - allowTaskPreemption: - body.jobSpecification?.["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification?.["maxParallelTasks"], - displayName: body.jobSpecification?.["displayName"], - usesTaskDependencies: - body.jobSpecification?.["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification?.["onAllTasksComplete"], - onTaskFailure: body.jobSpecification?.["onTaskFailure"], - networkConfiguration: !body.jobSpecification?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification?.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification?.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification?.jobManagerTask - ? undefined - : { - id: body.jobSpecification?.jobManagerTask?.["id"], - displayName: - body.jobSpecification?.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification?.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification?.jobManagerTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification?.jobManagerTask?.[ - "resourceFiles" - ] - : body.jobSpecification?.jobManagerTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - outputFiles: - body.jobSpecification?.jobManagerTask?.["outputFiles"] === - undefined - ? body.jobSpecification?.jobManagerTask?.["outputFiles"] - : body.jobSpecification?.jobManagerTask?.[ - "outputFiles" - ].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: - p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - body.jobSpecification?.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification?.jobManagerTask?.[ - "environmentSettings" - ] - : body.jobSpecification?.jobManagerTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - constraints: !body.jobSpecification?.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.jobManagerTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobManagerTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobSpecification?.jobManagerTask - ?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: - body.jobSpecification?.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification?.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !body.jobSpecification?.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: - body.jobSpecification?.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - body.jobSpecification?.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? body.jobSpecification?.jobManagerTask?.[ - "applicationPackageReferences" - ] - : body.jobSpecification?.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - ?.jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification?.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification?.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification?.jobPreparationTask - ? undefined - : { - id: body.jobSpecification?.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification?.jobPreparationTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification - ?.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobPreparationTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification - ?.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification?.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification?.jobPreparationTask?.[ - "resourceFiles" - ] - : body.jobSpecification?.jobPreparationTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - body.jobSpecification?.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification?.jobPreparationTask?.[ - "environmentSettings" - ] - : body.jobSpecification?.jobPreparationTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - constraints: !body.jobSpecification?.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !body.jobSpecification?.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification?.jobReleaseTask - ? undefined - : { - id: body.jobSpecification?.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification?.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification?.jobReleaseTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification?.jobReleaseTask?.[ - "resourceFiles" - ] - : body.jobSpecification?.jobReleaseTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: - body.jobSpecification?.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification?.jobReleaseTask?.[ - "environmentSettings" - ] - : body.jobSpecification?.jobReleaseTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - maxWallClockTime: - body.jobSpecification?.jobReleaseTask?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification?.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification?.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: - body.jobSpecification?.["commonEnvironmentSettings"] === - undefined - ? body.jobSpecification?.["commonEnvironmentSettings"] - : body.jobSpecification?.["commonEnvironmentSettings"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - poolInfo: { - poolId: body.jobSpecification?.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification?.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osVersion" - ], - }, - virtualMachineConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: - p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: - p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask + ? body.poolInfo + : poolInformationSerializer(body.poolInfo), + onAllTasksComplete: body["onAllTasksComplete"], + metadata: + body["metadata"] === undefined + ? body["metadata"] + : body["metadata"].map(metadataItemSerializer), + }, + }); +} + +export async function _updateJobDeserialize( + result: UpdateJob200Response | UpdateJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * This replaces only the Job properties specified in the request. For example, if + * the Job has constraints, and a request does not specify the constraints + * element, then the Job keeps the existing constraints. + */ +export async function updateJob( + context: Client, + jobId: string, + body: BatchJobUpdateOptions, + options: UpdateJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateJobSend(context, jobId, body, options); + return _updateJobDeserialize(result); +} + +export function _replaceJobSend( + context: Client, + jobId: string, + body: BatchJob, + options: ReplaceJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs/{jobId}", jobId) + .put({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? body.constraints + : jobConstraintsSerializer(body.constraints), + poolInfo: poolInformationSerializer(body.poolInfo), + onAllTasksComplete: body["onAllTasksComplete"], + metadata: + body["metadata"] === undefined + ? body["metadata"] + : body["metadata"].map(metadataItemSerializer), + }, + }); +} + +export async function _replaceJobDeserialize( + result: ReplaceJob200Response | ReplaceJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * This fully replaces all the updatable properties of the Job. For example, if + * the Job has constraints associated with it and if constraints is not specified + * with this request, then the Batch service will remove the existing constraints. + */ +export async function replaceJob( + context: Client, + jobId: string, + body: BatchJob, + options: ReplaceJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _replaceJobSend(context, jobId, body, options); + return _replaceJobDeserialize(result); +} + +export function _disableJobSend( + context: Client, + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs/{jobId}/disable", jobId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { disableTasks: body["disableTasks"] }, + }); +} + +export async function _disableJobDeserialize( + result: DisableJob202Response | DisableJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * The Batch Service immediately moves the Job to the disabling state. Batch then + * uses the disableTasks parameter to determine what to do with the currently + * running Tasks of the Job. The Job remains in the disabling state until the + * disable operation is completed and all Tasks have been dealt with according to + * the disableTasks option; the Job then moves to the disabled state. No new Tasks + * are started under the Job until it moves back to active state. If you try to + * disable a Job that is in any state other than active, disabling, or disabled, + * the request fails with status code 409. + */ +export async function disableJob( + context: Client, + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _disableJobSend(context, jobId, body, options); + return _disableJobDeserialize(result); +} + +export function _enableJobSend( + context: Client, + jobId: string, + options: EnableJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs/{jobId}/enable", jobId) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _enableJobDeserialize( + result: EnableJob202Response | EnableJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * When you call this API, the Batch service sets a disabled Job to the enabling + * state. After the this operation is completed, the Job moves to the active + * state, and scheduling of new Tasks under the Job resumes. The Batch service + * does not allow a Task to remain in the active state for more than 180 days. + * Therefore, if you enable a Job containing active Tasks which were added more + * than 180 days ago, those Tasks will not run. + */ +export async function enableJob( + context: Client, + jobId: string, + options: EnableJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _enableJobSend(context, jobId, options); + return _enableJobDeserialize(result); +} + +export function _terminateJobSend( + context: Client, + jobId: string, + body?: BatchJobTerminateOptions, + options: TerminateJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs/{jobId}/terminate", jobId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: + body === undefined + ? body + : { terminateReason: body["terminateReason"] }, + }); +} + +export async function _terminateJobDeserialize( + result: TerminateJob202Response | TerminateJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * When a Terminate Job request is received, the Batch service sets the Job to the + * terminating state. The Batch service then terminates any running Tasks + * associated with the Job and runs any required Job release Tasks. Then the Job + * moves into the completed state. If there are any Tasks in the Job in the active + * state, they will remain in the active state. Once a Job is terminated, new + * Tasks cannot be added and any remaining active Tasks will not be scheduled. + */ +export async function terminateJob( + context: Client, + jobId: string, + body?: BatchJobTerminateOptions, + options: TerminateJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _terminateJobSend(context, jobId, body, options); + return _terminateJobDeserialize(result); +} + +export function _createJobSend( + context: Client, + body: BatchJobCreateOptions, + options: CreateJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + id: body["id"], + displayName: body["displayName"], + usesTaskDependencies: body["usesTaskDependencies"], + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? body.constraints + : jobConstraintsSerializer(body.constraints), + jobManagerTask: !body.jobManagerTask + ? body.jobManagerTask + : jobManagerTaskSerializer(body.jobManagerTask), + jobPreparationTask: !body.jobPreparationTask + ? body.jobPreparationTask + : jobPreparationTaskSerializer(body.jobPreparationTask), + jobReleaseTask: !body.jobReleaseTask + ? body.jobReleaseTask + : jobReleaseTaskSerializer(body.jobReleaseTask), + commonEnvironmentSettings: + body["commonEnvironmentSettings"] === undefined + ? body["commonEnvironmentSettings"] + : body["commonEnvironmentSettings"].map( + environmentSettingSerializer, + ), + poolInfo: poolInformationSerializer(body.poolInfo), + onAllTasksComplete: body["onAllTasksComplete"], + onTaskFailure: body["onTaskFailure"], + networkConfiguration: !body.networkConfiguration + ? body.networkConfiguration + : jobNetworkConfigurationSerializer(body.networkConfiguration), + metadata: + body["metadata"] === undefined + ? body["metadata"] + : body["metadata"].map(metadataItemSerializer), + }, + }); +} + +export async function _createJobDeserialize( + result: CreateJob201Response | CreateJobDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * The Batch service supports two ways to control the work done as part of a Job. + * In the first approach, the user specifies a Job Manager Task. The Batch service + * launches this Task when it is ready to start the Job. The Job Manager Task + * controls all other Tasks that run under this Job, by using the Task APIs. In + * the second approach, the user directly controls the execution of Tasks under an + * active Job, by using the Task APIs. Also note: when naming Jobs, avoid + * including sensitive information such as user names or secret project names. + * This information may appear in telemetry logs accessible to Microsoft Support + * engineers. + */ +export async function createJob( + context: Client, + body: BatchJobCreateOptions, + options: CreateJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createJobSend(context, body, options); + return _createJobDeserialize(result); +} + +export function _listJobsSend( + context: Client, + options: ListJobsOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _listJobsDeserialize( + result: ListJobs200Response | ListJobsDefaultResponse, +): Promise<_BatchJobListResult> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: + result.body["value"] === undefined + ? result.body["value"] + : result.body["value"].map((p) => ({ + id: p["id"], + displayName: p["displayName"], + usesTaskDependencies: p["usesTaskDependencies"], + url: p["url"], + eTag: p["eTag"], + lastModified: + p["lastModified"] !== undefined + ? new Date(p["lastModified"]) + : undefined, + creationTime: + p["creationTime"] !== undefined + ? new Date(p["creationTime"]) + : undefined, + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + priority: p["priority"], + allowTaskPreemption: p["allowTaskPreemption"], + maxParallelTasks: p["maxParallelTasks"], + constraints: !p.constraints + ? undefined + : { + maxWallClockTime: p.constraints?.["maxWallClockTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !p.jobManagerTask + ? undefined + : { + id: p.jobManagerTask?.["id"], + displayName: p.jobManagerTask?.["displayName"], + commandLine: p.jobManagerTask?.["commandLine"], + containerSettings: !p.jobManagerTask?.containerSettings + ? undefined + : { + containerRunOptions: + p.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobManagerTask?.containerSettings?.["imageName"], + registry: !p.jobManagerTask?.containerSettings?.registry + ? undefined + : { + username: + p.jobManagerTask?.containerSettings?.registry?.[ + "username" + ], + password: + p.jobManagerTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.jobManagerTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobManagerTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobManagerTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobManagerTask?.["resourceFiles"] === undefined + ? p.jobManagerTask?.["resourceFiles"] + : p.jobManagerTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + outputFiles: + p.jobManagerTask?.["outputFiles"] === undefined + ? p.jobManagerTask?.["outputFiles"] + : p.jobManagerTask?.["outputFiles"].map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - commandLine: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.[ - "registryServer" - ], - identityReference: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification - ?.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container + ?.identityReference?.["resourceId"], + }, + uploadHeaders: + p.destination.container?.[ + "uploadHeaders" ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" + ? p.destination.container?.[ + "uploadHeaders" + ] + : p.destination.container?.[ + "uploadHeaders" ].map((p) => ({ name: p["name"], value: p["value"], })), - userIdentity: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], }, - certificateReferences: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: - p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "userAccounts" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "userAccounts" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.[ - "uid" - ], - gid: p.linuxUserConfiguration?.[ - "gid" - ], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: + p.jobManagerTask?.["environmentSettings"] === undefined + ? p.jobManagerTask?.["environmentSettings"] + : p.jobManagerTask?.["environmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + constraints: !p.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + p.jobManagerTask?.constraints?.["maxWallClockTime"], + retentionTime: + p.jobManagerTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + p.jobManagerTask?.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: p.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + p.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !p.jobManagerTask?.userIdentity + ? undefined + : { + username: p.jobManagerTask?.userIdentity?.["username"], + autoUser: !p.jobManagerTask?.userIdentity?.autoUser + ? undefined + : { + scope: + p.jobManagerTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + p.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + runExclusive: p.jobManagerTask?.["runExclusive"], + applicationPackageReferences: + p.jobManagerTask?.["applicationPackageReferences"] === + undefined + ? p.jobManagerTask?.["applicationPackageReferences"] + : p.jobManagerTask?.["applicationPackageReferences"].map( + (p) => ({ + applicationId: p["applicationId"], + version: p["version"], + }), + ), + authenticationTokenSettings: !p.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + p.jobManagerTask?.authenticationTokenSettings?.[ + "access" + ], + }, + allowLowPriorityNode: + p.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !p.jobPreparationTask + ? undefined + : { + id: p.jobPreparationTask?.["id"], + commandLine: p.jobPreparationTask?.["commandLine"], + containerSettings: !p.jobPreparationTask?.containerSettings + ? undefined + : { + containerRunOptions: + p.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobPreparationTask?.containerSettings?.[ + "imageName" + ], + registry: !p.jobPreparationTask?.containerSettings + ?.registry + ? undefined + : { + username: + p.jobPreparationTask?.containerSettings + ?.registry?.["username"], + password: + p.jobPreparationTask?.containerSettings + ?.registry?.["password"], + registryServer: + p.jobPreparationTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !p.jobPreparationTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.jobPreparationTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobPreparationTask?.["resourceFiles"] === undefined + ? p.jobPreparationTask?.["resourceFiles"] + : p.jobPreparationTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + environmentSettings: + p.jobPreparationTask?.["environmentSettings"] === undefined + ? p.jobPreparationTask?.["environmentSettings"] + : p.jobPreparationTask?.["environmentSettings"].map( + (p) => ({ name: p["name"], value: p["value"] }), + ), + constraints: !p.jobPreparationTask?.constraints + ? undefined + : { + maxWallClockTime: + p.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + p.jobPreparationTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + p.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], + userIdentity: !p.jobPreparationTask?.userIdentity + ? undefined + : { + username: + p.jobPreparationTask?.userIdentity?.["username"], + autoUser: !p.jobPreparationTask?.userIdentity?.autoUser + ? undefined + : { + scope: + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + rerunOnNodeRebootAfterSuccess: + p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], + }, + jobReleaseTask: !p.jobReleaseTask + ? undefined + : { + id: p.jobReleaseTask?.["id"], + commandLine: p.jobReleaseTask?.["commandLine"], + containerSettings: !p.jobReleaseTask?.containerSettings + ? undefined + : { + containerRunOptions: + p.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobReleaseTask?.containerSettings?.["imageName"], + registry: !p.jobReleaseTask?.containerSettings?.registry + ? undefined + : { + username: + p.jobReleaseTask?.containerSettings?.registry?.[ + "username" + ], + password: + p.jobReleaseTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.jobReleaseTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobReleaseTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobReleaseTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobReleaseTask?.["resourceFiles"] === undefined + ? p.jobReleaseTask?.["resourceFiles"] + : p.jobReleaseTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + environmentSettings: + p.jobReleaseTask?.["environmentSettings"] === undefined + ? p.jobReleaseTask?.["environmentSettings"] + : p.jobReleaseTask?.["environmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], + retentionTime: p.jobReleaseTask?.["retentionTime"], + userIdentity: !p.jobReleaseTask?.userIdentity + ? undefined + : { + username: p.jobReleaseTask?.userIdentity?.["username"], + autoUser: !p.jobReleaseTask?.userIdentity?.autoUser + ? undefined + : { + scope: + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + }, + commonEnvironmentSettings: + p["commonEnvironmentSettings"] === undefined + ? p["commonEnvironmentSettings"] + : p["commonEnvironmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + poolInfo: { + poolId: p.poolInfo["poolId"], + autoPoolSpecification: !p.poolInfo.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !p.poolInfo.autoPoolSpecification?.pool + ? undefined + : { + displayName: + p.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + p.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + p.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["sku"], + version: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + exactVersion: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["exactVersion"], + }, + nodeAgentSkuId: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "dataDisks" + ].map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGb: p["diskSizeGB"], + storageAccountType: + p["storageAccountType"], + })), + licenseType: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: p.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] === undefined + ? p.poolInfo.autoPoolSpecification + ?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ + "containerRegistries" + ].map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: + p["registryServer"], + identityReference: + !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "extensions" + ].map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: + p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: + p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings ? undefined : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" + placement: + p.poolInfo.autoPoolSpecification + ?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" ], }, - })), - metadata: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["metadata"] === - undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] === undefined - ? body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : body.jobSpecification?.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + }, + }, + taskSlotsPerNode: + p.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !p.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + p.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + p.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNatPools: + p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ].map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: + p["networkSecurityGroupRules"] === + undefined + ? p["networkSecurityGroupRules"] + : p[ + "networkSecurityGroupRules" + ].map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + })), + })), + }, + publicIpAddressConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + ipAddressProvisioningType: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask + ? undefined + : { + commandLine: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !p.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !p.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry ? undefined : { - accountName: - p - .azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p - .azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p - .azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p - .azureBlobFileSystemConfiguration?.[ - "sasKey" + username: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "username" ], - blobfuseOptions: - p - .azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" + password: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "password" ], - relativeMountPath: - p - .azureBlobFileSystemConfiguration?.[ - "relativeMountPath" + registryServer: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "registryServer" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference + identityReference: !p.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference ? undefined : { resourceId: - p - .azureBlobFileSystemConfiguration + p.poolInfo + .autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry ?.identityReference?.[ "resourceId" ], }, }, - nfsMountConfiguration: - !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.[ - "source" - ], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + workingDirectory: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] + : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: + p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + environmentSettings: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] === + undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] + : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ? undefined + : { + username: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.[ + "username" + ], + autoUser: !p.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], + scope: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], }, - })), - targetNodeCommunicationMode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - metadata: - body.jobSpecification?.["metadata"] === undefined - ? body.jobSpecification?.["metadata"] - : body.jobSpecification?.["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + }, + maxTaskRetryCount: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], + }, + certificateReferences: + p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ].map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ].map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: + p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ].map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: + !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.[ + "uid" + ], + gid: p.linuxUserConfiguration?.[ + "gid" + ], + sshPrivateKey: + p.linuxUserConfiguration?.[ + "sshPrivateKey" + ], + }, + windowsUserConfiguration: + !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.[ + "loginMode" + ], + }, + })), + metadata: + p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: + p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ].map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p + .azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p + .azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p + .azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p + .azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p + .azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p + .azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p + .azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: + !p.nfsMountConfiguration + ? undefined + : { + source: + p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.nfsMountConfiguration?.[ + "mountOptions" + ], + }, + cifsMountConfiguration: + !p.cifsMountConfiguration + ? undefined + : { + username: + p.cifsMountConfiguration?.[ + "username" + ], + source: + p.cifsMountConfiguration?.[ + "source" + ], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.cifsMountConfiguration?.[ + "mountOptions" + ], + password: + p.cifsMountConfiguration?.[ + "password" + ], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, }, - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _updateJobScheduleDeserialize( - result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; + onAllTasksComplete: p["onAllTasksComplete"], + onTaskFailure: p["onTaskFailure"], + networkConfiguration: !p.networkConfiguration + ? undefined + : { subnetId: p.networkConfiguration?.["subnetId"] }, + metadata: + p["metadata"] === undefined + ? p["metadata"] + : p["metadata"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + executionInfo: !p.executionInfo + ? undefined + : { + startTime: new Date(p.executionInfo?.["startTime"]), + endTime: + p.executionInfo?.["endTime"] !== undefined + ? new Date(p.executionInfo?.["endTime"]) + : undefined, + poolId: p.executionInfo?.["poolId"], + schedulingError: !p.executionInfo?.schedulingError + ? undefined + : { + category: + p.executionInfo?.schedulingError?.["category"], + code: p.executionInfo?.schedulingError?.["code"], + message: p.executionInfo?.schedulingError?.["message"], + details: + p.executionInfo?.schedulingError?.["details"] === + undefined + ? p.executionInfo?.schedulingError?.["details"] + : p.executionInfo?.schedulingError?.["details"].map( + (p) => ({ name: p["name"], value: p["value"] }), + ), + }, + terminateReason: p.executionInfo?.["terminateReason"], + }, + stats: !p.stats + ? undefined + : { + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + userCPUTime: p.stats?.["userCPUTime"], + kernelCPUTime: p.stats?.["kernelCPUTime"], + wallClockTime: p.stats?.["wallClockTime"], + readIOps: p.stats?.["readIOps"], + writeIOps: p.stats?.["writeIOps"], + readIOGiB: p.stats?.["readIOGiB"], + writeIOGiB: p.stats?.["writeIOGiB"], + numSucceededTasks: p.stats?.["numSucceededTasks"], + numFailedTasks: p.stats?.["numFailedTasks"], + numTaskRetries: p.stats?.["numTaskRetries"], + waitTime: p.stats?.["waitTime"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; } -/** - * This replaces only the Job Schedule properties specified in the request. For - * example, if the schedule property is not specified with this request, then the - * Batch service will keep the existing schedule. Changes to a Job Schedule only - * impact Jobs created by the schedule after the update has taken place; currently - * running Jobs are unaffected. - */ -export async function updateJobSchedule( +/** Lists all of the Jobs in the specified Account. */ +export function listJobs( context: Client, - jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateJobScheduleSend( + options: ListJobsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - jobScheduleId, - body, - options, + () => _listJobsSend(context, options), + _listJobsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" }, ); - return _updateJobScheduleDeserialize(result); } - -export function _replaceJobScheduleSend( - context: Client, - jobScheduleId: string, - body: BatchJobSchedule, - options: ReplaceJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .put({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, + +export function _listJobsFromScheduleSend( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId) + .get({ + ...operationOptionsToRequestParameters(options), queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, }, - body: { - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification.jobManagerTask - ? undefined - : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobManagerTask?.["resourceFiles"] === - undefined - ? body.jobSpecification.jobManagerTask?.["resourceFiles"] - : body.jobSpecification.jobManagerTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + }); +} + +export async function _listJobsFromScheduleDeserialize( + result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse, +): Promise<_BatchJobListResult> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: + result.body["value"] === undefined + ? result.body["value"] + : result.body["value"].map((p) => ({ + id: p["id"], + displayName: p["displayName"], + usesTaskDependencies: p["usesTaskDependencies"], + url: p["url"], + eTag: p["eTag"], + lastModified: + p["lastModified"] !== undefined + ? new Date(p["lastModified"]) + : undefined, + creationTime: + p["creationTime"] !== undefined + ? new Date(p["creationTime"]) + : undefined, + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + priority: p["priority"], + allowTaskPreemption: p["allowTaskPreemption"], + maxParallelTasks: p["maxParallelTasks"], + constraints: !p.constraints + ? undefined + : { + maxWallClockTime: p.constraints?.["maxWallClockTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !p.jobManagerTask + ? undefined + : { + id: p.jobManagerTask?.["id"], + displayName: p.jobManagerTask?.["displayName"], + commandLine: p.jobManagerTask?.["commandLine"], + containerSettings: !p.jobManagerTask?.containerSettings + ? undefined + : { + containerRunOptions: + p.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobManagerTask?.containerSettings?.["imageName"], + registry: !p.jobManagerTask?.containerSettings?.registry ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: - body.jobSpecification.jobManagerTask?.["outputFiles"] === - undefined - ? body.jobSpecification.jobManagerTask?.["outputFiles"] - : body.jobSpecification.jobManagerTask?.["outputFiles"].map( - (p) => ({ + : { + username: + p.jobManagerTask?.containerSettings?.registry?.[ + "username" + ], + password: + p.jobManagerTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.jobManagerTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobManagerTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobManagerTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobManagerTask?.["resourceFiles"] === undefined + ? p.jobManagerTask?.["resourceFiles"] + : p.jobManagerTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + outputFiles: + p.jobManagerTask?.["outputFiles"] === undefined + ? p.jobManagerTask?.["outputFiles"] + : p.jobManagerTask?.["outputFiles"].map((p) => ({ filePattern: p["filePattern"], destination: { container: !p.destination.container @@ -12602,1070 +5395,1631 @@ export function _replaceJobScheduleSend( uploadOptions: { uploadCondition: p.uploadOptions["uploadCondition"], }, - }), - ), - environmentSettings: - body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] - : body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] - : body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + })), + environmentSettings: + p.jobManagerTask?.["environmentSettings"] === undefined + ? p.jobManagerTask?.["environmentSettings"] + : p.jobManagerTask?.["environmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + constraints: !p.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + p.jobManagerTask?.constraints?.["maxWallClockTime"], + retentionTime: + p.jobManagerTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + p.jobManagerTask?.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: p.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + p.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !p.jobManagerTask?.userIdentity + ? undefined + : { + username: p.jobManagerTask?.userIdentity?.["username"], + autoUser: !p.jobManagerTask?.userIdentity?.autoUser + ? undefined + : { + scope: + p.jobManagerTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + p.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + runExclusive: p.jobManagerTask?.["runExclusive"], + applicationPackageReferences: + p.jobManagerTask?.["applicationPackageReferences"] === + undefined + ? p.jobManagerTask?.["applicationPackageReferences"] + : p.jobManagerTask?.["applicationPackageReferences"].map( + (p) => ({ + applicationId: p["applicationId"], + version: p["version"], + }), + ), + authenticationTokenSettings: !p.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + p.jobManagerTask?.authenticationTokenSettings?.[ + "access" + ], + }, + allowLowPriorityNode: + p.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !p.jobPreparationTask + ? undefined + : { + id: p.jobPreparationTask?.["id"], + commandLine: p.jobPreparationTask?.["commandLine"], + containerSettings: !p.jobPreparationTask?.containerSettings + ? undefined + : { + containerRunOptions: + p.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobPreparationTask?.containerSettings?.[ + "imageName" + ], + registry: !p.jobPreparationTask?.containerSettings + ?.registry ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobReleaseTask?.["resourceFiles"] === - undefined - ? body.jobSpecification.jobReleaseTask?.["resourceFiles"] - : body.jobSpecification.jobReleaseTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + : { + username: + p.jobPreparationTask?.containerSettings + ?.registry?.["username"], + password: + p.jobPreparationTask?.containerSettings + ?.registry?.["password"], + registryServer: + p.jobPreparationTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !p.jobPreparationTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.jobPreparationTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobPreparationTask?.["resourceFiles"] === undefined + ? p.jobPreparationTask?.["resourceFiles"] + : p.jobPreparationTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + environmentSettings: + p.jobPreparationTask?.["environmentSettings"] === undefined + ? p.jobPreparationTask?.["environmentSettings"] + : p.jobPreparationTask?.["environmentSettings"].map( + (p) => ({ name: p["name"], value: p["value"] }), + ), + constraints: !p.jobPreparationTask?.constraints + ? undefined + : { + maxWallClockTime: + p.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + p.jobPreparationTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + p.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], + userIdentity: !p.jobPreparationTask?.userIdentity + ? undefined + : { + username: + p.jobPreparationTask?.userIdentity?.["username"], + autoUser: !p.jobPreparationTask?.userIdentity?.autoUser ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - }, - commonEnvironmentSettings: - body.jobSpecification["commonEnvironmentSettings"] === undefined - ? body.jobSpecification["commonEnvironmentSettings"] - : body.jobSpecification["commonEnvironmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification + : { + scope: + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + rerunOnNodeRebootAfterSuccess: + p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], + }, + jobReleaseTask: !p.jobReleaseTask ? undefined : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + id: p.jobReleaseTask?.["id"], + commandLine: p.jobReleaseTask?.["commandLine"], + containerSettings: !p.jobReleaseTask?.containerSettings ? undefined : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + containerRunOptions: + p.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.jobReleaseTask?.containerSettings?.["imageName"], + registry: !p.jobReleaseTask?.containerSettings?.registry ? undefined : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + username: + p.jobReleaseTask?.containerSettings?.registry?.[ + "username" + ], + password: + p.jobReleaseTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.jobReleaseTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobReleaseTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobReleaseTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + workingDirectory: + p.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.jobReleaseTask?.["resourceFiles"] === undefined + ? p.jobReleaseTask?.["resourceFiles"] + : p.jobReleaseTask?.["resourceFiles"].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + environmentSettings: + p.jobReleaseTask?.["environmentSettings"] === undefined + ? p.jobReleaseTask?.["environmentSettings"] + : p.jobReleaseTask?.["environmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], + retentionTime: p.jobReleaseTask?.["retentionTime"], + userIdentity: !p.jobReleaseTask?.userIdentity + ? undefined + : { + username: p.jobReleaseTask?.userIdentity?.["username"], + autoUser: !p.jobReleaseTask?.userIdentity?.autoUser ? undefined : { - imageReference: { - publisher: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" + scope: + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "scope" ], - version: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + elevationLevel: + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + }, + commonEnvironmentSettings: + p["commonEnvironmentSettings"] === undefined + ? p["commonEnvironmentSettings"] + : p["commonEnvironmentSettings"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + poolInfo: { + poolId: p.poolInfo["poolId"], + autoPoolSpecification: !p.poolInfo.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !p.poolInfo.autoPoolSpecification?.pool + ? undefined + : { + displayName: + p.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + p.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + p.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], + ?.imageReference["sku"], + version: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + exactVersion: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["exactVersion"], + }, + nodeAgentSkuId: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "dataDisks" + ].map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGb: p["diskSizeGB"], + storageAccountType: + p["storageAccountType"], + })), + licenseType: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: p.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] === undefined + ? p.poolInfo.autoPoolSpecification + ?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ + "containerRegistries" + ].map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: + p["registryServer"], + identityReference: + !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: + p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] + : p.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "extensions" + ].map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: + p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: + p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !p.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + p.poolInfo.autoPoolSpecification + ?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + p.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !p.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + p.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo + resizeTimeout: + p.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !p.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: - body.jobSpecification.poolInfo + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNatPools: + p.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ].map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: + p["networkSecurityGroupRules"] === + undefined + ? p["networkSecurityGroupRules"] + : p[ + "networkSecurityGroupRules" + ].map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + })), + })), + }, + publicIpAddressConfiguration: !p.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + ipAddressProvisioningType: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + p.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask + ? undefined + : { + commandLine: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !p.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !p.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "username" + ], + password: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + p.poolInfo + .autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] === undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] + : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: + p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + environmentSettings: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] === + undefined + ? p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] + : p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" ].map((p) => ({ name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), + value: p["value"], })), - }, - publicIPAddressConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" - ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.poolInfo + userIdentity: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ? undefined + : { + username: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.[ + "username" + ], + autoUser: !p.poolInfo .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry + ?.userIdentity?.autoUser + ? undefined + : { + scope: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], + }, + certificateReferences: + p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ].map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ].map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: + p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ].map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: + !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.[ + "uid" + ], + gid: p.linuxUserConfiguration?.[ + "gid" + ], + sshPrivateKey: + p.linuxUserConfiguration?.[ + "sshPrivateKey" + ], + }, + windowsUserConfiguration: + !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.[ + "loginMode" + ], + }, + })), + metadata: + p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: + p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] === undefined + ? p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] + : p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ].map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p + .azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p + .azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p + .azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p + .azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p + .azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p + .azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p + .azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: + !p.nfsMountConfiguration + ? undefined + : { + source: + p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.nfsMountConfiguration?.[ + "mountOptions" + ], + }, + cifsMountConfiguration: + !p.cifsMountConfiguration ? undefined : { username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], + p.cifsMountConfiguration?.[ + "username" + ], + source: + p.cifsMountConfiguration?.[ + "source" + ], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.cifsMountConfiguration?.[ + "mountOptions" + ], password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, + p.cifsMountConfiguration?.[ + "password" + ], }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + azureFileShareConfiguration: + !p.azureFileShareConfiguration ? undefined : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], }, - }, - maxTaskRetryCount: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] === + })), + targetNodeCommunicationMode: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: p["onAllTasksComplete"], + onTaskFailure: p["onTaskFailure"], + networkConfiguration: !p.networkConfiguration + ? undefined + : { subnetId: p.networkConfiguration?.["subnetId"] }, + metadata: + p["metadata"] === undefined + ? p["metadata"] + : p["metadata"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + executionInfo: !p.executionInfo + ? undefined + : { + startTime: new Date(p.executionInfo?.["startTime"]), + endTime: + p.executionInfo?.["endTime"] !== undefined + ? new Date(p.executionInfo?.["endTime"]) + : undefined, + poolId: p.executionInfo?.["poolId"], + schedulingError: !p.executionInfo?.schedulingError + ? undefined + : { + category: + p.executionInfo?.schedulingError?.["category"], + code: p.executionInfo?.schedulingError?.["code"], + message: p.executionInfo?.schedulingError?.["message"], + details: + p.executionInfo?.schedulingError?.["details"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" + ? p.executionInfo?.schedulingError?.["details"] + : p.executionInfo?.schedulingError?.["details"].map( + (p) => ({ name: p["name"], value: p["value"] }), + ), + }, + terminateReason: p.executionInfo?.["terminateReason"], + }, + stats: !p.stats + ? undefined + : { + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + userCPUTime: p.stats?.["userCPUTime"], + kernelCPUTime: p.stats?.["kernelCPUTime"], + wallClockTime: p.stats?.["wallClockTime"], + readIOps: p.stats?.["readIOps"], + writeIOps: p.stats?.["writeIOps"], + readIOGiB: p.stats?.["readIOGiB"], + writeIOGiB: p.stats?.["writeIOGiB"], + numSucceededTasks: p.stats?.["numSucceededTasks"], + numFailedTasks: p.stats?.["numFailedTasks"], + numTaskRetries: p.stats?.["numTaskRetries"], + waitTime: p.stats?.["waitTime"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists the Jobs that have been created under the specified Job Schedule. */ +export function listJobsFromSchedule( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listJobsFromScheduleSend(context, jobScheduleId, options), + _listJobsFromScheduleDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _listJobPreparationAndReleaseTaskStatusSend( + context: Client, + jobId: string, + options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { + requestOptions: {}, + }, +): StreamableMethod< + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse +> { + return context + .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listJobPreparationAndReleaseTaskStatusDeserialize( + result: + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse, +): Promise<_BatchJobListPreparationAndReleaseTaskStatusResult> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: + result.body["value"] === undefined + ? result.body["value"] + : result.body["value"].map((p) => ({ + poolId: p["poolId"], + nodeId: p["nodeId"], + nodeUrl: p["nodeUrl"], + jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo + ? undefined + : { + startTime: new Date( + p.jobPreparationTaskExecutionInfo?.["startTime"], + ), + endTime: + p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobPreparationTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobPreparationTaskExecutionInfo + ?.containerInfo + ? undefined + : { + containerId: + p.jobPreparationTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobPreparationTaskExecutionInfo?.containerInfo?.[ + "state" + ], + error: + p.jobPreparationTaskExecutionInfo?.containerInfo?.[ + "error" + ], + }, + failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "category" + ], + code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "code" + ], + message: + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "message" + ], + details: + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "details" + ] === undefined + ? p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "details" ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" + : p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "details" ].map((p) => ({ name: p["name"], value: p["value"], })), - mountConfiguration: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" + }, + retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], + lastRetryTime: + p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== + undefined + ? new Date( + p.jobPreparationTaskExecutionInfo?.["lastRetryTime"], + ) + : undefined, + result: p.jobPreparationTaskExecutionInfo?.["result"], + }, + jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo + ? undefined + : { + startTime: new Date( + p.jobReleaseTaskExecutionInfo?.["startTime"], + ), + endTime: + p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobReleaseTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo + ? undefined + : { + containerId: + p.jobReleaseTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobReleaseTaskExecutionInfo?.containerInfo?.[ + "state" + ], + error: + p.jobReleaseTaskExecutionInfo?.containerInfo?.[ + "error" + ], + }, + failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "category" + ], + code: p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "code" + ], + message: + p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "message" + ], + details: + p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "details" + ] === undefined + ? p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "details" ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" + : p.jobReleaseTaskExecutionInfo?.failureInfo?.[ + "details" ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, + name: p["name"], + value: p["value"], })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], }, + result: p.jobReleaseTaskExecutionInfo?.["result"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** + * This API returns the Job Preparation and Job Release Task status on all Compute + * Nodes that have run the Job Preparation or Job Release Task. This includes + * Compute Nodes which have since been removed from the Pool. If this API is + * invoked on a Job which has no Job Preparation or Job Release Task, the Batch + * service returns HTTP status code 409 (Conflict) with an error code of + * JobPreparationTaskNotSpecified. + */ +export function listJobPreparationAndReleaseTaskStatus( + context: Client, + jobId: string, + options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), + _listJobPreparationAndReleaseTaskStatusDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _getJobTaskCountsSend( + context: Client, + jobId: string, + options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, +): StreamableMethod< + GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse +> { + return context + .path("/jobs/{jobId}/taskcounts", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _getJobTaskCountsDeserialize( + result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + taskCounts: { + active: result.body.taskCounts["active"], + running: result.body.taskCounts["running"], + completed: result.body.taskCounts["completed"], + succeeded: result.body.taskCounts["succeeded"], + failed: result.body.taskCounts["failed"], + }, + taskSlotCounts: { + active: result.body.taskSlotCounts["active"], + running: result.body.taskSlotCounts["running"], + completed: result.body.taskSlotCounts["completed"], + succeeded: result.body.taskSlotCounts["succeeded"], + failed: result.body.taskSlotCounts["failed"], + }, + }; +} + +/** + * Task counts provide a count of the Tasks by active, running or completed Task + * state, and a count of Tasks which succeeded or failed. Tasks in the preparing + * state are counted as running. Note that the numbers returned may not always be + * up to date. If you need exact task counts, use a list query. + */ +export async function getJobTaskCounts( + context: Client, + jobId: string, + options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getJobTaskCountsSend(context, jobId, options); + return _getJobTaskCountsDeserialize(result); +} + +export function _createCertificateSend( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptionalParams = { requestOptions: {} }, +): StreamableMethod< + CreateCertificate201Response | CreateCertificateDefaultResponse +> { + return context + .path("/certificates") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + thumbprint: body["thumbprint"], + thumbprintAlgorithm: body["thumbprintAlgorithm"], + data: uint8ArrayToString(body["data"], "base64"), + certificateFormat: body["certificateFormat"], + password: body["password"], + }, + }); +} + +export async function _createCertificateDeserialize( + result: CreateCertificate201Response | CreateCertificateDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** Creates a Certificate to the specified Account. */ +export async function createCertificate( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createCertificateSend(context, body, options); + return _createCertificateDeserialize(result); +} + +export function _listCertificatesSend( + context: Client, + options: ListCertificatesOptionalParams = { requestOptions: {} }, +): StreamableMethod< + ListCertificates200Response | ListCertificatesDefaultResponse +> { + return context + .path("/certificates") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listCertificatesDeserialize( + result: ListCertificates200Response | ListCertificatesDefaultResponse, +): Promise<_CertificateListResult> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: + result.body["value"] === undefined + ? result.body["value"] + : result.body["value"].map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + url: p["url"], + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + publicData: + typeof p["publicData"] === "string" + ? stringToUint8Array(p["publicData"], "base64") + : p["publicData"], + deleteCertificateError: !p.deleteCertificateError + ? undefined + : { + code: p.deleteCertificateError?.["code"], + message: p.deleteCertificateError?.["message"], + values: + p.deleteCertificateError?.["values"] === undefined + ? p.deleteCertificateError?.["values"] + : p.deleteCertificateError?.["values"].map((p) => ({ + name: p["name"], + value: p["value"], + })), }, - }, - metadata: - body.jobSpecification["metadata"] === undefined - ? body.jobSpecification["metadata"] - : body.jobSpecification["metadata"].map((p) => ({ + data: + typeof p["data"] === "string" + ? stringToUint8Array(p["data"], "base64") + : p["data"], + certificateFormat: p["certificateFormat"], + password: p["password"], + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists all of the Certificates that have been added to the specified Account. */ +export function listCertificates( + context: Client, + options: ListCertificatesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listCertificatesSend(context, options), + _listCertificatesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _cancelCertificateDeletionSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", + thumbprintAlgorithm, + thumbprint, + ) + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _cancelCertificateDeletionDeserialize( + result: + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * If you try to delete a Certificate that is being used by a Pool or Compute + * Node, the status of the Certificate changes to deleteFailed. If you decide that + * you want to continue using the Certificate, you can use this operation to set + * the status of the Certificate back to active. If you intend to delete the + * Certificate, you do not need to run this operation after the deletion failed. + * You must make sure that the Certificate is not being used by any resources, and + * then you can try again to delete the Certificate. + */ +export async function cancelCertificateDeletion( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _cancelCertificateDeletionSend( + context, + thumbprintAlgorithm, + thumbprint, + options, + ); + return _cancelCertificateDeletionDeserialize(result); +} + +export function _deleteCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptionalParams = { requestOptions: {} }, +): StreamableMethod< + DeleteCertificate202Response | DeleteCertificateDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint, + ) + .delete({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _deleteCertificateDeserialize( + result: DeleteCertificate202Response | DeleteCertificateDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * You cannot delete a Certificate if a resource (Pool or Compute Node) is using + * it. Before you can delete a Certificate, you must therefore make sure that the + * Certificate is not associated with any existing Pools, the Certificate is not + * installed on any Nodes (even if you remove a Certificate from a Pool, it is not + * removed from existing Compute Nodes in that Pool until they restart), and no + * running Tasks depend on the Certificate. If you try to delete a Certificate + * that is in use, the deletion fails. The Certificate status changes to + * deleteFailed. You can use Cancel Delete Certificate to set the status back to + * active if you decide that you want to continue using the Certificate. + */ +export async function deleteCertificate( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options, + ); + return _deleteCertificateDeserialize(result); +} + +export function _getCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint, + ) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + $select: options?.$select, + }, + }); +} + +export async function _getCertificateDeserialize( + result: GetCertificate200Response | GetCertificateDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + thumbprint: result.body["thumbprint"], + thumbprintAlgorithm: result.body["thumbprintAlgorithm"], + url: result.body["url"], + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + publicData: + typeof result.body["publicData"] === "string" + ? stringToUint8Array(result.body["publicData"], "base64") + : result.body["publicData"], + deleteCertificateError: !result.body.deleteCertificateError + ? undefined + : { + code: result.body.deleteCertificateError?.["code"], + message: result.body.deleteCertificateError?.["message"], + values: + result.body.deleteCertificateError?.["values"] === undefined + ? result.body.deleteCertificateError?.["values"] + : result.body.deleteCertificateError?.["values"].map((p) => ({ name: p["name"], value: p["value"], })), }, - metadata: - body["metadata"] === undefined - ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _replaceJobScheduleDeserialize( - result: ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - return; + data: + typeof result.body["data"] === "string" + ? stringToUint8Array(result.body["data"], "base64") + : result.body["data"], + certificateFormat: result.body["certificateFormat"], + password: result.body["password"], + }; } -/** - * This fully replaces all the updatable properties of the Job Schedule. For - * example, if the schedule property is not specified with this request, then the - * Batch service will remove the existing schedule. Changes to a Job Schedule only - * impact Jobs created by the schedule after the update has taken place; currently - * running Jobs are unaffected. - */ -export async function replaceJobSchedule( +/** Gets information about the specified Certificate. */ +export async function getCertificate( context: Client, - jobScheduleId: string, - body: BatchJobSchedule, - options: ReplaceJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _replaceJobScheduleSend( + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getCertificateSend( context, - jobScheduleId, - body, + thumbprintAlgorithm, + thumbprint, options, ); - return _replaceJobScheduleDeserialize(result); + return _getCertificateDeserialize(result); } -export function _disableJobScheduleSend( +export function _jobScheduleExistsSend( context: Client, jobScheduleId: string, - options: DisableJobScheduleOptionalParams = { requestOptions: {} }, + options: JobScheduleExistsOptionalParams = { requestOptions: {} }, ): StreamableMethod< - DisableJobSchedule204Response | DisableJobScheduleDefaultResponse + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse > { return context - .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .head({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifMatch !== undefined @@ -13688,8 +7042,11 @@ export function _disableJobScheduleSend( }); } -export async function _disableJobScheduleDeserialize( - result: DisableJobSchedule204Response | DisableJobScheduleDefaultResponse, +export async function _jobScheduleExistsDeserialize( + result: + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -13698,26 +7055,26 @@ export async function _disableJobScheduleDeserialize( return; } -/** No new Jobs will be created until the Job Schedule is enabled again. */ -export async function disableJobSchedule( +/** Checks the specified Job Schedule exists. */ +export async function jobScheduleExists( context: Client, jobScheduleId: string, - options: DisableJobScheduleOptionalParams = { requestOptions: {} }, + options: JobScheduleExistsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _disableJobScheduleSend(context, jobScheduleId, options); - return _disableJobScheduleDeserialize(result); + const result = await _jobScheduleExistsSend(context, jobScheduleId, options); + return _jobScheduleExistsDeserialize(result); } -export function _enableJobScheduleSend( +export function _deleteJobScheduleSend( context: Client, jobScheduleId: string, - options: EnableJobScheduleOptionalParams = { requestOptions: {} }, + options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod< - EnableJobSchedule204Response | EnableJobScheduleDefaultResponse + DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse > { return context - .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .delete({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifMatch !== undefined @@ -13740,8 +7097,8 @@ export function _enableJobScheduleSend( }); } -export async function _enableJobScheduleDeserialize( - result: EnableJobSchedule204Response | EnableJobScheduleDefaultResponse, +export async function _deleteJobScheduleDeserialize( + result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -13750,26 +7107,30 @@ export async function _enableJobScheduleDeserialize( return; } -/** Enables a Job Schedule. */ -export async function enableJobSchedule( +/** + * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that + * schedule. When Tasks are deleted, all the files in their working directories on + * the Compute Nodes are also deleted (the retention period is ignored). The Job + * Schedule statistics are no longer accessible once the Job Schedule is deleted, + * though they are still counted towards Account lifetime statistics. + */ +export async function deleteJobSchedule( context: Client, jobScheduleId: string, - options: EnableJobScheduleOptionalParams = { requestOptions: {} }, + options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _enableJobScheduleSend(context, jobScheduleId, options); - return _enableJobScheduleDeserialize(result); + const result = await _deleteJobScheduleSend(context, jobScheduleId, options); + return _deleteJobScheduleDeserialize(result); } -export function _terminateJobScheduleSend( +export function _getJobScheduleSend( context: Client, jobScheduleId: string, - options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse -> { + options: GetJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .get({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.ifMatch !== undefined @@ -13788,1206 +7149,1565 @@ export function _terminateJobScheduleSend( queryParameters: { "api-version": options?.apiVersion ?? "2023-05-01.17.0", timeOut: options?.timeOutInSeconds, + $select: options?.$select, + $expand: options?.$expand, }, }); } -export async function _terminateJobScheduleDeserialize( - result: TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse, -): Promise { +export async function _getJobScheduleDeserialize( + result: GetJobSchedule200Response | GetJobScheduleDefaultResponse, +): Promise { if (isUnexpected(result)) { throw createRestError(result); } - return; -} - -/** Terminates a Job Schedule. */ -export async function terminateJobSchedule( - context: Client, - jobScheduleId: string, - options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _terminateJobScheduleSend( - context, - jobScheduleId, - options, - ); - return _terminateJobScheduleDeserialize(result); -} - -export function _createJobScheduleSend( - context: Client, - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod< - CreateJobSchedule201Response | CreateJobScheduleDefaultResponse -> { - return context - .path("/jobschedules") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: { - id: body["id"], - displayName: body["displayName"], - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification.jobManagerTask - ? undefined - : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry + return { + id: result.body["id"], + displayName: result.body["displayName"], + url: result.body["url"], + eTag: result.body["eTag"], + lastModified: + result.body["lastModified"] !== undefined + ? new Date(result.body["lastModified"]) + : undefined, + creationTime: + result.body["creationTime"] !== undefined + ? new Date(result.body["creationTime"]) + : undefined, + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + schedule: { + doNotRunUntil: + result.body.schedule["doNotRunUntil"] !== undefined + ? new Date(result.body.schedule["doNotRunUntil"]) + : undefined, + doNotRunAfter: + result.body.schedule["doNotRunAfter"] !== undefined + ? new Date(result.body.schedule["doNotRunAfter"]) + : undefined, + startWindow: result.body.schedule["startWindow"], + recurrenceInterval: result.body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: result.body.jobSpecification["priority"], + allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], + displayName: result.body.jobSpecification["displayName"], + usesTaskDependencies: + result.body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], + onTaskFailure: result.body.jobSpecification["onTaskFailure"], + networkConfiguration: !result.body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + result.body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !result.body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + result.body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !result.body.jobSpecification.jobManagerTask + ? undefined + : { + id: result.body.jobSpecification.jobManagerTask?.["id"], + displayName: + result.body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + result.body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobManagerTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: + result.body.jobSpecification.jobManagerTask?.["resourceFiles"] === + undefined + ? result.body.jobSpecification.jobManagerTask?.["resourceFiles"] + : result.body.jobSpecification.jobManagerTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: + result.body.jobSpecification.jobManagerTask?.["outputFiles"] === + undefined + ? result.body.jobSpecification.jobManagerTask?.["outputFiles"] + : result.body.jobSpecification.jobManagerTask?.[ + "outputFiles" + ].map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container + ?.identityReference?.["resourceId"], + }, + uploadHeaders: + p.destination.container?.["uploadHeaders"] === + undefined + ? p.destination.container?.["uploadHeaders"] + : p.destination.container?.[ + "uploadHeaders" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: + result.body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] === undefined + ? result.body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] + : result.body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ].map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobManagerTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + result.body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + result.body.jobSpecification.jobManagerTask?.[ + "killJobOnCompletion" + ], + userIdentity: !result.body.jobSpecification.jobManagerTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + runExclusive: + result.body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: + result.body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] === undefined + ? result.body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] + : result.body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ].map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !result.body.jobSpecification + .jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + result.body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + result.body.jobSpecification.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !result.body.jobSpecification.jobPreparationTask + ? undefined + : { + id: result.body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + result.body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: + result.body.jobSpecification.jobPreparationTask?.[ + "resourceFiles" + ] === undefined + ? result.body.jobSpecification.jobPreparationTask?.[ + "resourceFiles" + ] + : result.body.jobSpecification.jobPreparationTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: + result.body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] === undefined + ? result.body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] + : result.body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ].map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxTaskRetryCount"], + }, + waitForSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "waitForSuccess" + ], + userIdentity: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !result.body.jobSpecification.jobReleaseTask + ? undefined + : { + id: result.body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + result.body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: + result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] === + undefined + ? result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] + : result.body.jobSpecification.jobReleaseTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: + result.body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] === undefined + ? result.body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] + : result.body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ].map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: + result.body.jobSpecification["commonEnvironmentSettings"] === undefined + ? result.body.jobSpecification["commonEnvironmentSettings"] + : result.body.jobSpecification["commonEnvironmentSettings"].map( + (p) => ({ name: p["name"], value: p["value"] }), + ), + poolInfo: { + poolId: result.body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !result.body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["displayName"], + vmSize: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + exactVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "exactVersion" ], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, }, - workingDirectory: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobManagerTask?.["resourceFiles"] === - undefined - ? body.jobSpecification.jobManagerTask?.["resourceFiles"] - : body.jobSpecification.jobManagerTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: - body.jobSpecification.jobManagerTask?.["outputFiles"] === - undefined - ? body.jobSpecification.jobManagerTask?.["outputFiles"] - : body.jobSpecification.jobManagerTask?.["outputFiles"].map( - (p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference + nodeAgentSkuId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] === + undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "dataDisks" + ].map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGb: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ + "containerRegistries" + ].map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] === + undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ + "extensions" + ].map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !result.body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["resizeTimeout"], + targetDedicatedNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["enableAutoScale"], + autoScaleFormula: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNatPools: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ].map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: + p["networkSecurityGroupRules"] === + undefined + ? p["networkSecurityGroupRules"] + : p["networkSecurityGroupRules"].map( + (p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + }), + ), + })), + }, + publicIpAddressConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + ipAddressProvisioningType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.jobSpecification + .poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ].map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined : { resourceId: - p.destination.container - ?.identityReference?.["resourceId"], + p.identityReference?.["resourceId"], }, - uploadHeaders: - p.destination.container?.[ - "uploadHeaders" - ] === undefined - ? p.destination.container?.[ - "uploadHeaders" - ] - : p.destination.container?.[ - "uploadHeaders" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }), - ), - environmentSettings: - body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] === undefined - ? body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] - : body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] - : body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference + })), + environmentSettings: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], + }, + certificateReferences: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ].map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ].map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["applicationLicenses"], + userAccounts: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["userAccounts"] === + undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["userAccounts"] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ].map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], }, - }, - workingDirectory: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: - body.jobSpecification.jobReleaseTask?.["resourceFiles"] === - undefined - ? body.jobSpecification.jobReleaseTask?.["resourceFiles"] - : body.jobSpecification.jobReleaseTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: - body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] - : body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ].map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - }, - commonEnvironmentSettings: - body.jobSpecification["commonEnvironmentSettings"] === undefined - ? body.jobSpecification["commonEnvironmentSettings"] - : body.jobSpecification["commonEnvironmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool - ? undefined - : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSkuId" - ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration + windowsUserConfiguration: + !p.windowsUserConfiguration ? undefined : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], + loginMode: + p.windowsUserConfiguration?.["loginMode"], }, - dataDisks: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "dataDisks" - ].map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGb"], - storageAccountType: - p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration + })), + metadata: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["metadata"] === undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["metadata"] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ].map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["mountConfiguration"] === + undefined + ? result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["mountConfiguration"] + : result.body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ].map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" ], - containerRegistries: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ].map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" ], - }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" ], - }, - extensions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.virtualMachineConfiguration?.[ - "extensions" - ].map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: - p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: - body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.networkConfiguration?.endpointConfiguration?.[ - "inboundNatPools" - ].map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: - p["networkSecurityGroupRules"] === - undefined - ? p["networkSecurityGroupRules"] - : p[ - "networkSecurityGroupRules" - ].map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIpAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressProvisioningType" + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIpAddressConfiguration?.[ - "ipAddressIds" + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" ], - }, - enableAcceleratedNetworking: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" ], - imageName: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], }, - resourceFiles: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ].map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - environmentSettings: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration ? undefined : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], }, - maxTaskRetryCount: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ].map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] === - undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ].map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: - !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" - ], - }, - })), - metadata: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ].map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] === undefined - ? body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] - : body.jobSpecification.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ].map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p - .azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: - p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.[ - "mountOptions" - ], - }, - cifsMountConfiguration: - !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.[ - "username" - ], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.[ - "password" - ], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], - }, - }, - }, - metadata: - body.jobSpecification["metadata"] === undefined - ? body.jobSpecification["metadata"] - : body.jobSpecification["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + })), + targetNodeCommunicationMode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + metadata: + result.body.jobSpecification["metadata"] === undefined + ? result.body.jobSpecification["metadata"] + : result.body.jobSpecification["metadata"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + executionInfo: !result.body.executionInfo + ? undefined + : { + nextRunTime: + result.body.executionInfo?.["nextRunTime"] !== undefined + ? new Date(result.body.executionInfo?.["nextRunTime"]) + : undefined, + recentJob: !result.body.executionInfo?.recentJob + ? undefined + : { + id: result.body.executionInfo?.recentJob?.["id"], + url: result.body.executionInfo?.recentJob?.["url"], + }, + endTime: + result.body.executionInfo?.["endTime"] !== undefined + ? new Date(result.body.executionInfo?.["endTime"]) + : undefined, + }, + metadata: + result.body["metadata"] === undefined + ? result.body["metadata"] + : result.body["metadata"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + stats: !result.body.stats + ? undefined + : { + url: result.body.stats?.["url"], + startTime: new Date(result.body.stats?.["startTime"]), + lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), + userCPUTime: result.body.stats?.["userCPUTime"], + kernelCPUTime: result.body.stats?.["kernelCPUTime"], + wallClockTime: result.body.stats?.["wallClockTime"], + readIOps: result.body.stats?.["readIOps"], + writeIOps: result.body.stats?.["writeIOps"], + readIOGiB: result.body.stats?.["readIOGiB"], + writeIOGiB: result.body.stats?.["writeIOGiB"], + numSucceededTasks: result.body.stats?.["numSucceededTasks"], + numFailedTasks: result.body.stats?.["numFailedTasks"], + numTaskRetries: result.body.stats?.["numTaskRetries"], + waitTime: result.body.stats?.["waitTime"], }, + }; +} + +/** Gets information about the specified Job Schedule. */ +export async function getJobSchedule( + context: Client, + jobScheduleId: string, + options: GetJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getJobScheduleSend(context, jobScheduleId, options); + return _getJobScheduleDeserialize(result); +} + +export function _updateJobScheduleSend( + context: Client, + jobScheduleId: string, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + schedule: !body.schedule + ? body.schedule + : scheduleSerializer(body.schedule), + jobSpecification: !body.jobSpecification + ? body.jobSpecification + : jobSpecificationSerializer(body.jobSpecification), + metadata: + body["metadata"] === undefined + ? body["metadata"] + : body["metadata"].map(metadataItemSerializer), + }, + }); +} + +export async function _updateJobScheduleDeserialize( + result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * This replaces only the Job Schedule properties specified in the request. For + * example, if the schedule property is not specified with this request, then the + * Batch service will keep the existing schedule. Changes to a Job Schedule only + * impact Jobs created by the schedule after the update has taken place; currently + * running Jobs are unaffected. + */ +export async function updateJobSchedule( + context: Client, + jobScheduleId: string, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateJobScheduleSend( + context, + jobScheduleId, + body, + options, + ); + return _updateJobScheduleDeserialize(result); +} + +export function _replaceJobScheduleSend( + context: Client, + jobScheduleId: string, + body: BatchJobSchedule, + options: ReplaceJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .put({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + schedule: scheduleSerializer(body.schedule), + jobSpecification: jobSpecificationSerializer(body.jobSpecification), + metadata: + body["metadata"] === undefined + ? body["metadata"] + : body["metadata"].map(metadataItemSerializer), + }, + }); +} + +export async function _replaceJobScheduleDeserialize( + result: ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** + * This fully replaces all the updatable properties of the Job Schedule. For + * example, if the schedule property is not specified with this request, then the + * Batch service will remove the existing schedule. Changes to a Job Schedule only + * impact Jobs created by the schedule after the update has taken place; currently + * running Jobs are unaffected. + */ +export async function replaceJobSchedule( + context: Client, + jobScheduleId: string, + body: BatchJobSchedule, + options: ReplaceJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _replaceJobScheduleSend( + context, + jobScheduleId, + body, + options, + ); + return _replaceJobScheduleDeserialize(result); +} + +export function _disableJobScheduleSend( + context: Client, + jobScheduleId: string, + options: DisableJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + DisableJobSchedule204Response | DisableJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _disableJobScheduleDeserialize( + result: DisableJobSchedule204Response | DisableJobScheduleDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** No new Jobs will be created until the Job Schedule is enabled again. */ +export async function disableJobSchedule( + context: Client, + jobScheduleId: string, + options: DisableJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _disableJobScheduleSend(context, jobScheduleId, options); + return _disableJobScheduleDeserialize(result); +} + +export function _enableJobScheduleSend( + context: Client, + jobScheduleId: string, + options: EnableJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + EnableJobSchedule204Response | EnableJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _enableJobScheduleDeserialize( + result: EnableJobSchedule204Response | EnableJobScheduleDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** Enables a Job Schedule. */ +export async function enableJobSchedule( + context: Client, + jobScheduleId: string, + options: EnableJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _enableJobScheduleSend(context, jobScheduleId, options); + return _enableJobScheduleDeserialize(result); +} + +export function _terminateJobScheduleSend( + context: Client, + jobScheduleId: string, + options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _terminateJobScheduleDeserialize( + result: TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** Terminates a Job Schedule. */ +export async function terminateJobSchedule( + context: Client, + jobScheduleId: string, + options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _terminateJobScheduleSend( + context, + jobScheduleId, + options, + ); + return _terminateJobScheduleDeserialize(result); +} + +export function _createJobScheduleSend( + context: Client, + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod< + CreateJobSchedule201Response | CreateJobScheduleDefaultResponse +> { + return context + .path("/jobschedules") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { + "api-version": options?.apiVersion ?? "2023-05-01.17.0", + timeOut: options?.timeOutInSeconds, + }, + body: { + id: body["id"], + displayName: body["displayName"], + schedule: scheduleSerializer(body.schedule), + jobSpecification: jobSpecificationSerializer(body.jobSpecification), metadata: body["metadata"] === undefined ? body["metadata"] - : body["metadata"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + : body["metadata"].map(metadataItemSerializer), }, }); } @@ -15035,7 +8755,7 @@ export function _listJobSchedulesSend( export async function _listJobSchedulesDeserialize( result: ListJobSchedules200Response | ListJobSchedulesDefaultResponse, -): Promise { +): Promise<_BatchJobScheduleListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -16368,206 +10088,51 @@ export function _createTaskSend( id: body["id"], displayName: body["displayName"], exitConditions: !body.exitConditions - ? undefined - : { - exitCodes: - body.exitConditions?.["exitCodes"] === undefined - ? body.exitConditions?.["exitCodes"] - : body.exitConditions?.["exitCodes"].map((p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - exitCodeRanges: - body.exitConditions?.["exitCodeRanges"] === undefined - ? body.exitConditions?.["exitCodeRanges"] - : body.exitConditions?.["exitCodeRanges"].map((p) => ({ - start: p["start"], - end: p["end"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - preProcessingError: !body.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - body.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - body.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !body.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - body.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - body.exitConditions?.fileUploadError?.[ - "dependencyAction" - ], - }, - default: !body.exitConditions?.default - ? undefined - : { - jobAction: body.exitConditions?.default?.["jobAction"], - dependencyAction: - body.exitConditions?.default?.["dependencyAction"], - }, - }, + ? body.exitConditions + : exitConditionsSerializer(body.exitConditions), commandLine: body["commandLine"], containerSettings: !body.containerSettings - ? undefined - : { - containerRunOptions: - body.containerSettings?.["containerRunOptions"], - imageName: body.containerSettings?.["imageName"], - registry: !body.containerSettings?.registry - ? undefined - : { - username: body.containerSettings?.registry?.["username"], - password: body.containerSettings?.registry?.["password"], - registryServer: - body.containerSettings?.registry?.["registryServer"], - identityReference: !body.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: body.containerSettings?.["workingDirectory"], - }, + ? body.containerSettings + : taskContainerSettingsSerializer(body.containerSettings), resourceFiles: body["resourceFiles"] === undefined ? body["resourceFiles"] - : body["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), + : body["resourceFiles"].map(resourceFileSerializer), outputFiles: body["outputFiles"] === undefined ? body["outputFiles"] - : body["outputFiles"].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.["uploadHeaders"].map( - (p) => ({ name: p["name"], value: p["value"] }), - ), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), + : body["outputFiles"].map(outputFileSerializer), environmentSettings: body["environmentSettings"] === undefined ? body["environmentSettings"] - : body["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), + : body["environmentSettings"].map(environmentSettingSerializer), affinityInfo: !body.affinityInfo - ? undefined - : { affinityId: body.affinityInfo?.["affinityId"] }, + ? body.affinityInfo + : affinityInformationSerializer(body.affinityInfo), constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, + ? body.constraints + : taskConstraintsSerializer(body.constraints), requiredSlots: body["requiredSlots"], userIdentity: !body.userIdentity - ? undefined - : { - username: body.userIdentity?.["username"], - autoUser: !body.userIdentity?.autoUser - ? undefined - : { - scope: body.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.userIdentity?.autoUser?.["elevationLevel"], - }, - }, + ? body.userIdentity + : userIdentitySerializer(body.userIdentity), multiInstanceSettings: !body.multiInstanceSettings - ? undefined - : { - numberOfInstances: - body.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - body.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: - body.multiInstanceSettings?.["commonResourceFiles"] === - undefined - ? body.multiInstanceSettings?.["commonResourceFiles"] - : body.multiInstanceSettings?.["commonResourceFiles"].map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }), - ), - }, + ? body.multiInstanceSettings + : multiInstanceSettingsSerializer(body.multiInstanceSettings), dependsOn: !body.dependsOn - ? undefined - : { - taskIds: body.dependsOn?.["taskIds"], - taskIdRanges: - body.dependsOn?.["taskIdRanges"] === undefined - ? body.dependsOn?.["taskIdRanges"] - : body.dependsOn?.["taskIdRanges"].map((p) => ({ - start: p["start"], - end: p["end"], - })), - }, + ? body.dependsOn + : taskDependenciesSerializer(body.dependsOn), applicationPackageReferences: body["applicationPackageReferences"] === undefined ? body["applicationPackageReferences"] - : body["applicationPackageReferences"].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), + : body["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), authenticationTokenSettings: !body.authenticationTokenSettings - ? undefined - : { access: body.authenticationTokenSettings?.["access"] }, + ? body.authenticationTokenSettings + : authenticationTokenSettingsSerializer( + body.authenticationTokenSettings, + ), }, }); } @@ -16619,7 +10184,7 @@ export function _listTasksSend( export async function _listTasksDeserialize( result: ListTasks200Response | ListTasksDefaultResponse, -): Promise { +): Promise<_BatchTaskListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -16973,215 +10538,7 @@ export function _createTaskCollectionSend( timeOut: options?.timeOutInSeconds, }, body: { - value: collection["value"].map((p) => ({ - id: p["id"], - displayName: p["displayName"], - exitConditions: !p.exitConditions - ? undefined - : { - exitCodes: - p.exitConditions?.["exitCodes"] === undefined - ? p.exitConditions?.["exitCodes"] - : p.exitConditions?.["exitCodes"].map((p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - exitCodeRanges: - p.exitConditions?.["exitCodeRanges"] === undefined - ? p.exitConditions?.["exitCodeRanges"] - : p.exitConditions?.["exitCodeRanges"].map((p) => ({ - start: p["start"], - end: p["end"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - preProcessingError: !p.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - p.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - p.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !p.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - p.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - p.exitConditions?.fileUploadError?.["dependencyAction"], - }, - default: !p.exitConditions?.default - ? undefined - : { - jobAction: p.exitConditions?.default?.["jobAction"], - dependencyAction: - p.exitConditions?.default?.["dependencyAction"], - }, - }, - commandLine: p["commandLine"], - containerSettings: !p.containerSettings - ? undefined - : { - containerRunOptions: - p.containerSettings?.["containerRunOptions"], - imageName: p.containerSettings?.["imageName"], - registry: !p.containerSettings?.registry - ? undefined - : { - username: p.containerSettings?.registry?.["username"], - password: p.containerSettings?.registry?.["password"], - registryServer: - p.containerSettings?.registry?.["registryServer"], - identityReference: !p.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: p.containerSettings?.["workingDirectory"], - }, - resourceFiles: - p["resourceFiles"] === undefined - ? p["resourceFiles"] - : p["resourceFiles"].map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: - p["outputFiles"] === undefined - ? p["outputFiles"] - : p["outputFiles"].map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: - p.destination.container?.["uploadHeaders"] === - undefined - ? p.destination.container?.["uploadHeaders"] - : p.destination.container?.["uploadHeaders"].map( - (p) => ({ - name: p["name"], - value: p["value"], - }), - ), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: - p["environmentSettings"] === undefined - ? p["environmentSettings"] - : p["environmentSettings"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - affinityInfo: !p.affinityInfo - ? undefined - : { affinityId: p.affinityInfo?.["affinityId"] }, - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - retentionTime: p.constraints?.["retentionTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p["requiredSlots"], - userIdentity: !p.userIdentity - ? undefined - : { - username: p.userIdentity?.["username"], - autoUser: !p.userIdentity?.autoUser - ? undefined - : { - scope: p.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - multiInstanceSettings: !p.multiInstanceSettings - ? undefined - : { - numberOfInstances: - p.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - p.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: - p.multiInstanceSettings?.["commonResourceFiles"] === undefined - ? p.multiInstanceSettings?.["commonResourceFiles"] - : p.multiInstanceSettings?.["commonResourceFiles"].map( - (p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - }), - ), - }, - dependsOn: !p.dependsOn - ? undefined - : { - taskIds: p.dependsOn?.["taskIds"], - taskIdRanges: - p.dependsOn?.["taskIdRanges"] === undefined - ? p.dependsOn?.["taskIdRanges"] - : p.dependsOn?.["taskIdRanges"].map((p) => ({ - start: p["start"], - end: p["end"], - })), - }, - applicationPackageReferences: - p["applicationPackageReferences"] === undefined - ? p["applicationPackageReferences"] - : p["applicationPackageReferences"].map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !p.authenticationTokenSettings - ? undefined - : { access: p.authenticationTokenSettings?.["access"] }, - })), + value: collection["value"].map(batchTaskCreateOptionsSerializer), }, }); } @@ -17703,12 +11060,8 @@ export function _replaceTaskSend( }, body: { constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, + ? body.constraints + : taskConstraintsSerializer(body.constraints), }, }); } @@ -18039,7 +11392,7 @@ export async function _getTaskFileDeserialize( throw createRestError(result); } - return result.body; + return result.body as any; } /** Returns the content of the specified Task file. */ @@ -18145,7 +11498,7 @@ export function _listTaskFilesSend( export async function _listTaskFilesDeserialize( result: ListTaskFiles200Response | ListTaskFilesDefaultResponse, -): Promise { +): Promise<_NodeFileListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -19029,8 +12382,8 @@ export function _uploadNodeLogsSend( startTime: body["startTime"].toISOString(), endTime: body["endTime"]?.toISOString(), identityReference: !body.identityReference - ? undefined - : { resourceId: body.identityReference?.["resourceId"] }, + ? body.identityReference + : batchNodeIdentityReferenceSerializer(body.identityReference), }, }); } @@ -19092,7 +12445,7 @@ export function _listNodesSend( export async function _listNodesDeserialize( result: ListNodes200Response | ListNodesDefaultResponse, -): Promise { +): Promise<_BatchNodeListResult> { if (isUnexpected(result)) { throw createRestError(result); } @@ -19516,7 +12869,7 @@ export function _listNodeExtensionsSend( export async function _listNodeExtensionsDeserialize( result: ListNodeExtensions200Response | ListNodeExtensionsDefaultResponse, -): Promise { +): Promise<_NodeVMExtensionList> { if (isUnexpected(result)) { throw createRestError(result); } @@ -19789,7 +13142,7 @@ export function _listNodeFilesSend( export async function _listNodeFilesDeserialize( result: ListNodeFiles200Response | ListNodeFilesDefaultResponse, -): Promise { +): Promise<_NodeFileListResult> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts index 47ea77c9a6..07d99e7007 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts @@ -51,14 +51,11 @@ export { BatchNodeRemoteLoginSettingsResult, UploadBatchServiceLogsOptions, UploadBatchServiceLogsResult, - BatchNodeListResult, NodeVMExtension, VMExtension, VMExtensionInstanceView, InstanceViewStatus, StatusLevelTypes, - NodeVMExtensionList, - NodeFileListResult, NodeFile, FileProperties, BatchTaskCreateOptions, @@ -82,7 +79,6 @@ export { ApplicationPackageReference, AuthenticationTokenSettings, AccessScope, - BatchTaskListResult, BatchTask, BatchNodeInformation, TaskStatistics, @@ -149,12 +145,10 @@ export { JobScheduleStatistics, BatchJobScheduleUpdateOptions, BatchJobScheduleCreateOptions, - BatchJobScheduleListResult, BatchCertificate, CertificateState, DeleteCertificateError, CertificateFormat, - CertificateListResult, BatchJob, JobState, JobExecutionInformation, @@ -165,8 +159,6 @@ export { DisableJobOption, BatchJobTerminateOptions, BatchJobCreateOptions, - BatchJobListResult, - BatchJobListPreparationAndReleaseTaskStatusResult, JobPreparationAndReleaseTaskExecutionInformation, JobPreparationTaskExecutionInformation, JobPreparationTaskState, @@ -175,17 +167,13 @@ export { TaskCountsResult, TaskCounts, TaskSlotCounts, - AccountListSupportedImagesResult, ImageInformation, OSType, VerificationType, - PoolNodeCountsListResult, PoolNodeCounts, NodeCounts, - PoolListUsageMetricsResult, PoolUsageMetrics, BatchPoolCreateOptions, - BatchPoolListResult, BatchPool, PoolState, AllocationState, @@ -205,7 +193,6 @@ export { BatchNodeDeallocationOption, BatchPoolReplaceOptions, NodeRemoveOptions, - ApplicationListResult, BatchApplication, Versions, ListApplicationsOptionalParams, diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts index 632dc50282..d5f78b8449 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts @@ -50,14 +50,11 @@ export { BatchNodeRemoteLoginSettingsResult, UploadBatchServiceLogsOptions, UploadBatchServiceLogsResult, - BatchNodeListResult, NodeVMExtension, VMExtension, VMExtensionInstanceView, InstanceViewStatus, StatusLevelTypes, - NodeVMExtensionList, - NodeFileListResult, NodeFile, FileProperties, BatchTaskCreateOptions, @@ -81,7 +78,6 @@ export { ApplicationPackageReference, AuthenticationTokenSettings, AccessScope, - BatchTaskListResult, BatchTask, BatchNodeInformation, TaskStatistics, @@ -148,12 +144,10 @@ export { JobScheduleStatistics, BatchJobScheduleUpdateOptions, BatchJobScheduleCreateOptions, - BatchJobScheduleListResult, BatchCertificate, CertificateState, DeleteCertificateError, CertificateFormat, - CertificateListResult, BatchJob, JobState, JobExecutionInformation, @@ -164,8 +158,6 @@ export { DisableJobOption, BatchJobTerminateOptions, BatchJobCreateOptions, - BatchJobListResult, - BatchJobListPreparationAndReleaseTaskStatusResult, JobPreparationAndReleaseTaskExecutionInformation, JobPreparationTaskExecutionInformation, JobPreparationTaskState, @@ -174,17 +166,13 @@ export { TaskCountsResult, TaskCounts, TaskSlotCounts, - AccountListSupportedImagesResult, ImageInformation, OSType, VerificationType, - PoolNodeCountsListResult, PoolNodeCounts, NodeCounts, - PoolListUsageMetricsResult, PoolUsageMetrics, BatchPoolCreateOptions, - BatchPoolListResult, BatchPool, PoolState, AllocationState, @@ -204,7 +192,6 @@ export { BatchNodeDeallocationOption, BatchPoolReplaceOptions, NodeRemoveOptions, - ApplicationListResult, BatchApplication, Versions, } from "./models.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts index afe9fa4ebb..dd655324eb 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,97 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + BatchNodeUserCreateOptions as BatchNodeUserCreateOptionsRest, + BatchNodeUserUpdateOptions as BatchNodeUserUpdateOptionsRest, + StartTask as StartTaskRest, + TaskContainerSettings as TaskContainerSettingsRest, + ContainerRegistry as ContainerRegistryRest, + BatchNodeIdentityReference as BatchNodeIdentityReferenceRest, + ResourceFile as ResourceFileRest, + EnvironmentSetting as EnvironmentSettingRest, + UserIdentity as UserIdentityRest, + AutoUserSpecification as AutoUserSpecificationRest, + CertificateReference as CertificateReferenceRest, + ImageReference as ImageReferenceRest, + NodeRebootOptions as NodeRebootOptionsRest, + NodeReimageOptions as NodeReimageOptionsRest, + NodeDisableSchedulingOptions as NodeDisableSchedulingOptionsRest, + UploadBatchServiceLogsOptions as UploadBatchServiceLogsOptionsRest, + VMExtension as VMExtensionRest, + BatchTaskCreateOptions as BatchTaskCreateOptionsRest, + ExitConditions as ExitConditionsRest, + ExitCodeMapping as ExitCodeMappingRest, + ExitOptions as ExitOptionsRest, + ExitCodeRangeMapping as ExitCodeRangeMappingRest, + OutputFile as OutputFileRest, + OutputFileDestination as OutputFileDestinationRest, + OutputFileBlobContainerDestination as OutputFileBlobContainerDestinationRest, + HttpHeader as HttpHeaderRest, + OutputFileUploadOptions as OutputFileUploadOptionsRest, + AffinityInformation as AffinityInformationRest, + TaskConstraints as TaskConstraintsRest, + MultiInstanceSettings as MultiInstanceSettingsRest, + TaskDependencies as TaskDependenciesRest, + TaskIdRange as TaskIdRangeRest, + ApplicationPackageReference as ApplicationPackageReferenceRest, + AuthenticationTokenSettings as AuthenticationTokenSettingsRest, + BatchTask as BatchTaskRest, + BatchTaskCollection as BatchTaskCollectionRest, + BatchJobSchedule as BatchJobScheduleRest, + Schedule as ScheduleRest, + JobSpecification as JobSpecificationRest, + JobNetworkConfiguration as JobNetworkConfigurationRest, + JobConstraints as JobConstraintsRest, + JobManagerTask as JobManagerTaskRest, + JobPreparationTask as JobPreparationTaskRest, + JobReleaseTask as JobReleaseTaskRest, + PoolInformation as PoolInformationRest, + AutoPoolSpecification as AutoPoolSpecificationRest, + PoolSpecification as PoolSpecificationRest, + CloudServiceConfiguration as CloudServiceConfigurationRest, + VirtualMachineConfiguration as VirtualMachineConfigurationRest, + WindowsConfiguration as WindowsConfigurationRest, + DataDisk as DataDiskRest, + ContainerConfiguration as ContainerConfigurationRest, + DiskEncryptionConfiguration as DiskEncryptionConfigurationRest, + NodePlacementConfiguration as NodePlacementConfigurationRest, + OSDisk as OSDiskRest, + DiffDiskSettings as DiffDiskSettingsRest, + TaskSchedulingPolicy as TaskSchedulingPolicyRest, + NetworkConfiguration as NetworkConfigurationRest, + PoolEndpointConfiguration as PoolEndpointConfigurationRest, + InboundNATPool as InboundNATPoolRest, + NetworkSecurityGroupRule as NetworkSecurityGroupRuleRest, + PublicIPAddressConfiguration as PublicIPAddressConfigurationRest, + UserAccount as UserAccountRest, + LinuxUserConfiguration as LinuxUserConfigurationRest, + WindowsUserConfiguration as WindowsUserConfigurationRest, + MetadataItem as MetadataItemRest, + MountConfiguration as MountConfigurationRest, + AzureBlobFileSystemConfiguration as AzureBlobFileSystemConfigurationRest, + NFSMountConfiguration as NFSMountConfigurationRest, + CifsMountConfiguration as CifsMountConfigurationRest, + AzureFileShareConfiguration as AzureFileShareConfigurationRest, + BatchJobScheduleUpdateOptions as BatchJobScheduleUpdateOptionsRest, + BatchJobScheduleCreateOptions as BatchJobScheduleCreateOptionsRest, + BatchCertificate as BatchCertificateRest, + BatchJob as BatchJobRest, + BatchJobUpdateOptions as BatchJobUpdateOptionsRest, + BatchJobDisableOptions as BatchJobDisableOptionsRest, + BatchJobTerminateOptions as BatchJobTerminateOptionsRest, + BatchJobCreateOptions as BatchJobCreateOptionsRest, + BatchPoolCreateOptions as BatchPoolCreateOptionsRest, + BatchPoolUpdateOptions as BatchPoolUpdateOptionsRest, + BatchPoolEnableAutoScaleOptions as BatchPoolEnableAutoScaleOptionsRest, + BatchPoolEvaluateAutoScaleOptions as BatchPoolEvaluateAutoScaleOptionsRest, + BatchPoolResizeOptions as BatchPoolResizeOptionsRest, + BatchPoolReplaceOptions as BatchPoolReplaceOptionsRest, + NodeRemoveOptions as NodeRemoveOptionsRest, +} from "../rest/index.js"; + /** Options for creating a user account for RDP or SSH access on an Azure Batch Compute Node. */ export interface BatchNodeUserCreateOptions { /** The user name of the Account. */ @@ -15,6 +106,18 @@ export interface BatchNodeUserCreateOptions { sshPublicKey?: string; } +export function batchNodeUserCreateOptionsSerializer( + item: BatchNodeUserCreateOptions, +): BatchNodeUserCreateOptionsRest { + return { + name: item["name"], + isAdmin: item["isAdmin"], + expiryTime: item["expiryTime"]?.toISOString(), + password: item["password"], + sshPublicKey: item["sshPublicKey"], + }; +} + /** An error response received from the Azure Batch service. */ export interface BatchError { /** An identifier for the error. Codes are invariant and are intended to be consumed programmatically. */ @@ -51,6 +154,16 @@ export interface BatchNodeUserUpdateOptions { sshPublicKey?: string; } +export function batchNodeUserUpdateOptionsSerializer( + item: BatchNodeUserUpdateOptions, +): BatchNodeUserUpdateOptionsRest { + return { + password: item["password"], + expiryTime: item["expiryTime"]?.toISOString(), + sshPublicKey: item["sshPublicKey"], + }; +} + /** A Compute Node in the Batch service. */ export interface BatchNode { /** The ID of the Compute Node. Every Compute Node that is added to a Pool is assigned a unique ID. Whenever a Compute Node is removed from a Pool, all of its local files are deleted, and the ID is reclaimed and could be reused for new Compute Nodes. */ @@ -107,7 +220,6 @@ export interface BatchNode { } /** BatchNodeState enums */ -/** */ export type BatchNodeState = | "idle" | "rebooting" @@ -123,7 +235,6 @@ export type BatchNodeState = | "offline" | "preempted"; /** SchedulingState enums */ -/** */ export type SchedulingState = "enabled" | "disabled"; /** Information about a Task running on a Compute Node. */ @@ -143,7 +254,6 @@ export interface TaskInformation { } /** TaskState enums */ -/** */ export type TaskState = "active" | "preparing" | "running" | "completed"; /** Information about the execution of a Task. */ @@ -193,7 +303,6 @@ export interface TaskFailureInformation { } /** ErrorCategory enums */ -/** */ export type ErrorCategory = "usererror" | "servererror"; /** Represents a name-value pair. */ @@ -205,7 +314,6 @@ export interface NameValuePair { } /** TaskExecutionResult enums */ -/** */ export type TaskExecutionResult = "success" | "failure"; /** @@ -240,6 +348,28 @@ export interface StartTask { waitForSuccess?: boolean; } +export function startTaskSerializer(item: StartTask): StartTaskRest { + return { + commandLine: item["commandLine"], + containerSettings: !item.containerSettings + ? item.containerSettings + : taskContainerSettingsSerializer(item.containerSettings), + resourceFiles: + item["resourceFiles"] === undefined + ? item["resourceFiles"] + : item["resourceFiles"].map(resourceFileSerializer), + environmentSettings: + item["environmentSettings"] === undefined + ? item["environmentSettings"] + : item["environmentSettings"].map(environmentSettingSerializer), + userIdentity: !item.userIdentity + ? item.userIdentity + : userIdentitySerializer(item.userIdentity), + maxTaskRetryCount: item["maxTaskRetryCount"], + waitForSuccess: item["waitForSuccess"], + }; +} + /** The container settings for a Task. */ export interface TaskContainerSettings { /** Additional options to the container create command. These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. */ @@ -252,6 +382,19 @@ export interface TaskContainerSettings { workingDirectory?: ContainerWorkingDirectory; } +export function taskContainerSettingsSerializer( + item: TaskContainerSettings, +): TaskContainerSettingsRest { + return { + containerRunOptions: item["containerRunOptions"], + imageName: item["imageName"], + registry: !item.registry + ? item.registry + : containerRegistrySerializer(item.registry), + workingDirectory: item["workingDirectory"], + }; +} + /** A private container registry. */ export interface ContainerRegistry { /** The user name to log into the registry server. */ @@ -264,6 +407,19 @@ export interface ContainerRegistry { identityReference?: BatchNodeIdentityReference; } +export function containerRegistrySerializer( + item: ContainerRegistry, +): ContainerRegistryRest { + return { + username: item["username"], + password: item["password"], + registryServer: item["registryServer"], + identityReference: !item.identityReference + ? item.identityReference + : batchNodeIdentityReferenceSerializer(item.identityReference), + }; +} + /** * The reference to a user assigned identity associated with the Batch pool which * a compute node will use. @@ -273,8 +429,15 @@ export interface BatchNodeIdentityReference { resourceId?: string; } +export function batchNodeIdentityReferenceSerializer( + item: BatchNodeIdentityReference, +): BatchNodeIdentityReferenceRest { + return { + resourceId: item["resourceId"], + }; +} + /** ContainerWorkingDirectory enums */ -/** */ export type ContainerWorkingDirectory = | "taskWorkingDirectory" | "containerImageDefault"; @@ -297,6 +460,20 @@ export interface ResourceFile { identityReference?: BatchNodeIdentityReference; } +export function resourceFileSerializer(item: ResourceFile): ResourceFileRest { + return { + autoStorageContainerName: item["autoStorageContainerName"], + storageContainerUrl: item["storageContainerUrl"], + httpUrl: item["httpUrl"], + blobPrefix: item["blobPrefix"], + filePath: item["filePath"], + fileMode: item["fileMode"], + identityReference: !item.identityReference + ? item.identityReference + : batchNodeIdentityReferenceSerializer(item.identityReference), + }; +} + /** An environment variable to be set on a Task process. */ export interface EnvironmentSetting { /** The name of the environment variable. */ @@ -305,6 +482,15 @@ export interface EnvironmentSetting { value?: string; } +export function environmentSettingSerializer( + item: EnvironmentSetting, +): EnvironmentSettingRest { + return { + name: item["name"], + value: item["value"], + }; +} + /** The definition of the user identity under which the Task is run. Specify either the userName or autoUser property, but not both. */ export interface UserIdentity { /** The name of the user identity under which the Task is run. The userName and autoUser properties are mutually exclusive; you must specify one but not both. */ @@ -313,6 +499,15 @@ export interface UserIdentity { autoUser?: AutoUserSpecification; } +export function userIdentitySerializer(item: UserIdentity): UserIdentityRest { + return { + username: item["username"], + autoUser: !item.autoUser + ? item.autoUser + : autoUserSpecificationSerializer(item.autoUser), + }; +} + /** Specifies the options for the auto user that runs an Azure Batch Task. */ export interface AutoUserSpecification { /** The scope for the auto user. The default value is pool. If the pool is running Windows a value of Task should be specified if stricter isolation between tasks is required. For example, if the task mutates the registry in a way which could impact other tasks, or if certificates have been specified on the pool which should not be accessible by normal tasks but should be accessible by StartTasks. */ @@ -321,11 +516,18 @@ export interface AutoUserSpecification { elevationLevel?: ElevationLevel; } +export function autoUserSpecificationSerializer( + item: AutoUserSpecification, +): AutoUserSpecificationRest { + return { + scope: item["scope"], + elevationLevel: item["elevationLevel"], + }; +} + /** AutoUserScope enums */ -/** */ export type AutoUserScope = "task" | "pool"; /** ElevationLevel enums */ -/** */ export type ElevationLevel = "nonadmin" | "admin"; /** Information about a StartTask running on a Compute Node. */ @@ -351,7 +553,6 @@ export interface StartTaskInformation { } /** StartTaskState enums */ -/** */ export type StartTaskState = "running" | "completed"; /** A reference to a Certificate to be installed on Compute Nodes in a Pool. Warning: This object is deprecated and will be removed after February, 2024. Please use the [Azure KeyVault Extension](https://learn.microsoft.com/azure/batch/batch-certificate-migration-guide) instead. */ @@ -368,11 +569,21 @@ export interface CertificateReference { visibility?: CertificateVisibility[]; } +export function certificateReferenceSerializer( + item: CertificateReference, +): CertificateReferenceRest { + return { + thumbprint: item["thumbprint"], + thumbprintAlgorithm: item["thumbprintAlgorithm"], + storeLocation: item["storeLocation"], + storeName: item["storeName"], + visibility: item["visibility"], + }; +} + /** CertificateStoreLocation enums */ -/** */ export type CertificateStoreLocation = "currentuser" | "localmachine"; /** CertificateVisibility enums */ -/** */ export type CertificateVisibility = "starttask" | "task" | "remoteuser"; /** An error encountered by a Compute Node. */ @@ -408,7 +619,6 @@ export interface InboundEndpoint { } /** InboundEndpointProtocol enums */ -/** */ export type InboundEndpointProtocol = "tcp" | "udp"; /** @@ -448,14 +658,33 @@ export interface ImageReference { readonly exactVersion?: string; } +export function imageReferenceSerializer( + item: ImageReference, +): ImageReferenceRest { + return { + publisher: item["publisher"], + offer: item["offer"], + sku: item["sku"], + version: item["version"], + virtualMachineImageId: item["virtualMachineImageId"], + }; +} + /** Options for rebooting an Azure Batch Compute Node. */ export interface NodeRebootOptions { /** When to reboot the Compute Node and what to do with currently running Tasks. The default value is requeue. */ nodeRebootOption?: BatchNodeRebootOption; } +export function nodeRebootOptionsSerializer( + item: NodeRebootOptions, +): NodeRebootOptionsRest { + return { + nodeRebootOption: item["nodeRebootOption"], + }; +} + /** BatchNodeRebootOption enums */ -/** */ export type BatchNodeRebootOption = | "requeue" | "terminate" @@ -468,8 +697,15 @@ export interface NodeReimageOptions { nodeReimageOption?: BatchNodeReimageOption; } +export function nodeReimageOptionsSerializer( + item: NodeReimageOptions, +): NodeReimageOptionsRest { + return { + nodeReimageOption: item["nodeReimageOption"], + }; +} + /** BatchNodeReimageOption enums */ -/** */ export type BatchNodeReimageOption = | "requeue" | "terminate" @@ -482,8 +718,15 @@ export interface NodeDisableSchedulingOptions { nodeDisableSchedulingOption?: DisableBatchNodeSchedulingOption; } +export function nodeDisableSchedulingOptionsSerializer( + item: NodeDisableSchedulingOptions, +): NodeDisableSchedulingOptionsRest { + return { + nodeDisableSchedulingOption: item["nodeDisableSchedulingOption"], + }; +} + /** DisableBatchNodeSchedulingOption enums */ -/** */ export type DisableBatchNodeSchedulingOption = | "requeue" | "terminate" @@ -509,6 +752,19 @@ export interface UploadBatchServiceLogsOptions { identityReference?: BatchNodeIdentityReference; } +export function uploadBatchServiceLogsOptionsSerializer( + item: UploadBatchServiceLogsOptions, +): UploadBatchServiceLogsOptionsRest { + return { + containerUrl: item["containerUrl"], + startTime: item["startTime"].toISOString(), + endTime: item["endTime"]?.toISOString(), + identityReference: !item.identityReference + ? item.identityReference + : batchNodeIdentityReferenceSerializer(item.identityReference), + }; +} + /** The result of uploading Batch service log files from a specific Compute Node. */ export interface UploadBatchServiceLogsResult { /** The virtual directory within Azure Blob Storage container to which the Batch Service log file(s) will be uploaded. The virtual directory name is part of the blob name for each log file uploaded, and it is built based poolId, nodeId and a unique identifier. */ @@ -518,7 +774,7 @@ export interface UploadBatchServiceLogsResult { } /** The result of listing the Compute Nodes in a Pool. */ -export interface BatchNodeListResult { +export interface _BatchNodeListResult { /** The list of Compute Nodes. */ value?: BatchNode[]; /** The URL to get the next set of results. */ @@ -557,6 +813,24 @@ export interface VMExtension { provisionAfterExtensions?: string[]; } +export function vMExtensionSerializer(item: VMExtension): VMExtensionRest { + return { + name: item["name"], + publisher: item["publisher"], + type: item["type"], + typeHandlerVersion: item["typeHandlerVersion"], + autoUpgradeMinorVersion: item["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: item["enableAutomaticUpgrade"], + settings: !item.settings + ? item.settings + : (serializeRecord(item.settings as any) as any), + protectedSettings: !item.protectedSettings + ? item.protectedSettings + : (serializeRecord(item.protectedSettings as any) as any), + provisionAfterExtensions: item["provisionAfterExtensions"], + }; +} + /** The vm extension instance view. */ export interface VMExtensionInstanceView { /** The name of the vm extension instance view. */ @@ -582,11 +856,10 @@ export interface InstanceViewStatus { } /** Level code. */ -/** */ export type StatusLevelTypes = "Error" | "Info" | "Warning"; /** The result of listing the Compute Node extensions in a Node. */ -export interface NodeVMExtensionList { +export interface _NodeVMExtensionList { /** The list of Compute Node extensions. */ value?: NodeVMExtension[]; /** The URL to get the next set of results. */ @@ -597,7 +870,7 @@ export interface NodeVMExtensionList { * The result of listing the files on a Compute Node, or the files associated with * a Task on a Compute Node. */ -export interface NodeFileListResult { +export interface _NodeFileListResult { /** The list of files. */ value?: NodeFile[]; /** The URL to get the next set of results. */ @@ -666,6 +939,59 @@ export interface BatchTaskCreateOptions { authenticationTokenSettings?: AuthenticationTokenSettings; } +export function batchTaskCreateOptionsSerializer( + item: BatchTaskCreateOptions, +): BatchTaskCreateOptionsRest { + return { + id: item["id"], + displayName: item["displayName"], + exitConditions: !item.exitConditions + ? item.exitConditions + : exitConditionsSerializer(item.exitConditions), + commandLine: item["commandLine"], + containerSettings: !item.containerSettings + ? item.containerSettings + : taskContainerSettingsSerializer(item.containerSettings), + resourceFiles: + item["resourceFiles"] === undefined + ? item["resourceFiles"] + : item["resourceFiles"].map(resourceFileSerializer), + outputFiles: + item["outputFiles"] === undefined + ? item["outputFiles"] + : item["outputFiles"].map(outputFileSerializer), + environmentSettings: + item["environmentSettings"] === undefined + ? item["environmentSettings"] + : item["environmentSettings"].map(environmentSettingSerializer), + affinityInfo: !item.affinityInfo + ? item.affinityInfo + : affinityInformationSerializer(item.affinityInfo), + constraints: !item.constraints + ? item.constraints + : taskConstraintsSerializer(item.constraints), + requiredSlots: item["requiredSlots"], + userIdentity: !item.userIdentity + ? item.userIdentity + : userIdentitySerializer(item.userIdentity), + multiInstanceSettings: !item.multiInstanceSettings + ? item.multiInstanceSettings + : multiInstanceSettingsSerializer(item.multiInstanceSettings), + dependsOn: !item.dependsOn + ? item.dependsOn + : taskDependenciesSerializer(item.dependsOn), + applicationPackageReferences: + item["applicationPackageReferences"] === undefined + ? item["applicationPackageReferences"] + : item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + authenticationTokenSettings: !item.authenticationTokenSettings + ? item.authenticationTokenSettings + : authenticationTokenSettingsSerializer(item.authenticationTokenSettings), + }; +} + /** Specifies how the Batch service should respond when the Task completes. */ export interface ExitConditions { /** A list of individual Task exit codes and how the Batch service should respond to them. */ @@ -680,6 +1006,28 @@ export interface ExitConditions { default?: ExitOptions; } +export function exitConditionsSerializer( + item: ExitConditions, +): ExitConditionsRest { + return { + exitCodes: + item["exitCodes"] === undefined + ? item["exitCodes"] + : item["exitCodes"].map(exitCodeMappingSerializer), + exitCodeRanges: + item["exitCodeRanges"] === undefined + ? item["exitCodeRanges"] + : item["exitCodeRanges"].map(exitCodeRangeMappingSerializer), + preProcessingError: !item.preProcessingError + ? item.preProcessingError + : exitOptionsSerializer(item.preProcessingError), + fileUploadError: !item.fileUploadError + ? item.fileUploadError + : exitOptionsSerializer(item.fileUploadError), + default: !item.default ? item.default : exitOptionsSerializer(item.default), + }; +} + /** * How the Batch service should respond if a Task exits with a particular exit * code. @@ -691,6 +1039,15 @@ export interface ExitCodeMapping { exitOptions: ExitOptions; } +export function exitCodeMappingSerializer( + item: ExitCodeMapping, +): ExitCodeMappingRest { + return { + code: item["code"], + exitOptions: exitOptionsSerializer(item.exitOptions), + }; +} + /** Specifies how the Batch service responds to a particular exit condition. */ export interface ExitOptions { /** An action to take on the Job containing the Task, if the Task completes with the given exit condition and the Job's onTaskFailed property is 'performExitOptionsJobAction'. The default is none for exit code 0 and terminate for all other exit conditions. If the Job's onTaskFailed property is noaction, then specifying this property returns an error and the add Task request fails with an invalid property value error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). */ @@ -699,11 +1056,16 @@ export interface ExitOptions { dependencyAction?: DependencyAction; } +export function exitOptionsSerializer(item: ExitOptions): ExitOptionsRest { + return { + jobAction: item["jobAction"], + dependencyAction: item["dependencyAction"], + }; +} + /** JobAction enums */ -/** */ export type JobAction = "none" | "disable" | "terminate"; /** DependencyAction enums */ -/** */ export type DependencyAction = "satisfy" | "block"; /** @@ -719,6 +1081,16 @@ export interface ExitCodeRangeMapping { exitOptions: ExitOptions; } +export function exitCodeRangeMappingSerializer( + item: ExitCodeRangeMapping, +): ExitCodeRangeMappingRest { + return { + start: item["start"], + end: item["end"], + exitOptions: exitOptionsSerializer(item.exitOptions), + }; +} + /** On every file uploads, Batch service writes two log files to the compute node, 'fileuploadout.txt' and 'fileuploaderr.txt'. These log files are used to learn more about a specific failure. */ export interface OutputFile { /** A pattern indicating which file(s) to upload. Both relative and absolute paths are supported. Relative paths are relative to the Task working directory. The following wildcards are supported: * matches 0 or more characters (for example pattern abc* would match abc or abcdef), ** matches any directory, ? matches any single character, [abc] matches one character in the brackets, and [a-c] matches one character in the range. */ @@ -729,12 +1101,30 @@ export interface OutputFile { uploadOptions: OutputFileUploadOptions; } +export function outputFileSerializer(item: OutputFile): OutputFileRest { + return { + filePattern: item["filePattern"], + destination: outputFileDestinationSerializer(item.destination), + uploadOptions: outputFileUploadOptionsSerializer(item.uploadOptions), + }; +} + /** The destination to which a file should be uploaded. */ export interface OutputFileDestination { /** A location in Azure blob storage to which files are uploaded. */ container?: OutputFileBlobContainerDestination; } +export function outputFileDestinationSerializer( + item: OutputFileDestination, +): OutputFileDestinationRest { + return { + container: !item.container + ? item.container + : outputFileBlobContainerDestinationSerializer(item.container), + }; +} + /** Specifies a file upload destination within an Azure blob storage container. */ export interface OutputFileBlobContainerDestination { /** The destination blob or virtual directory within the Azure Storage container. If filePattern refers to a specific file (i.e. contains no wildcards), then path is the name of the blob to which to upload that file. If filePattern contains one or more wildcards (and therefore may match multiple files), then path is the name of the blob virtual directory (which is prepended to each blob name) to which to upload the file(s). If omitted, file(s) are uploaded to the root of the container with a blob name matching their file name. */ @@ -747,6 +1137,22 @@ export interface OutputFileBlobContainerDestination { uploadHeaders?: HttpHeader[]; } +export function outputFileBlobContainerDestinationSerializer( + item: OutputFileBlobContainerDestination, +): OutputFileBlobContainerDestinationRest { + return { + path: item["path"], + containerUrl: item["containerUrl"], + identityReference: !item.identityReference + ? item.identityReference + : batchNodeIdentityReferenceSerializer(item.identityReference), + uploadHeaders: + item["uploadHeaders"] === undefined + ? item["uploadHeaders"] + : item["uploadHeaders"].map(httpHeaderSerializer), + }; +} + /** An HTTP header name-value pair */ export interface HttpHeader { /** The case-insensitive name of the header to be used while uploading output files. */ @@ -755,6 +1161,13 @@ export interface HttpHeader { value?: string; } +export function httpHeaderSerializer(item: HttpHeader): HttpHeaderRest { + return { + name: item["name"], + value: item["value"], + }; +} + /** * Options for an output file upload operation, including under what conditions * to perform the upload. @@ -764,8 +1177,15 @@ export interface OutputFileUploadOptions { uploadCondition: OutputFileUploadCondition; } +export function outputFileUploadOptionsSerializer( + item: OutputFileUploadOptions, +): OutputFileUploadOptionsRest { + return { + uploadCondition: item["uploadCondition"], + }; +} + /** OutputFileUploadCondition enums */ -/** */ export type OutputFileUploadCondition = | "tasksuccess" | "taskfailure" @@ -780,6 +1200,14 @@ export interface AffinityInformation { affinityId: string; } +export function affinityInformationSerializer( + item: AffinityInformation, +): AffinityInformationRest { + return { + affinityId: item["affinityId"], + }; +} + /** Execution constraints to apply to a Task. */ export interface TaskConstraints { /** The maximum elapsed time that the Task may run, measured from the time the Task starts. If the Task does not complete within the time limit, the Batch service terminates it. If this is not specified, there is no time limit on how long the Task may run. */ @@ -790,6 +1218,16 @@ export interface TaskConstraints { maxTaskRetryCount?: number; } +export function taskConstraintsSerializer( + item: TaskConstraints, +): TaskConstraintsRest { + return { + maxWallClockTime: item["maxWallClockTime"], + retentionTime: item["retentionTime"], + maxTaskRetryCount: item["maxTaskRetryCount"], + }; +} + /** * Multi-instance Tasks are commonly used to support MPI Tasks. In the MPI case, * if any of the subtasks fail (for example due to exiting with a non-zero exit @@ -805,6 +1243,19 @@ export interface MultiInstanceSettings { commonResourceFiles?: ResourceFile[]; } +export function multiInstanceSettingsSerializer( + item: MultiInstanceSettings, +): MultiInstanceSettingsRest { + return { + numberOfInstances: item["numberOfInstances"], + coordinationCommandLine: item["coordinationCommandLine"], + commonResourceFiles: + item["commonResourceFiles"] === undefined + ? item["commonResourceFiles"] + : item["commonResourceFiles"].map(resourceFileSerializer), + }; +} + /** * Specifies any dependencies of a Task. Any Task that is explicitly specified or * within a dependency range must complete before the dependant Task will be @@ -817,6 +1268,18 @@ export interface TaskDependencies { taskIdRanges?: TaskIdRange[]; } +export function taskDependenciesSerializer( + item: TaskDependencies, +): TaskDependenciesRest { + return { + taskIds: item["taskIds"], + taskIdRanges: + item["taskIdRanges"] === undefined + ? item["taskIdRanges"] + : item["taskIdRanges"].map(taskIdRangeSerializer), + }; +} + /** * The start and end of the range are inclusive. For example, if a range has start * 9 and end 12, then it represents Tasks '9', '10', '11' and '12'. @@ -828,6 +1291,13 @@ export interface TaskIdRange { end: number; } +export function taskIdRangeSerializer(item: TaskIdRange): TaskIdRangeRest { + return { + start: item["start"], + end: item["end"], + }; +} + /** A reference to an Package to be deployed to Compute Nodes. */ export interface ApplicationPackageReference { /** The ID of the application to deploy. When creating a pool, the package's application ID must be fully qualified (/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Batch/batchAccounts/{accountName}/applications/{applicationName}). */ @@ -836,6 +1306,15 @@ export interface ApplicationPackageReference { version?: string; } +export function applicationPackageReferenceSerializer( + item: ApplicationPackageReference, +): ApplicationPackageReferenceRest { + return { + applicationId: item["applicationId"], + version: item["version"], + }; +} + /** * The settings for an authentication token that the Task can use to perform Batch * service operations. @@ -845,12 +1324,19 @@ export interface AuthenticationTokenSettings { access?: AccessScope[]; } +export function authenticationTokenSettingsSerializer( + item: AuthenticationTokenSettings, +): AuthenticationTokenSettingsRest { + return { + access: item["access"], + }; +} + /** AccessScope enums */ -/** */ export type AccessScope = "job"; /** The result of listing the Tasks in a Job. */ -export interface BatchTaskListResult { +export interface _BatchTaskListResult { /** The list of Tasks. */ value?: BatchTask[]; /** The URL to get the next set of results. */ @@ -925,6 +1411,14 @@ export interface BatchTask { readonly authenticationTokenSettings?: AuthenticationTokenSettings; } +export function batchTaskSerializer(item: BatchTask): BatchTaskRest { + return { + constraints: !item.constraints + ? item.constraints + : taskConstraintsSerializer(item.constraints), + }; +} + /** Information about the Compute Node on which a Task ran. */ export interface BatchNodeInformation { /** An identifier for the Node on which the Task ran, which can be passed when adding a Task to request that the Task be scheduled on this Compute Node. */ @@ -973,6 +1467,14 @@ export interface BatchTaskCollection { value: BatchTaskCreateOptions[]; } +export function batchTaskCollectionSerializer( + item: BatchTaskCollection, +): BatchTaskCollectionRest { + return { + value: item["value"].map(batchTaskCreateOptionsSerializer), + }; +} + /** The result of adding a collection of Tasks to a Job. */ export interface TaskAddCollectionResult { /** The results of the add Task collection operation. */ @@ -996,7 +1498,6 @@ export interface TaskAddResult { } /** TaskAddStatus enums */ -/** */ export type TaskAddStatus = "Success" | "clienterror" | "servererror"; /** The result of listing the subtasks of a Task. */ @@ -1034,7 +1535,6 @@ export interface SubtaskInformation { } /** SubtaskState enums */ -/** */ export type SubtaskState = "preparing" | "running" | "completed"; /** @@ -1074,8 +1574,20 @@ export interface BatchJobSchedule { readonly stats?: JobScheduleStatistics; } +export function batchJobScheduleSerializer( + item: BatchJobSchedule, +): BatchJobScheduleRest { + return { + schedule: scheduleSerializer(item.schedule), + jobSpecification: jobSpecificationSerializer(item.jobSpecification), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** JobScheduleState enums */ -/** */ export type JobScheduleState = | "active" | "completed" @@ -1098,6 +1610,15 @@ export interface Schedule { recurrenceInterval?: string; } +export function scheduleSerializer(item: Schedule): ScheduleRest { + return { + doNotRunUntil: item["doNotRunUntil"]?.toISOString(), + doNotRunAfter: item["doNotRunAfter"]?.toISOString(), + startWindow: item["startWindow"], + recurrenceInterval: item["recurrenceInterval"], + }; +} + /** Specifies details of the Jobs to be created on a schedule. */ export interface JobSpecification { /** The priority of Jobs created under this schedule. Priority values can range from -1000 to 1000, with -1000 being the lowest priority and 1000 being the highest priority. The default value is 0. This priority is used as the default for all Jobs under the Job Schedule. You can update a Job's priority after it has been created using by using the update Job API. */ @@ -1132,11 +1653,47 @@ export interface JobSpecification { metadata?: MetadataItem[]; } +export function jobSpecificationSerializer( + item: JobSpecification, +): JobSpecificationRest { + return { + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + displayName: item["displayName"], + usesTaskDependencies: item["usesTaskDependencies"], + onAllTasksComplete: item["onAllTasksComplete"], + onTaskFailure: item["onTaskFailure"], + networkConfiguration: !item.networkConfiguration + ? item.networkConfiguration + : jobNetworkConfigurationSerializer(item.networkConfiguration), + constraints: !item.constraints + ? item.constraints + : jobConstraintsSerializer(item.constraints), + jobManagerTask: !item.jobManagerTask + ? item.jobManagerTask + : jobManagerTaskSerializer(item.jobManagerTask), + jobPreparationTask: !item.jobPreparationTask + ? item.jobPreparationTask + : jobPreparationTaskSerializer(item.jobPreparationTask), + jobReleaseTask: !item.jobReleaseTask + ? item.jobReleaseTask + : jobReleaseTaskSerializer(item.jobReleaseTask), + commonEnvironmentSettings: + item["commonEnvironmentSettings"] === undefined + ? item["commonEnvironmentSettings"] + : item["commonEnvironmentSettings"].map(environmentSettingSerializer), + poolInfo: poolInformationSerializer(item.poolInfo), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** The action the Batch service should take when all Tasks in the Job are in the completed state. */ -/** */ export type OnAllTasksComplete = "noaction" | "terminatejob"; /** OnTaskFailure enums */ -/** */ export type OnTaskFailure = "noaction" | "performexitoptionsjobaction"; /** The network configuration for the Job. */ @@ -1145,6 +1702,14 @@ export interface JobNetworkConfiguration { subnetId: string; } +export function jobNetworkConfigurationSerializer( + item: JobNetworkConfiguration, +): JobNetworkConfigurationRest { + return { + subnetId: item["subnetId"], + }; +} + /** The execution constraints for a Job. */ export interface JobConstraints { /** The maximum elapsed time that the Job may run, measured from the time the Job is created. If the Job does not complete within the time limit, the Batch service terminates it and any Tasks that are still running. In this case, the termination reason will be MaxWallClockTimeExpiry. If this property is not specified, there is no time limit on how long the Job may run. */ @@ -1153,6 +1718,15 @@ export interface JobConstraints { maxTaskRetryCount?: number; } +export function jobConstraintsSerializer( + item: JobConstraints, +): JobConstraintsRest { + return { + maxWallClockTime: item["maxWallClockTime"], + maxTaskRetryCount: item["maxTaskRetryCount"], + }; +} + /** * Specifies details of a Job Manager Task. * The Job Manager Task is automatically started when the Job is created. The @@ -1220,6 +1794,50 @@ export interface JobManagerTask { allowLowPriorityNode?: boolean; } +export function jobManagerTaskSerializer( + item: JobManagerTask, +): JobManagerTaskRest { + return { + id: item["id"], + displayName: item["displayName"], + commandLine: item["commandLine"], + containerSettings: !item.containerSettings + ? item.containerSettings + : taskContainerSettingsSerializer(item.containerSettings), + resourceFiles: + item["resourceFiles"] === undefined + ? item["resourceFiles"] + : item["resourceFiles"].map(resourceFileSerializer), + outputFiles: + item["outputFiles"] === undefined + ? item["outputFiles"] + : item["outputFiles"].map(outputFileSerializer), + environmentSettings: + item["environmentSettings"] === undefined + ? item["environmentSettings"] + : item["environmentSettings"].map(environmentSettingSerializer), + constraints: !item.constraints + ? item.constraints + : taskConstraintsSerializer(item.constraints), + requiredSlots: item["requiredSlots"], + killJobOnCompletion: item["killJobOnCompletion"], + userIdentity: !item.userIdentity + ? item.userIdentity + : userIdentitySerializer(item.userIdentity), + runExclusive: item["runExclusive"], + applicationPackageReferences: + item["applicationPackageReferences"] === undefined + ? item["applicationPackageReferences"] + : item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + authenticationTokenSettings: !item.authenticationTokenSettings + ? item.authenticationTokenSettings + : authenticationTokenSettingsSerializer(item.authenticationTokenSettings), + allowLowPriorityNode: item["allowLowPriorityNode"], + }; +} + /** * A Job Preparation Task to run before any Tasks of the Job on any given Compute Node. * You can use Job Preparation to prepare a Node to run Tasks for the Job. @@ -1269,6 +1887,34 @@ export interface JobPreparationTask { rerunOnNodeRebootAfterSuccess?: boolean; } +export function jobPreparationTaskSerializer( + item: JobPreparationTask, +): JobPreparationTaskRest { + return { + id: item["id"], + commandLine: item["commandLine"], + containerSettings: !item.containerSettings + ? item.containerSettings + : taskContainerSettingsSerializer(item.containerSettings), + resourceFiles: + item["resourceFiles"] === undefined + ? item["resourceFiles"] + : item["resourceFiles"].map(resourceFileSerializer), + environmentSettings: + item["environmentSettings"] === undefined + ? item["environmentSettings"] + : item["environmentSettings"].map(environmentSettingSerializer), + constraints: !item.constraints + ? item.constraints + : taskConstraintsSerializer(item.constraints), + waitForSuccess: item["waitForSuccess"], + userIdentity: !item.userIdentity + ? item.userIdentity + : userIdentitySerializer(item.userIdentity), + rerunOnNodeRebootAfterSuccess: item["rerunOnNodeRebootAfterSuccess"], + }; +} + /** * A Job Release Task to run on Job completion on any Compute Node where the Job has run. * The Job Release Task runs when the Job ends, because of one of the following: @@ -1306,6 +1952,31 @@ export interface JobReleaseTask { userIdentity?: UserIdentity; } +export function jobReleaseTaskSerializer( + item: JobReleaseTask, +): JobReleaseTaskRest { + return { + id: item["id"], + commandLine: item["commandLine"], + containerSettings: !item.containerSettings + ? item.containerSettings + : taskContainerSettingsSerializer(item.containerSettings), + resourceFiles: + item["resourceFiles"] === undefined + ? item["resourceFiles"] + : item["resourceFiles"].map(resourceFileSerializer), + environmentSettings: + item["environmentSettings"] === undefined + ? item["environmentSettings"] + : item["environmentSettings"].map(environmentSettingSerializer), + maxWallClockTime: item["maxWallClockTime"], + retentionTime: item["retentionTime"], + userIdentity: !item.userIdentity + ? item.userIdentity + : userIdentitySerializer(item.userIdentity), + }; +} + /** Specifies how a Job should be assigned to a Pool. */ export interface PoolInformation { /** The ID of an existing Pool. All the Tasks of the Job will run on the specified Pool. You must ensure that the Pool referenced by this property exists. If the Pool does not exist at the time the Batch service tries to schedule a Job, no Tasks for the Job will run until you create a Pool with that id. Note that the Batch service will not reject the Job request; it will simply not run Tasks until the Pool exists. You must specify either the Pool ID or the auto Pool specification, but not both. */ @@ -1314,6 +1985,17 @@ export interface PoolInformation { autoPoolSpecification?: AutoPoolSpecification; } +export function poolInformationSerializer( + item: PoolInformation, +): PoolInformationRest { + return { + poolId: item["poolId"], + autoPoolSpecification: !item.autoPoolSpecification + ? item.autoPoolSpecification + : autoPoolSpecificationSerializer(item.autoPoolSpecification), + }; +} + /** * Specifies characteristics for a temporary 'auto pool'. The Batch service will * create this auto Pool when the Job is submitted. @@ -1329,8 +2011,18 @@ export interface AutoPoolSpecification { pool?: PoolSpecification; } +export function autoPoolSpecificationSerializer( + item: AutoPoolSpecification, +): AutoPoolSpecificationRest { + return { + autoPoolIdPrefix: item["autoPoolIdPrefix"], + poolLifetimeOption: item["poolLifetimeOption"], + keepAlive: item["keepAlive"], + pool: !item.pool ? item.pool : poolSpecificationSerializer(item.pool), + }; +} + /** PoolLifetimeOption enums */ -/** */ export type PoolLifetimeOption = "jobschedule" | "job"; /** Specification for creating a new Pool. */ @@ -1385,6 +2077,62 @@ export interface PoolSpecification { targetNodeCommunicationMode?: NodeCommunicationMode; } +export function poolSpecificationSerializer( + item: PoolSpecification, +): PoolSpecificationRest { + return { + displayName: item["displayName"], + vmSize: item["vmSize"], + cloudServiceConfiguration: !item.cloudServiceConfiguration + ? item.cloudServiceConfiguration + : cloudServiceConfigurationSerializer(item.cloudServiceConfiguration), + virtualMachineConfiguration: !item.virtualMachineConfiguration + ? item.virtualMachineConfiguration + : virtualMachineConfigurationSerializer(item.virtualMachineConfiguration), + taskSlotsPerNode: item["taskSlotsPerNode"], + taskSchedulingPolicy: !item.taskSchedulingPolicy + ? item.taskSchedulingPolicy + : taskSchedulingPolicySerializer(item.taskSchedulingPolicy), + resizeTimeout: item["resizeTimeout"], + targetDedicatedNodes: item["targetDedicatedNodes"], + targetLowPriorityNodes: item["targetLowPriorityNodes"], + enableAutoScale: item["enableAutoScale"], + autoScaleFormula: item["autoScaleFormula"], + autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], + enableInterNodeCommunication: item["enableInterNodeCommunication"], + networkConfiguration: !item.networkConfiguration + ? item.networkConfiguration + : networkConfigurationSerializer(item.networkConfiguration), + startTask: !item.startTask + ? item.startTask + : startTaskSerializer(item.startTask), + certificateReferences: + item["certificateReferences"] === undefined + ? item["certificateReferences"] + : item["certificateReferences"].map(certificateReferenceSerializer), + applicationPackageReferences: + item["applicationPackageReferences"] === undefined + ? item["applicationPackageReferences"] + : item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + applicationLicenses: item["applicationLicenses"], + userAccounts: + item["userAccounts"] === undefined + ? item["userAccounts"] + : item["userAccounts"].map(userAccountSerializer), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + mountConfiguration: + item["mountConfiguration"] === undefined + ? item["mountConfiguration"] + : item["mountConfiguration"].map(mountConfigurationSerializer), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + }; +} + /** * The configuration for Compute Nodes in a Pool based on the Azure Cloud Services * platform. @@ -1408,6 +2156,15 @@ export interface CloudServiceConfiguration { osVersion?: string; } +export function cloudServiceConfigurationSerializer( + item: CloudServiceConfiguration, +): CloudServiceConfigurationRest { + return { + osFamily: item["osFamily"], + osVersion: item["osVersion"], + }; +} + /** * The configuration for Compute Nodes in a Pool based on the Azure Virtual * Machines infrastructure. @@ -1445,12 +2202,51 @@ export interface VirtualMachineConfiguration { osDisk?: OSDisk; } +export function virtualMachineConfigurationSerializer( + item: VirtualMachineConfiguration, +): VirtualMachineConfigurationRest { + return { + imageReference: imageReferenceSerializer(item.imageReference), + nodeAgentSKUId: item["nodeAgentSkuId"], + windowsConfiguration: !item.windowsConfiguration + ? item.windowsConfiguration + : windowsConfigurationSerializer(item.windowsConfiguration), + dataDisks: + item["dataDisks"] === undefined + ? item["dataDisks"] + : item["dataDisks"].map(dataDiskSerializer), + licenseType: item["licenseType"], + containerConfiguration: !item.containerConfiguration + ? item.containerConfiguration + : containerConfigurationSerializer(item.containerConfiguration), + diskEncryptionConfiguration: !item.diskEncryptionConfiguration + ? item.diskEncryptionConfiguration + : diskEncryptionConfigurationSerializer(item.diskEncryptionConfiguration), + nodePlacementConfiguration: !item.nodePlacementConfiguration + ? item.nodePlacementConfiguration + : nodePlacementConfigurationSerializer(item.nodePlacementConfiguration), + extensions: + item["extensions"] === undefined + ? item["extensions"] + : item["extensions"].map(vMExtensionSerializer), + osDisk: !item.osDisk ? item.osDisk : oSDiskSerializer(item.osDisk), + }; +} + /** Windows operating system settings to apply to the virtual machine. */ export interface WindowsConfiguration { /** Whether automatic updates are enabled on the virtual machine. If omitted, the default value is true. */ enableAutomaticUpdates?: boolean; } +export function windowsConfigurationSerializer( + item: WindowsConfiguration, +): WindowsConfigurationRest { + return { + enableAutomaticUpdates: item["enableAutomaticUpdates"], + }; +} + /** * Settings which will be used by the data disks associated to Compute Nodes in * the Pool. When using attached data disks, you need to mount and format the @@ -1467,11 +2263,18 @@ export interface DataDisk { storageAccountType?: StorageAccountType; } +export function dataDiskSerializer(item: DataDisk): DataDiskRest { + return { + lun: item["lun"], + caching: item["caching"], + diskSizeGB: item["diskSizeGb"], + storageAccountType: item["storageAccountType"], + }; +} + /** CachingType enums */ -/** */ export type CachingType = "none" | "readonly" | "readwrite"; /** StorageAccountType enums */ -/** */ export type StorageAccountType = "standard_lrs" | "premium_lrs"; /** The configuration for container-enabled Pools. */ @@ -1484,8 +2287,20 @@ export interface ContainerConfiguration { containerRegistries?: ContainerRegistry[]; } +export function containerConfigurationSerializer( + item: ContainerConfiguration, +): ContainerConfigurationRest { + return { + type: item["type"], + containerImageNames: item["containerImageNames"], + containerRegistries: + item["containerRegistries"] === undefined + ? item["containerRegistries"] + : item["containerRegistries"].map(containerRegistrySerializer), + }; +} + /** ContainerType enums */ -/** */ export type ContainerType = "dockerCompatible" | "criCompatible"; /** @@ -1498,8 +2313,15 @@ export interface DiskEncryptionConfiguration { targets?: DiskEncryptionTarget[]; } +export function diskEncryptionConfigurationSerializer( + item: DiskEncryptionConfiguration, +): DiskEncryptionConfigurationRest { + return { + targets: item["targets"], + }; +} + /** DiskEncryptionTarget enums */ -/** */ export type DiskEncryptionTarget = "osdisk" | "temporarydisk"; /** @@ -1512,8 +2334,15 @@ export interface NodePlacementConfiguration { policy?: NodePlacementPolicyType; } +export function nodePlacementConfigurationSerializer( + item: NodePlacementConfiguration, +): NodePlacementConfigurationRest { + return { + policy: item["policy"], + }; +} + /** NodePlacementPolicyType enums */ -/** */ export type NodePlacementPolicyType = "regional" | "zonal"; /** Settings for the operating system disk of the compute node (VM). */ @@ -1522,6 +2351,14 @@ export interface OSDisk { ephemeralOSDiskSettings?: DiffDiskSettings; } +export function oSDiskSerializer(item: OSDisk): OSDiskRest { + return { + ephemeralOSDiskSettings: !item.ephemeralOSDiskSettings + ? item.ephemeralOSDiskSettings + : diffDiskSettingsSerializer(item.ephemeralOSDiskSettings), + }; +} + /** * Specifies the ephemeral Disk Settings for the operating system disk used by the * compute node (VM). @@ -1531,8 +2368,15 @@ export interface DiffDiskSettings { placement?: DiffDiskPlacement; } +export function diffDiskSettingsSerializer( + item: DiffDiskSettings, +): DiffDiskSettingsRest { + return { + placement: item["placement"], + }; +} + /** AccessDiffDiskPlacementScope enums */ -/** */ export type DiffDiskPlacement = "cachedisk"; /** Specifies how Tasks should be distributed across Compute Nodes. */ @@ -1541,8 +2385,15 @@ export interface TaskSchedulingPolicy { nodeFillType: BatchNodeFillType; } +export function taskSchedulingPolicySerializer( + item: TaskSchedulingPolicy, +): TaskSchedulingPolicyRest { + return { + nodeFillType: item["nodeFillType"], + }; +} + /** BatchNodeFillType enums */ -/** */ export type BatchNodeFillType = "spread" | "pack"; /** The network configuration for a Pool. */ @@ -1559,8 +2410,25 @@ export interface NetworkConfiguration { enableAcceleratedNetworking?: boolean; } +export function networkConfigurationSerializer( + item: NetworkConfiguration, +): NetworkConfigurationRest { + return { + subnetId: item["subnetId"], + dynamicVNetAssignmentScope: item["dynamicVNetAssignmentScope"], + endpointConfiguration: !item.endpointConfiguration + ? item.endpointConfiguration + : poolEndpointConfigurationSerializer(item.endpointConfiguration), + publicIPAddressConfiguration: !item.publicIpAddressConfiguration + ? item.publicIpAddressConfiguration + : publicIpAddressConfigurationSerializer( + item.publicIpAddressConfiguration, + ), + enableAcceleratedNetworking: item["enableAcceleratedNetworking"], + }; +} + /** DynamicVNetAssignmentScope enums */ -/** */ export type DynamicVNetAssignmentScope = "none" | "job"; /** The endpoint configuration for a Pool. */ @@ -1569,6 +2437,14 @@ export interface PoolEndpointConfiguration { inboundNatPools: InboundNATPool[]; } +export function poolEndpointConfigurationSerializer( + item: PoolEndpointConfiguration, +): PoolEndpointConfigurationRest { + return { + inboundNATPools: item["inboundNatPools"].map(inboundNATPoolSerializer), + }; +} + /** * A inbound NAT Pool that can be used to address specific ports on Compute Nodes * in a Batch Pool externally. @@ -1588,6 +2464,24 @@ export interface InboundNATPool { networkSecurityGroupRules?: NetworkSecurityGroupRule[]; } +export function inboundNATPoolSerializer( + item: InboundNATPool, +): InboundNATPoolRest { + return { + name: item["name"], + protocol: item["protocol"], + backendPort: item["backendPort"], + frontendPortRangeStart: item["frontendPortRangeStart"], + frontendPortRangeEnd: item["frontendPortRangeEnd"], + networkSecurityGroupRules: + item["networkSecurityGroupRules"] === undefined + ? item["networkSecurityGroupRules"] + : item["networkSecurityGroupRules"].map( + networkSecurityGroupRuleSerializer, + ), + }; +} + /** A network security group rule to apply to an inbound endpoint. */ export interface NetworkSecurityGroupRule { /** The priority for this rule. Priorities within a Pool must be unique and are evaluated in order of priority. The lower the number the higher the priority. For example, rules could be specified with order numbers of 150, 250, and 350. The rule with the order number of 150 takes precedence over the rule that has an order of 250. Allowed priorities are 150 to 4096. If any reserved or duplicate values are provided the request fails with HTTP status code 400. */ @@ -1600,8 +2494,18 @@ export interface NetworkSecurityGroupRule { sourcePortRanges?: string[]; } +export function networkSecurityGroupRuleSerializer( + item: NetworkSecurityGroupRule, +): NetworkSecurityGroupRuleRest { + return { + priority: item["priority"], + access: item["access"], + sourceAddressPrefix: item["sourceAddressPrefix"], + sourcePortRanges: item["sourcePortRanges"], + }; +} + /** NetworkSecurityGroupRuleAccess enums */ -/** */ export type NetworkSecurityGroupRuleAccess = "allow" | "deny"; /** The public IP Address configuration of the networking configuration of a Pool. */ @@ -1612,8 +2516,16 @@ export interface PublicIpAddressConfiguration { ipAddressIds?: string[]; } +export function publicIpAddressConfigurationSerializer( + item: PublicIpAddressConfiguration, +): PublicIPAddressConfigurationRest { + return { + provision: item["ipAddressProvisioningType"], + ipAddressIds: item["ipAddressIds"], + }; +} + /** IPAddressProvisioningType enums */ -/** */ export type IpAddressProvisioningType = | "batchmanaged" | "usermanaged" @@ -1636,6 +2548,20 @@ export interface UserAccount { windowsUserConfiguration?: WindowsUserConfiguration; } +export function userAccountSerializer(item: UserAccount): UserAccountRest { + return { + name: item["name"], + password: item["password"], + elevationLevel: item["elevationLevel"], + linuxUserConfiguration: !item.linuxUserConfiguration + ? item.linuxUserConfiguration + : linuxUserConfigurationSerializer(item.linuxUserConfiguration), + windowsUserConfiguration: !item.windowsUserConfiguration + ? item.windowsUserConfiguration + : windowsUserConfigurationSerializer(item.windowsUserConfiguration), + }; +} + /** Properties used to create a user Account on a Linux Compute Node. */ export interface LinuxUserConfiguration { /** The user ID of the user Account. The uid and gid properties must be specified together or not at all. If not specified the underlying operating system picks the uid. */ @@ -1646,14 +2572,31 @@ export interface LinuxUserConfiguration { sshPrivateKey?: string; } +export function linuxUserConfigurationSerializer( + item: LinuxUserConfiguration, +): LinuxUserConfigurationRest { + return { + uid: item["uid"], + gid: item["gid"], + sshPrivateKey: item["sshPrivateKey"], + }; +} + /** Properties used to create a user Account on a Windows Compute Node. */ export interface WindowsUserConfiguration { /** The login mode for the user. The default value for VirtualMachineConfiguration Pools is 'batch' and for CloudServiceConfiguration Pools is 'interactive'. */ loginMode?: LoginMode; } +export function windowsUserConfigurationSerializer( + item: WindowsUserConfiguration, +): WindowsUserConfigurationRest { + return { + loginMode: item["loginMode"], + }; +} + /** LoginMode enums */ -/** */ export type LoginMode = "batch" | "interactive"; /** @@ -1667,6 +2610,13 @@ export interface MetadataItem { value: string; } +export function metadataItemSerializer(item: MetadataItem): MetadataItemRest { + return { + name: item["name"], + value: item["value"], + }; +} + /** The file system to mount on each node. */ export interface MountConfiguration { /** The Azure Storage Container to mount using blob FUSE on each node. This property is mutually exclusive with all other properties. */ @@ -1679,6 +2629,27 @@ export interface MountConfiguration { azureFileShareConfiguration?: AzureFileShareConfiguration; } +export function mountConfigurationSerializer( + item: MountConfiguration, +): MountConfigurationRest { + return { + azureBlobFileSystemConfiguration: !item.azureBlobFileSystemConfiguration + ? item.azureBlobFileSystemConfiguration + : azureBlobFileSystemConfigurationSerializer( + item.azureBlobFileSystemConfiguration, + ), + nfsMountConfiguration: !item.nfsMountConfiguration + ? item.nfsMountConfiguration + : nfsMountConfigurationSerializer(item.nfsMountConfiguration), + cifsMountConfiguration: !item.cifsMountConfiguration + ? item.cifsMountConfiguration + : cifsMountConfigurationSerializer(item.cifsMountConfiguration), + azureFileShareConfiguration: !item.azureFileShareConfiguration + ? item.azureFileShareConfiguration + : azureFileShareConfigurationSerializer(item.azureFileShareConfiguration), + }; +} + /** Information used to connect to an Azure Storage Container using Blobfuse. */ export interface AzureBlobFileSystemConfiguration { /** The Azure Storage Account name. */ @@ -1697,6 +2668,22 @@ export interface AzureBlobFileSystemConfiguration { identityReference?: BatchNodeIdentityReference; } +export function azureBlobFileSystemConfigurationSerializer( + item: AzureBlobFileSystemConfiguration, +): AzureBlobFileSystemConfigurationRest { + return { + accountName: item["accountName"], + containerName: item["containerName"], + accountKey: item["accountKey"], + sasKey: item["sasKey"], + blobfuseOptions: item["blobfuseOptions"], + relativeMountPath: item["relativeMountPath"], + identityReference: !item.identityReference + ? item.identityReference + : batchNodeIdentityReferenceSerializer(item.identityReference), + }; +} + /** Information used to connect to an NFS file system. */ export interface NfsMountConfiguration { /** The URI of the file system to mount. */ @@ -1707,6 +2694,16 @@ export interface NfsMountConfiguration { mountOptions?: string; } +export function nfsMountConfigurationSerializer( + item: NfsMountConfiguration, +): NFSMountConfigurationRest { + return { + source: item["source"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + }; +} + /** Information used to connect to a CIFS file system. */ export interface CifsMountConfiguration { /** The user to use for authentication against the CIFS file system. */ @@ -1721,6 +2718,18 @@ export interface CifsMountConfiguration { password: string; } +export function cifsMountConfigurationSerializer( + item: CifsMountConfiguration, +): CifsMountConfigurationRest { + return { + username: item["username"], + source: item["source"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + password: item["password"], + }; +} + /** Information used to connect to an Azure Fileshare. */ export interface AzureFileShareConfiguration { /** The Azure Storage account name. */ @@ -1735,8 +2744,19 @@ export interface AzureFileShareConfiguration { mountOptions?: string; } +export function azureFileShareConfigurationSerializer( + item: AzureFileShareConfiguration, +): AzureFileShareConfigurationRest { + return { + accountName: item["accountName"], + azureFileUrl: item["azureFileUrl"], + accountKey: item["accountKey"], + relativeMountPath: item["relativeMountPath"], + mountOptions: item["mountOptions"], + }; +} + /** NodeCommunicationMode enums */ -/** */ export type NodeCommunicationMode = "default" | "classic" | "simplified"; /** @@ -1802,6 +2822,23 @@ export interface BatchJobScheduleUpdateOptions { metadata?: MetadataItem[]; } +export function batchJobScheduleUpdateOptionsSerializer( + item: BatchJobScheduleUpdateOptions, +): BatchJobScheduleUpdateOptionsRest { + return { + schedule: !item.schedule + ? item.schedule + : scheduleSerializer(item.schedule), + jobSpecification: !item.jobSpecification + ? item.jobSpecification + : jobSpecificationSerializer(item.jobSpecification), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** Options for creating an Azure Batch Job Schedule */ export interface BatchJobScheduleCreateOptions { /** A string that uniquely identifies the schedule within the Account. The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within an Account that differ only by case). */ @@ -1816,8 +2853,23 @@ export interface BatchJobScheduleCreateOptions { metadata?: MetadataItem[]; } +export function batchJobScheduleCreateOptionsSerializer( + item: BatchJobScheduleCreateOptions, +): BatchJobScheduleCreateOptionsRest { + return { + id: item["id"], + displayName: item["displayName"], + schedule: scheduleSerializer(item.schedule), + jobSpecification: jobSpecificationSerializer(item.jobSpecification), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** The result of listing the Job Schedules in an Account. */ -export interface BatchJobScheduleListResult { +export interface _BatchJobScheduleListResult { /** The list of Job Schedules. */ value?: BatchJobSchedule[]; /** The URL to get the next set of results. */ @@ -1855,8 +2907,19 @@ export interface BatchCertificate { password?: string; } +export function batchCertificateSerializer( + item: BatchCertificate, +): BatchCertificateRest { + return { + thumbprint: item["thumbprint"], + thumbprintAlgorithm: item["thumbprintAlgorithm"], + data: uint8ArrayToString(item["data"], "base64"), + certificateFormat: item["certificateFormat"], + password: item["password"], + }; +} + /** CertificateState enums */ -/** */ export type CertificateState = "active" | "deleting" | "deletefailed"; /** An error encountered by the Batch service when deleting a Certificate. */ @@ -1870,11 +2933,10 @@ export interface DeleteCertificateError { } /** CertificateFormat enums */ -/** */ export type CertificateFormat = "pfx" | "cer"; /** The result of listing the Certificates in the Account. */ -export interface CertificateListResult { +export interface _CertificateListResult { /** The list of Certificates. */ value?: BatchCertificate[]; /** The URL to get the next set of results. */ @@ -1937,8 +2999,24 @@ export interface BatchJob { readonly stats?: JobStatistics; } +export function batchJobSerializer(item: BatchJob): BatchJobRest { + return { + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + constraints: !item.constraints + ? item.constraints + : jobConstraintsSerializer(item.constraints), + poolInfo: poolInformationSerializer(item.poolInfo), + onAllTasksComplete: item["onAllTasksComplete"], + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** JobState enums */ -/** */ export type JobState = | "active" | "disabling" @@ -2024,14 +3102,42 @@ export interface BatchJobUpdateOptions { metadata?: MetadataItem[]; } +export function batchJobUpdateOptionsSerializer( + item: BatchJobUpdateOptions, +): BatchJobUpdateOptionsRest { + return { + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + constraints: !item.constraints + ? item.constraints + : jobConstraintsSerializer(item.constraints), + poolInfo: !item.poolInfo + ? item.poolInfo + : poolInformationSerializer(item.poolInfo), + onAllTasksComplete: item["onAllTasksComplete"], + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** Options for disabling an Azure Batch Job. */ export interface BatchJobDisableOptions { /** What to do with active Tasks associated with the Job. */ disableTasks: DisableJobOption; } +export function batchJobDisableOptionsSerializer( + item: BatchJobDisableOptions, +): BatchJobDisableOptionsRest { + return { + disableTasks: item["disableTasks"], + }; +} + /** DisableJobOption enums */ -/** */ export type DisableJobOption = "requeue" | "terminate" | "wait"; /** Options for terminating an Azure Batch Job. */ @@ -2040,6 +3146,14 @@ export interface BatchJobTerminateOptions { terminateReason?: string; } +export function batchJobTerminateOptionsSerializer( + item: BatchJobTerminateOptions, +): BatchJobTerminateOptionsRest { + return { + terminateReason: item["terminateReason"], + }; +} + /** Options for creating an Azure Batch Job. */ export interface BatchJobCreateOptions { /** A string that uniquely identifies the Job within the Account. The ID can contain any combination of alphanumeric characters including hyphens and underscores, and cannot contain more than 64 characters. The ID is case-preserving and case-insensitive (that is, you may not have two IDs within an Account that differ only by case). */ @@ -2076,8 +3190,47 @@ export interface BatchJobCreateOptions { metadata?: MetadataItem[]; } +export function batchJobCreateOptionsSerializer( + item: BatchJobCreateOptions, +): BatchJobCreateOptionsRest { + return { + id: item["id"], + displayName: item["displayName"], + usesTaskDependencies: item["usesTaskDependencies"], + priority: item["priority"], + allowTaskPreemption: item["allowTaskPreemption"], + maxParallelTasks: item["maxParallelTasks"], + constraints: !item.constraints + ? item.constraints + : jobConstraintsSerializer(item.constraints), + jobManagerTask: !item.jobManagerTask + ? item.jobManagerTask + : jobManagerTaskSerializer(item.jobManagerTask), + jobPreparationTask: !item.jobPreparationTask + ? item.jobPreparationTask + : jobPreparationTaskSerializer(item.jobPreparationTask), + jobReleaseTask: !item.jobReleaseTask + ? item.jobReleaseTask + : jobReleaseTaskSerializer(item.jobReleaseTask), + commonEnvironmentSettings: + item["commonEnvironmentSettings"] === undefined + ? item["commonEnvironmentSettings"] + : item["commonEnvironmentSettings"].map(environmentSettingSerializer), + poolInfo: poolInformationSerializer(item.poolInfo), + onAllTasksComplete: item["onAllTasksComplete"], + onTaskFailure: item["onTaskFailure"], + networkConfiguration: !item.networkConfiguration + ? item.networkConfiguration + : jobNetworkConfigurationSerializer(item.networkConfiguration), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + }; +} + /** The result of listing the Jobs in an Account. */ -export interface BatchJobListResult { +export interface _BatchJobListResult { /** The list of Jobs. */ value?: BatchJob[]; /** The URL to get the next set of results. */ @@ -2088,7 +3241,7 @@ export interface BatchJobListResult { * The result of listing the status of the Job Preparation and Job Release Tasks * for a Job. */ -export interface BatchJobListPreparationAndReleaseTaskStatusResult { +export interface _BatchJobListPreparationAndReleaseTaskStatusResult { /** A list of Job Preparation and Job Release Task execution information. */ value?: JobPreparationAndReleaseTaskExecutionInformation[]; /** The URL to get the next set of results. */ @@ -2139,7 +3292,6 @@ export interface JobPreparationTaskExecutionInformation { } /** JobPreparationTaskState enums */ -/** */ export type JobPreparationTaskState = "running" | "completed"; /** @@ -2168,7 +3320,6 @@ export interface JobReleaseTaskExecutionInformation { } /** JobReleaseTaskState enums */ -/** */ export type JobReleaseTaskState = "running" | "completed"; /** The Task and TaskSlot counts for a Job. */ @@ -2208,7 +3359,7 @@ export interface TaskSlotCounts { } /** The result of listing the supported Virtual Machine Images. */ -export interface AccountListSupportedImagesResult { +export interface _AccountListSupportedImagesResult { /** The list of supported Virtual Machine Images. */ value?: ImageInformation[]; /** The URL to get the next set of results. */ @@ -2235,14 +3386,12 @@ export interface ImageInformation { } /** OSType enums */ -/** */ export type OSType = "linux" | "windows"; /** VerificationType enums */ -/** */ export type VerificationType = "verified" | "unverified"; /** The result of listing the Compute Node counts in the Account. */ -export interface PoolNodeCountsListResult { +export interface _PoolNodeCountsListResult { /** A list of Compute Node counts by Pool. */ value?: PoolNodeCounts[]; /** The URL to get the next set of results. */ @@ -2292,7 +3441,7 @@ export interface NodeCounts { } /** The result of a listing the usage metrics for an Account. */ -export interface PoolListUsageMetricsResult { +export interface _PoolListUsageMetricsResult { /** The Pool usage metrics data. */ value?: PoolUsageMetrics[]; /** The URL to get the next set of results. */ @@ -2368,8 +3517,65 @@ export interface BatchPoolCreateOptions { targetNodeCommunicationMode?: NodeCommunicationMode; } +export function batchPoolCreateOptionsSerializer( + item: BatchPoolCreateOptions, +): BatchPoolCreateOptionsRest { + return { + id: item["id"], + displayName: item["displayName"], + vmSize: item["vmSize"], + cloudServiceConfiguration: !item.cloudServiceConfiguration + ? item.cloudServiceConfiguration + : cloudServiceConfigurationSerializer(item.cloudServiceConfiguration), + virtualMachineConfiguration: !item.virtualMachineConfiguration + ? item.virtualMachineConfiguration + : virtualMachineConfigurationSerializer(item.virtualMachineConfiguration), + resizeTimeout: item["resizeTimeout"], + targetDedicatedNodes: item["targetDedicatedNodes"], + targetLowPriorityNodes: item["targetLowPriorityNodes"], + enableAutoScale: item["enableAutoScale"], + autoScaleFormula: item["autoScaleFormula"], + autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], + enableInterNodeCommunication: item["enableInterNodeCommunication"], + networkConfiguration: !item.networkConfiguration + ? item.networkConfiguration + : networkConfigurationSerializer(item.networkConfiguration), + startTask: !item.startTask + ? item.startTask + : startTaskSerializer(item.startTask), + certificateReferences: + item["certificateReferences"] === undefined + ? item["certificateReferences"] + : item["certificateReferences"].map(certificateReferenceSerializer), + applicationPackageReferences: + item["applicationPackageReferences"] === undefined + ? item["applicationPackageReferences"] + : item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + applicationLicenses: item["applicationLicenses"], + taskSlotsPerNode: item["taskSlotsPerNode"], + taskSchedulingPolicy: !item.taskSchedulingPolicy + ? item.taskSchedulingPolicy + : taskSchedulingPolicySerializer(item.taskSchedulingPolicy), + userAccounts: + item["userAccounts"] === undefined + ? item["userAccounts"] + : item["userAccounts"].map(userAccountSerializer), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + mountConfiguration: + item["mountConfiguration"] === undefined + ? item["mountConfiguration"] + : item["mountConfiguration"].map(mountConfigurationSerializer), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + }; +} + /** The result of listing the Pools in an Account. */ -export interface BatchPoolListResult { +export interface _BatchPoolListResult { /** The list of Pools. */ value?: BatchPool[]; /** The URL to get the next set of results. */ @@ -2462,10 +3668,8 @@ export interface BatchPool { } /** PoolState enums */ -/** */ export type PoolState = "active" | "deleting"; /** AllocationState enums */ -/** */ export type AllocationState = "steady" | "resizing" | "stopping"; /** An error that occurred when resizing a Pool. */ @@ -2561,7 +3765,6 @@ export interface BatchPoolIdentity { } /** PoolIdentityType enums */ -/** */ export type PoolIdentityType = "UserAssigned" | "None"; /** The user assigned Identity */ @@ -2595,6 +3798,31 @@ export interface BatchPoolUpdateOptions { targetNodeCommunicationMode?: NodeCommunicationMode; } +export function batchPoolUpdateOptionsSerializer( + item: BatchPoolUpdateOptions, +): BatchPoolUpdateOptionsRest { + return { + startTask: !item.startTask + ? item.startTask + : startTaskSerializer(item.startTask), + certificateReferences: + item["certificateReferences"] === undefined + ? item["certificateReferences"] + : item["certificateReferences"].map(certificateReferenceSerializer), + applicationPackageReferences: + item["applicationPackageReferences"] === undefined + ? item["applicationPackageReferences"] + : item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + metadata: + item["metadata"] === undefined + ? item["metadata"] + : item["metadata"].map(metadataItemSerializer), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + }; +} + /** Options for enabling automatic scaling on an Azure Batch Pool. */ export interface BatchPoolEnableAutoScaleOptions { /** The formula for the desired number of Compute Nodes in the Pool. The formula is checked for validity before it is applied to the Pool. If the formula is not valid, the Batch service rejects the request with detailed error information. For more information about specifying this formula, see Automatically scale Compute Nodes in an Azure Batch Pool (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling). */ @@ -2603,12 +3831,29 @@ export interface BatchPoolEnableAutoScaleOptions { autoScaleEvaluationInterval?: string; } +export function batchPoolEnableAutoScaleOptionsSerializer( + item: BatchPoolEnableAutoScaleOptions, +): BatchPoolEnableAutoScaleOptionsRest { + return { + autoScaleFormula: item["autoScaleFormula"], + autoScaleEvaluationInterval: item["autoScaleEvaluationInterval"], + }; +} + /** Options for evaluating an automatic scaling formula on an Azure Batch Pool. */ export interface BatchPoolEvaluateAutoScaleOptions { /** The formula for the desired number of Compute Nodes in the Pool. The formula is validated and its results calculated, but it is not applied to the Pool. To apply the formula to the Pool, 'Enable automatic scaling on a Pool'. For more information about specifying this formula, see Automatically scale Compute Nodes in an Azure Batch Pool (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling). */ autoScaleFormula: string; } +export function batchPoolEvaluateAutoScaleOptionsSerializer( + item: BatchPoolEvaluateAutoScaleOptions, +): BatchPoolEvaluateAutoScaleOptionsRest { + return { + autoScaleFormula: item["autoScaleFormula"], + }; +} + /** Options for changing the size of an Azure Batch Pool. */ export interface BatchPoolResizeOptions { /** The desired number of dedicated Compute Nodes in the Pool. */ @@ -2621,8 +3866,18 @@ export interface BatchPoolResizeOptions { nodeDeallocationOption?: BatchNodeDeallocationOption; } +export function batchPoolResizeOptionsSerializer( + item: BatchPoolResizeOptions, +): BatchPoolResizeOptionsRest { + return { + targetDedicatedNodes: item["targetDedicatedNodes"], + targetLowPriorityNodes: item["targetLowPriorityNodes"], + resizeTimeout: item["resizeTimeout"], + nodeDeallocationOption: item["nodeDeallocationOption"], + }; +} + /** BatchNodeDeallocationOption enums */ -/** */ export type BatchNodeDeallocationOption = | "requeue" | "terminate" @@ -2650,6 +3905,24 @@ export interface BatchPoolReplaceOptions { targetNodeCommunicationMode?: NodeCommunicationMode; } +export function batchPoolReplaceOptionsSerializer( + item: BatchPoolReplaceOptions, +): BatchPoolReplaceOptionsRest { + return { + startTask: !item.startTask + ? item.startTask + : startTaskSerializer(item.startTask), + certificateReferences: item["certificateReferences"].map( + certificateReferenceSerializer, + ), + applicationPackageReferences: item["applicationPackageReferences"].map( + applicationPackageReferenceSerializer, + ), + metadata: item["metadata"].map(metadataItemSerializer), + targetNodeCommunicationMode: item["targetNodeCommunicationMode"], + }; +} + /** Options for removing nodes from an Azure Batch Pool. */ export interface NodeRemoveOptions { /** A list containing the IDs of the Compute Nodes to be removed from the specified Pool. A maximum of 100 nodes may be removed per request. */ @@ -2660,8 +3933,18 @@ export interface NodeRemoveOptions { nodeDeallocationOption?: BatchNodeDeallocationOption; } +export function nodeRemoveOptionsSerializer( + item: NodeRemoveOptions, +): NodeRemoveOptionsRest { + return { + nodeList: item["nodeList"], + resizeTimeout: item["resizeTimeout"], + nodeDeallocationOption: item["nodeDeallocationOption"], + }; +} + /** The result of listing the applications available in an Account. */ -export interface ApplicationListResult { +export interface _ApplicationListResult { /** The list of applications available in the Account. */ value?: BatchApplication[]; /** The URL to get the next set of results. */ @@ -2679,5 +3962,4 @@ export interface BatchApplication { } /** The Azure Batch service version. */ -/** */ export type Versions = "2023-05-01.17.0"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts index c471a986d2..37f215a247 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/options.ts @@ -3,6 +3,7 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface ListApplicationsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -18,6 +19,7 @@ export interface ListApplicationsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface GetApplicationOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -28,6 +30,7 @@ export interface GetApplicationOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -60,6 +63,7 @@ export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { $filter?: string; } +/** Optional parameters. */ export interface CreatePoolOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -72,6 +76,7 @@ export interface CreatePoolOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListPoolsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -96,6 +101,7 @@ export interface ListPoolsOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface DeletePoolOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -130,6 +136,7 @@ export interface DeletePoolOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface PoolExistsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -164,6 +171,7 @@ export interface PoolExistsOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface GetPoolOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -202,6 +210,7 @@ export interface GetPoolOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface UpdatePoolOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -238,6 +247,7 @@ export interface UpdatePoolOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -248,6 +258,7 @@ export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -284,6 +295,7 @@ export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -296,6 +308,7 @@ export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ResizePoolOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -332,6 +345,7 @@ export interface ResizePoolOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface StopPoolResizeOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -366,6 +380,7 @@ export interface StopPoolResizeOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -378,6 +393,7 @@ export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface RemoveNodesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -414,6 +430,7 @@ export interface RemoveNodesOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListSupportedImagesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 @@ -432,6 +449,7 @@ export interface ListSupportedImagesOptionalParams extends OperationOptions { $filter?: string; } +/** Optional parameters. */ export interface ListPoolNodeCountsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -452,6 +470,7 @@ export interface ListPoolNodeCountsOptionalParams extends OperationOptions { $filter?: string; } +/** Optional parameters. */ export interface DeleteJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -486,6 +505,7 @@ export interface DeleteJobOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface GetJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -524,6 +544,7 @@ export interface GetJobOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface UpdateJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -560,6 +581,7 @@ export interface UpdateJobOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ReplaceJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -596,6 +618,7 @@ export interface ReplaceJobOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DisableJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -632,6 +655,7 @@ export interface DisableJobOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface EnableJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -666,6 +690,7 @@ export interface EnableJobOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface TerminateJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -702,6 +727,7 @@ export interface TerminateJobOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface CreateJobOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -714,6 +740,7 @@ export interface CreateJobOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListJobsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -738,6 +765,7 @@ export interface ListJobsOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface ListJobsFromScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -762,6 +790,7 @@ export interface ListJobsFromScheduleOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface ListJobPreparationAndReleaseTaskStatusOptionalParams extends OperationOptions { /** @@ -783,6 +812,7 @@ export interface ListJobPreparationAndReleaseTaskStatusOptionalParams $select?: string[]; } +/** Optional parameters. */ export interface GetJobTaskCountsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -793,6 +823,7 @@ export interface GetJobTaskCountsOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface CreateCertificateOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -805,6 +836,7 @@ export interface CreateCertificateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListCertificatesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -827,6 +859,7 @@ export interface ListCertificatesOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface CancelCertificateDeletionOptionalParams extends OperationOptions { /** The API version to use for this operation. */ @@ -838,6 +871,7 @@ export interface CancelCertificateDeletionOptionalParams timeOutInSeconds?: number; } +/** Optional parameters. */ export interface DeleteCertificateOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -848,6 +882,7 @@ export interface DeleteCertificateOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface GetCertificateOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -860,6 +895,7 @@ export interface GetCertificateOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface JobScheduleExistsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -894,6 +930,7 @@ export interface JobScheduleExistsOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface DeleteJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -928,6 +965,7 @@ export interface DeleteJobScheduleOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface GetJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -966,6 +1004,7 @@ export interface GetJobScheduleOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface UpdateJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1002,6 +1041,7 @@ export interface UpdateJobScheduleOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ReplaceJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1038,6 +1078,7 @@ export interface ReplaceJobScheduleOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DisableJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1072,6 +1113,7 @@ export interface DisableJobScheduleOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface EnableJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1106,6 +1148,7 @@ export interface EnableJobScheduleOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface TerminateJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1140,6 +1183,7 @@ export interface TerminateJobScheduleOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface CreateJobScheduleOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1152,6 +1196,7 @@ export interface CreateJobScheduleOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListJobSchedulesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1176,6 +1221,7 @@ export interface ListJobSchedulesOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface CreateTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1188,6 +1234,7 @@ export interface CreateTaskOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListTasksOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1212,6 +1259,7 @@ export interface ListTasksOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface CreateTaskCollectionOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1224,6 +1272,7 @@ export interface CreateTaskCollectionOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DeleteTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1258,6 +1307,7 @@ export interface DeleteTaskOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface GetTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1296,6 +1346,7 @@ export interface GetTaskOptionalParams extends OperationOptions { $expand?: string[]; } +/** Optional parameters. */ export interface ReplaceTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1332,6 +1383,7 @@ export interface ReplaceTaskOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListSubTasksOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1344,6 +1396,7 @@ export interface ListSubTasksOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface TerminateTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1378,6 +1431,7 @@ export interface TerminateTaskOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface ReactivateTaskOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1412,6 +1466,7 @@ export interface ReactivateTaskOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface DeleteTaskFileOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1429,6 +1484,7 @@ export interface DeleteTaskFileOptionalParams extends OperationOptions { recursive?: boolean; } +/** Optional parameters. */ export interface GetTaskFileOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1456,6 +1512,7 @@ export interface GetTaskFileOptionalParams extends OperationOptions { ocpRange?: string; } +/** Optional parameters. */ export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1478,6 +1535,7 @@ export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface ListTaskFilesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1503,6 +1561,7 @@ export interface ListTaskFilesOptionalParams extends OperationOptions { recursive?: boolean; } +/** Optional parameters. */ export interface CreateNodeUserOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1515,6 +1574,7 @@ export interface CreateNodeUserOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DeleteNodeUserOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1525,6 +1585,7 @@ export interface DeleteNodeUserOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface ReplaceNodeUserOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1537,6 +1598,7 @@ export interface ReplaceNodeUserOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface GetNodeOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1549,6 +1611,7 @@ export interface GetNodeOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface RebootNodeOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1561,6 +1624,7 @@ export interface RebootNodeOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ReimageNodeOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1573,6 +1637,7 @@ export interface ReimageNodeOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface DisableNodeSchedulingOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1585,6 +1650,7 @@ export interface DisableNodeSchedulingOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface EnableNodeSchedulingOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1595,6 +1661,7 @@ export interface EnableNodeSchedulingOptionalParams extends OperationOptions { timeOutInSeconds?: number; } +/** Optional parameters. */ export interface GetNodeRemoteLoginSettingsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ @@ -1606,6 +1673,7 @@ export interface GetNodeRemoteLoginSettingsOptionalParams timeOutInSeconds?: number; } +/** Optional parameters. */ export interface GetNodeRemoteDesktopFileOptionalParams extends OperationOptions { /** The API version to use for this operation. */ @@ -1617,6 +1685,7 @@ export interface GetNodeRemoteDesktopFileOptionalParams timeOutInSeconds?: number; } +/** Optional parameters. */ export interface UploadNodeLogsOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1629,6 +1698,7 @@ export interface UploadNodeLogsOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ListNodesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1651,6 +1721,7 @@ export interface ListNodesOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface GetNodeExtensionOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1663,6 +1734,7 @@ export interface GetNodeExtensionOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface ListNodeExtensionsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 @@ -1678,6 +1750,7 @@ export interface ListNodeExtensionsOptionalParams extends OperationOptions { $select?: string[]; } +/** Optional parameters. */ export interface DeleteNodeFileOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1695,6 +1768,7 @@ export interface DeleteNodeFileOptionalParams extends OperationOptions { recursive?: boolean; } +/** Optional parameters. */ export interface GetNodeFileOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1722,6 +1796,7 @@ export interface GetNodeFileOptionalParams extends OperationOptions { ocpRange?: string; } +/** Optional parameters. */ export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -1744,6 +1819,7 @@ export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { ifUnmodifiedSince?: Date; } +/** Optional parameters. */ export interface ListNodeFilesOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/batchClient.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/batchClient.ts index 6059823f69..6cf2f8d15d 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/batchClient.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/batchClient.ts @@ -6,6 +6,9 @@ import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; import { BatchContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface BatchContextOptions extends ClientOptions {} + /** * Initialize a new instance of `BatchContext` * @param endpointParam - Batch account endpoint (for example: https://batchaccount.eastus2.batch.azure.com). @@ -15,10 +18,9 @@ import { BatchContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential, - options: ClientOptions = {}, + options: BatchContextOptions = {}, ): BatchContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-batch-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -43,7 +45,6 @@ export default function createClient( ], }, }; - const client = getClient(endpointUrl, credentials, options) as BatchContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/responses.ts index be7a5c5a64..9b1f085f8b 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/rest/responses.ts @@ -1320,6 +1320,8 @@ export interface GetTaskFile200Headers { "ocp-batch-file-mode": string; /** The length of the file. */ "content-length": number; + /** Type of content */ + "content-type": "application/octet-stream"; } /** The request has succeeded. */ diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/package.json index dd0fd68dc2..68c3c52dbb 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/package.json @@ -42,7 +42,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md index 8b4a445fc4..a3341cf231 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/review/ai-chat-protocol.api.md @@ -10,7 +10,7 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public (undocumented) +// @public export type APIVersion = "2023-10-01-preview"; // @public @@ -62,11 +62,11 @@ export class ChatProtocolClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface ChatProtocolClientOptions extends ClientOptions { } -// @public (undocumented) +// @public export type ChatRole = "user" | "system" | "assistant"; // @public @@ -78,15 +78,15 @@ export interface ChoiceDeltaRecord { sessionState?: any; } -// @public (undocumented) +// @public export interface CreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface CreateStreamingOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export type FinishReason = "stop" | "length"; // @public diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts index 9157a96755..17df948c88 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { ChatProtocolContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface ChatProtocolClientOptions extends ClientOptions {} export { ChatProtocolContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts index 785cc0aab4..98d35499b4 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts @@ -2,6 +2,7 @@ // Licensed under the MIT license. import { + chatMessageSerializer, StreamingChatCompletionOptionsRecord, ChatCompletionChunkRecord, ChatCompletionOptionsRecord, @@ -17,6 +18,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../helpers/serializerHelpers.js"; import { CreateStreamingOptionalParams, CreateOptionalParams, @@ -32,14 +34,12 @@ export function _createStreamingSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: body["messages"].map((p) => ({ - content: p["content"], - role: p["role"], - session_state: p["sessionState"], - })), + messages: body["messages"].map(chatMessageSerializer), stream: body["stream"], session_state: body["sessionState"], - context: body["context"], + context: !body.context + ? body.context + : (serializeRecord(body.context as any) as any), }, }) as StreamableMethod; } @@ -86,14 +86,12 @@ export function _createSend( .post({ ...operationOptionsToRequestParameters(options), body: { - messages: body["messages"].map((p) => ({ - content: p["content"], - role: p["role"], - session_state: p["sessionState"], - })), + messages: body["messages"].map(chatMessageSerializer), stream: body["stream"], session_state: body["sessionState"], - context: body["context"], + context: !body.context + ? body.context + : (serializeRecord(body.context as any) as any), }, }) as StreamableMethod; } diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts index 4c251689c5..ebc500ee64 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,13 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { + ChatMessage as ChatMessageRest, + StreamingChatCompletionOptions as StreamingChatCompletionOptionsRest, + ChatCompletionOptions as ChatCompletionOptionsRest, +} from "../rest/index.js"; + /** A single, role-attributed message within a chat completion interaction. */ export interface ChatMessage { /** The text associated with the message. */ @@ -16,8 +23,15 @@ export interface ChatMessage { sessionState?: any; } +export function chatMessageSerializer(item: ChatMessage): ChatMessageRest { + return { + content: item["content"], + role: item["role"], + session_state: item["sessionState"], + }; +} + /** A representation of the intended purpose of a message. */ -/** */ export type ChatRole = "user" | "system" | "assistant"; /** The configuration for a streaming chat completion request. */ @@ -40,6 +54,19 @@ export interface StreamingChatCompletionOptionsRecord { context?: Record; } +export function streamingChatCompletionOptionsRecordSerializer( + item: StreamingChatCompletionOptionsRecord, +): StreamingChatCompletionOptionsRest { + return { + messages: item["messages"].map(chatMessageSerializer), + stream: item["stream"], + session_state: item["sessionState"], + context: !item.context + ? item.context + : (serializeRecord(item.context as any) as any), + }; +} + /** A single response to a streaming completion request. */ export interface ChatCompletionChunkRecord { /** The collection of choice deltas received in this chunk. */ @@ -84,7 +111,6 @@ export interface ChatMessageDelta { } /** Representation of the reason why a chat session has finished processing. */ -/** */ export type FinishReason = "stop" | "length"; /** The configuration for a chat completion request. */ @@ -107,6 +133,19 @@ export interface ChatCompletionOptionsRecord { context?: Record; } +export function chatCompletionOptionsRecordSerializer( + item: ChatCompletionOptionsRecord, +): ChatCompletionOptionsRest { + return { + messages: item["messages"].map(chatMessageSerializer), + stream: item["stream"], + session_state: item["sessionState"], + context: !item.context + ? item.context + : (serializeRecord(item.context as any) as any), + }; +} + /** Representation of the response to a chat completion request. */ export interface ChatCompletionRecord { /** The collection of generated completions. */ @@ -135,5 +174,5 @@ export interface ChatChoiceRecord { finishReason: FinishReason; } -/** */ +/** Type of APIVersion */ export type APIVersion = "2023-10-01-preview"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts index 63ed4490cd..13c95204e1 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/models/options.ts @@ -3,6 +3,8 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface CreateStreamingOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface CreateOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/rest/chatProtocolClient.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/rest/chatProtocolClient.ts index 868e8649d5..839299230f 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/rest/chatProtocolClient.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/rest/chatProtocolClient.ts @@ -6,6 +6,9 @@ import { logger } from "../logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { ChatProtocolContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface ChatProtocolContextOptions extends ClientOptions {} + /** * Initialize a new instance of `ChatProtocolContext` * @param endpointParam - A sequence of textual characters. @@ -15,10 +18,9 @@ import { ChatProtocolContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {}, + options: ChatProtocolContextOptions = {}, ): ChatProtocolContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-ai-chat-protocol-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -37,7 +39,6 @@ export default function createClient( apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "api-key", }, }; - const client = getClient( endpointUrl, credentials, diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/package.json b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/package.json index 644ea3f70f..c540ac2df8 100644 --- a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/package.json @@ -40,7 +40,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", diff --git a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/review/confidential-ledger.api.md b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/review/confidential-ledger.api.md index e1c3e263e5..732a49ce1f 100644 --- a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/review/confidential-ledger.api.md +++ b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/review/confidential-ledger.api.md @@ -26,7 +26,12 @@ export type ConfidentialLedgerClient = Client & { }; // @public -function createClient(ledgerUri: string, credentials: TokenCredential, options?: ClientOptions): ConfidentialLedgerClient; +export interface ConfidentialLedgerClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +function createClient(ledgerUri: string, credentials: TokenCredential, { apiVersion, ...options }?: ConfidentialLedgerClientOptions): ConfidentialLedgerClient; export default createClient; // @public (undocumented) diff --git a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/src/confidentialLedgerClient.ts b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/src/confidentialLedgerClient.ts index 064a71ccd5..689973bac9 100644 --- a/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/src/confidentialLedgerClient.ts +++ b/packages/typespec-test/test/confidentialLedger/generated/typespec-ts/src/confidentialLedgerClient.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { TokenCredential } from "@azure/core-auth"; import { ConfidentialLedgerClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface ConfidentialLedgerClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `ConfidentialLedgerClient` * @param ledgerUri - Represent a URL string as described by https://url.spec.whatwg.org/ @@ -15,10 +21,12 @@ import { ConfidentialLedgerClient } from "./clientDefinitions.js"; export default function createClient( ledgerUri: string, credentials: TokenCredential, - options: ClientOptions = {}, + { + apiVersion = "2022-05-13", + ...options + }: ConfidentialLedgerClientOptions = {}, ): ConfidentialLedgerClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${ledgerUri}`; - options.apiVersion = options.apiVersion ?? "2022-05-13"; const userAgentInfo = `azsdk-js-confidential-ledger-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -38,12 +46,28 @@ export default function createClient( ], }, }; - const client = getClient( endpointUrl, credentials, options, ) as ConfidentialLedgerClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/package.json index c1a3cc4596..2462478b06 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/package.json @@ -42,7 +42,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md index 11c561cf57..2fb44144a9 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md @@ -10,7 +10,7 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public (undocumented) +// @public export interface AddOrUpdateBlockItemsOptionalParams extends OperationOptions { } @@ -24,7 +24,7 @@ export interface AddOrUpdateBlockItemsResult { value?: TextBlockItem[]; } -// @public (undocumented) +// @public export interface AnalyzeImageOptionalParams extends OperationOptions { } @@ -35,7 +35,7 @@ export interface AnalyzeImageOptions { outputType?: AnalyzeImageOutputType; } -// @public (undocumented) +// @public export type AnalyzeImageOutputType = "FourLevels"; // @public @@ -43,7 +43,7 @@ export interface AnalyzeImageResult { analyzeResults: ImageAnalyzeSeverityResult[]; } -// @public (undocumented) +// @public export interface AnalyzeTextOptionalParams extends OperationOptions { } @@ -56,7 +56,7 @@ export interface AnalyzeTextOptions { text: string; } -// @public (undocumented) +// @public export type AnalyzeTextOutputType = "FourLevels" | "EightLevels"; // @public @@ -81,7 +81,7 @@ export class ContentSafetyClient { removeBlockItems(blocklistName: string, body: RemoveBlockItemsOptions, options?: RemoveBlockItemsOptionalParams): Promise; } -// @public (undocumented) +// @public export interface ContentSafetyClientOptions extends ClientOptions { apiVersion?: string; } @@ -91,20 +91,20 @@ export type ContinuablePage = TPage & { continuationToken?: string; }; -// @public (undocumented) +// @public export interface CreateOrUpdateTextBlocklistOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface DeleteTextBlocklistOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTextBlocklistItemOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTextBlocklistOptionalParams extends OperationOptions { } @@ -114,7 +114,7 @@ export interface ImageAnalyzeSeverityResult { severity?: number; } -// @public (undocumented) +// @public export type ImageCategory = "Hate" | "SelfHarm" | "Sexual" | "Violence"; // @public @@ -123,14 +123,14 @@ export interface ImageData { content?: Uint8Array; } -// @public (undocumented) +// @public export interface ListTextBlocklistItemsOptionalParams extends OperationOptions { maxpagesize?: number; skip?: number; top?: number; } -// @public (undocumented) +// @public export interface ListTextBlocklistsOptionalParams extends OperationOptions { } @@ -141,24 +141,12 @@ export interface PagedAsyncIterableIterator>; } -// @public -export interface PagedTextBlockItem { - nextLink?: string; - value: TextBlockItem[]; -} - -// @public -export interface PagedTextBlocklist { - nextLink?: string; - value: TextBlocklist[]; -} - // @public export interface PageSettings { continuationToken?: string; } -// @public (undocumented) +// @public export interface RemoveBlockItemsOptionalParams extends OperationOptions { } @@ -199,10 +187,10 @@ export interface TextBlocklistMatchResult { blocklistName: string; } -// @public (undocumented) +// @public export type TextCategory = "Hate" | "SelfHarm" | "Sexual" | "Violence"; -// @public (undocumented) +// @public export type Versions = "2023-10-01"; // (No @packageDocumentation comment for this package) diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts index 7261424d73..d2e8fe6e75 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { ContentSafetyContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface ContentSafetyClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts index fb67b425f7..7af4f0e629 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts @@ -2,6 +2,8 @@ // Licensed under the MIT license. import { + textBlockItemInfoSerializer, + imageDataSerializer, TextBlocklist, AddOrUpdateBlockItemsOptions, AddOrUpdateBlockItemsResult, @@ -11,8 +13,8 @@ import { AnalyzeImageResult, AnalyzeTextOptions, AnalyzeTextResult, - PagedTextBlocklist, - PagedTextBlockItem, + _PagedTextBlockItem, + _PagedTextBlocklist, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; @@ -46,7 +48,6 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; -import { uint8ArrayToString } from "@azure/core-util"; import { AnalyzeTextOptionalParams, AnalyzeImageOptionalParams, @@ -122,13 +123,7 @@ export function _analyzeImageSend( .post({ ...operationOptionsToRequestParameters(options), body: { - image: { - content: - body.image["content"] !== undefined - ? uint8ArrayToString(body.image["content"], "base64") - : undefined, - blobUrl: body.image["blobUrl"], - }, + image: imageDataSerializer(body.image), categories: body["categories"], outputType: body["outputType"], }, @@ -299,7 +294,7 @@ export function _listTextBlocklistsSend( export async function _listTextBlocklistsDeserialize( result: ListTextBlocklists200Response | ListTextBlocklistsDefaultResponse, -): Promise { +): Promise<_PagedTextBlocklist> { if (isUnexpected(result)) { throw createRestError(result); } @@ -341,12 +336,7 @@ export function _addOrUpdateBlockItemsSend( ) .post({ ...operationOptionsToRequestParameters(options), - body: { - blockItems: body["blockItems"].map((p) => ({ - description: p["description"], - text: p["text"], - })), - }, + body: { blockItems: body["blockItems"].map(textBlockItemInfoSerializer) }, }); } @@ -499,7 +489,7 @@ export async function _listTextBlocklistItemsDeserialize( result: | ListTextBlocklistItems200Response | ListTextBlocklistItemsDefaultResponse, -): Promise { +): Promise<_PagedTextBlockItem> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts index 12f7881e11..186bf188f1 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts @@ -25,8 +25,6 @@ export { TextBlocklistMatchResult, TextAnalyzeSeverityResult, Versions, - PagedTextBlocklist, - PagedTextBlockItem, AnalyzeTextOptionalParams, AnalyzeImageOptionalParams, GetTextBlocklistOptionalParams, diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts index 1d92d7b9e5..8cfa6172b0 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts @@ -21,8 +21,6 @@ export { TextBlocklistMatchResult, TextAnalyzeSeverityResult, Versions, - PagedTextBlocklist, - PagedTextBlockItem, } from "./models.js"; export { AnalyzeTextOptionalParams, diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts index f5202c4eb1..6faf4dba5e 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { uint8ArrayToString } from "@azure/core-util"; +import { + TextBlocklist as TextBlocklistRest, + TextBlockItemInfo as TextBlockItemInfoRest, + AddOrUpdateBlockItemsOptions as AddOrUpdateBlockItemsOptionsRest, + RemoveBlockItemsOptions as RemoveBlockItemsOptionsRest, + AnalyzeImageOptions as AnalyzeImageOptionsRest, + ImageData as ImageDataRest, + AnalyzeTextOptions as AnalyzeTextOptionsRest, +} from "../rest/index.js"; + /** Text Blocklist. */ export interface TextBlocklist { /** Text blocklist name. */ @@ -9,6 +20,15 @@ export interface TextBlocklist { description?: string; } +export function textBlocklistSerializer( + item: TextBlocklist, +): TextBlocklistRest { + return { + blocklistName: item["blocklistName"], + description: item["description"], + }; +} + /** Block item info in text blocklist. */ export interface TextBlockItemInfo { /** Block item description. */ @@ -17,12 +37,29 @@ export interface TextBlockItemInfo { text: string; } +export function textBlockItemInfoSerializer( + item: TextBlockItemInfo, +): TextBlockItemInfoRest { + return { + description: item["description"], + text: item["text"], + }; +} + /** The request of adding blockItems to text blocklist. */ export interface AddOrUpdateBlockItemsOptions { /** Array of blockItemInfo to add. */ blockItems: TextBlockItemInfo[]; } +export function addOrUpdateBlockItemsOptionsSerializer( + item: AddOrUpdateBlockItemsOptions, +): AddOrUpdateBlockItemsOptionsRest { + return { + blockItems: item["blockItems"].map(textBlockItemInfoSerializer), + }; +} + /** The response of adding blockItems to text blocklist. */ export interface AddOrUpdateBlockItemsResult { /** Array of blockItems added. */ @@ -45,6 +82,14 @@ export interface RemoveBlockItemsOptions { blockItemIds: string[]; } +export function removeBlockItemsOptionsSerializer( + item: RemoveBlockItemsOptions, +): RemoveBlockItemsOptionsRest { + return { + blockItemIds: item["blockItemIds"], + }; +} + /** The analysis request of the image. */ export interface AnalyzeImageOptions { /** The image needs to be analyzed. */ @@ -55,6 +100,16 @@ export interface AnalyzeImageOptions { outputType?: AnalyzeImageOutputType; } +export function analyzeImageOptionsSerializer( + item: AnalyzeImageOptions, +): AnalyzeImageOptionsRest { + return { + image: imageDataSerializer(item.image), + categories: item["categories"], + outputType: item["outputType"], + }; +} + /** The content or blob url of image, could be base64 encoding bytes or blob url. You can choose only one of them. If both are given, the request will be refused. The maximum size of image is 2048 pixels * 2048 pixels, no larger than 4MB at the same time. The minimum size of image is 50 pixels * 50 pixels. */ export interface ImageData { /** Base64 encoding of image. */ @@ -63,11 +118,19 @@ export interface ImageData { blobUrl?: string; } +export function imageDataSerializer(item: ImageData): ImageDataRest { + return { + content: + item["content"] !== undefined + ? uint8ArrayToString(item["content"], "base64") + : undefined, + blobUrl: item["blobUrl"], + }; +} + /** Image analyze category */ -/** */ export type ImageCategory = "Hate" | "SelfHarm" | "Sexual" | "Violence"; /** The type of image analysis output. */ -/** */ export type AnalyzeImageOutputType = "FourLevels"; /** The analysis response of the image. */ @@ -98,11 +161,21 @@ export interface AnalyzeTextOptions { outputType?: AnalyzeTextOutputType; } +export function analyzeTextOptionsSerializer( + item: AnalyzeTextOptions, +): AnalyzeTextOptionsRest { + return { + text: item["text"], + categories: item["categories"], + blocklistNames: item["blocklistNames"], + breakByBlocklists: item["breakByBlocklists"], + outputType: item["outputType"], + }; +} + /** Text analyze category */ -/** */ export type TextCategory = "Hate" | "SelfHarm" | "Sexual" | "Violence"; /** The type of text analysis output. */ -/** */ export type AnalyzeTextOutputType = "FourLevels" | "EightLevels"; /** The analysis response of the text */ @@ -131,11 +204,11 @@ export interface TextAnalyzeSeverityResult { severity?: number; } -/** */ +/** Type of Versions */ export type Versions = "2023-10-01"; /** Paged collection of TextBlocklist items */ -export interface PagedTextBlocklist { +export interface _PagedTextBlocklist { /** The TextBlocklist items on this page */ value: TextBlocklist[]; /** The link to the next page of items */ @@ -143,7 +216,7 @@ export interface PagedTextBlocklist { } /** Paged collection of TextBlockItem items */ -export interface PagedTextBlockItem { +export interface _PagedTextBlockItem { /** The TextBlockItem items on this page */ value: TextBlockItem[]; /** The link to the next page of items */ diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts index 5dd4631db2..cff3931a7f 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/options.ts @@ -3,28 +3,38 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface AnalyzeTextOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface AnalyzeImageOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTextBlocklistOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface CreateOrUpdateTextBlocklistOptionalParams extends OperationOptions { /** This request has a JSON Merge Patch body. */ contentType?: string; } +/** Optional parameters. */ export interface DeleteTextBlocklistOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListTextBlocklistsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface AddOrUpdateBlockItemsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface RemoveBlockItemsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTextBlocklistItemOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListTextBlocklistItemsOptionalParams extends OperationOptions { /** The number of result items to return. */ top?: number; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/rest/contentSafetyClient.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/rest/contentSafetyClient.ts index 92d2943486..c3d6bb1bb8 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/rest/contentSafetyClient.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/rest/contentSafetyClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { ContentSafetyContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface ContentSafetyContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `ContentSafetyContext` * @param endpointParam - Supported Cognitive Services endpoints (protocol and hostname, for example: @@ -16,11 +22,10 @@ import { ContentSafetyContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {}, + { apiVersion = "2023-10-01", ...options }: ContentSafetyContextOptions = {}, ): ContentSafetyContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/contentsafety`; - options.apiVersion = options.apiVersion ?? "2023-10-01"; const userAgentInfo = `azsdk-js-ai-content-safety-rest/1.0.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -42,12 +47,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as ContentSafetyContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/contoso/generated/openapi/2022-11-01-preview/openapi.json b/packages/typespec-test/test/contoso/generated/openapi/2022-11-01-preview/openapi.json index 3011bb835d..ead6aac2e2 100644 --- a/packages/typespec-test/test/contoso/generated/openapi/2022-11-01-preview/openapi.json +++ b/packages/typespec-test/test/contoso/generated/openapi/2022-11-01-preview/openapi.json @@ -158,6 +158,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true }, "delete": { @@ -221,6 +224,9 @@ } } }, + "x-ms-long-running-operation-options": { + "final-state-via": "operation-location" + }, "x-ms-long-running-operation": true } }, diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/package.json b/packages/typespec-test/test/contoso/generated/typespec-ts/package.json index 673199fc66..216e9bb6d6 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -60,7 +60,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/review/contosowidgetmanager-rest.api.md b/packages/typespec-test/test/contoso/generated/typespec-ts/review/contosowidgetmanager-rest.api.md index f118224378..c74a7f29ef 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/review/contosowidgetmanager-rest.api.md +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/review/contosowidgetmanager-rest.api.md @@ -21,7 +21,7 @@ import { RequestParameters } from '@azure-rest/core-client'; import { StreamableMethod } from '@azure-rest/core-client'; // @public -function createClient(endpointParam: string, options?: ClientOptions): WidgetManagerClient; +function createClient(endpointParam: string, { apiVersion, ...options }?: WidgetManagerClientOptions): WidgetManagerClient; export default createClient; // @public (undocumented) @@ -269,7 +269,7 @@ export interface ListWidgetsDefaultResponse extends HttpResponse { export type ListWidgetsParameters = RequestParameters; // @public -export type OperationStateOutput = "NotStarted" | "Running" | "Succeeded" | "Failed" | "Canceled"; +export type OperationStateOutput = string; // @public export interface OperationStatusOutput { @@ -344,6 +344,11 @@ export type WidgetManagerClient = Client & { path: Routes; }; +// @public +export interface WidgetManagerClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export interface WidgetOutput { manufacturerId: string; diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/src/outputModels.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/src/outputModels.ts index 33d855583f..f44266c94c 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/src/outputModels.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/src/outputModels.ts @@ -44,12 +44,7 @@ export interface OperationStatusOutput { error?: ErrorModel; } -/** Enum describing allowed operation states. */ -export type OperationStateOutput = - | "NotStarted" - | "Running" - | "Succeeded" - | "Failed" - | "Canceled"; +/** Alias for OperationStateOutput */ +export type OperationStateOutput = string; /** Paged collection of Widget items */ export type PagedWidgetOutput = Paged; diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/src/pollingHelper.ts index 71382cf231..76542ba5d6 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/src/pollingHelper.ts @@ -133,7 +133,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -142,7 +142,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/src/widgetManagerClient.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/src/widgetManagerClient.ts index 55849a6c69..5cb9297739 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/src/widgetManagerClient.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/src/widgetManagerClient.ts @@ -5,6 +5,12 @@ import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "./logger.js"; import { WidgetManagerClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface WidgetManagerClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `WidgetManagerClient` * @param endpointParam - The parameter endpointParam @@ -12,10 +18,12 @@ import { WidgetManagerClient } from "./clientDefinitions.js"; */ export default function createClient( endpointParam: string, - options: ClientOptions = {}, + { + apiVersion = "2022-11-01-preview", + ...options + }: WidgetManagerClientOptions = {}, ): WidgetManagerClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - options.apiVersion = options.apiVersion ?? "2022-11-01-preview"; const userAgentInfo = `azsdk-js-contosowidgetmanager-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -30,8 +38,24 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, }; - const client = getClient(endpointUrl, options) as WidgetManagerClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/contoso/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/package.json b/packages/typespec-test/test/customWrapper/generated/typespec-ts/package.json index 9703005cac..f4ecc59b65 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/package.json @@ -40,7 +40,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -57,7 +57,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/review/customWrapper.api.md b/packages/typespec-test/test/customWrapper/generated/typespec-ts/review/customWrapper.api.md index 9eb773bd6c..071ee43c33 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/review/customWrapper.api.md +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/review/customWrapper.api.md @@ -19,7 +19,12 @@ export type AuthoringClient = Client & { }; // @public -function createClient(endpointParam: string, credentials: KeyCredential, options?: ClientOptions): AuthoringClient; +export interface AuthoringClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +function createClient(endpointParam: string, credentials: KeyCredential, { apiVersion, ...options }?: AuthoringClientOptions): AuthoringClient; export default createClient; // @public diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/src/authoringClient.ts b/packages/typespec-test/test/customWrapper/generated/typespec-ts/src/authoringClient.ts index 996b2d22d6..0bab540534 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/src/authoringClient.ts +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/src/authoringClient.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { KeyCredential } from "@azure/core-auth"; import { AuthoringClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface AuthoringClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `AuthoringClient` * @param endpointParam - The endpoint to use. @@ -15,11 +21,13 @@ import { AuthoringClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + { + apiVersion = "2022-05-15-preview", + ...options + }: AuthoringClientOptions = {}, ): AuthoringClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/language`; - options.apiVersion = options.apiVersion ?? "2022-05-15-preview"; const userAgentInfo = `azsdk-js-customWrapper-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -38,12 +46,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as AuthoringClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/customWrapper/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/customWrapper/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/package.json index d58a12a565..570cd4cd6d 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/package.json @@ -42,7 +42,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md index 56f9ee66d1..16ebbb9c93 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md @@ -9,7 +9,7 @@ import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -// @public (undocumented) +// @public export interface AcknowledgeCloudEventsOptionalParams extends OperationOptions { contentType?: string; } @@ -57,7 +57,7 @@ export class EventGridClient { releaseCloudEvents(topicName: string, eventSubscriptionName: string, lockTokens: ReleaseOptions, options?: ReleaseCloudEventsOptionalParams): Promise; } -// @public (undocumented) +// @public export interface EventGridClientOptions extends ClientOptions { apiVersion?: string; } @@ -69,12 +69,12 @@ export interface FailedLockToken { lockToken: string; } -// @public (undocumented) +// @public export interface PublishCloudEventOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface PublishCloudEventsOptionalParams extends OperationOptions { contentType?: string; } @@ -83,7 +83,7 @@ export interface PublishCloudEventsOptionalParams extends OperationOptions { export interface PublishResult { } -// @public (undocumented) +// @public export interface ReceiveCloudEventsOptionalParams extends OperationOptions { maxEvents?: number; maxWaitTime?: number; @@ -100,7 +100,7 @@ export interface ReceiveResult { value: ReceiveDetails[]; } -// @public (undocumented) +// @public export interface RejectCloudEventsOptionalParams extends OperationOptions { contentType?: string; } @@ -116,7 +116,7 @@ export interface RejectResult { succeededLockTokens: string[]; } -// @public (undocumented) +// @public export interface ReleaseCloudEventsOptionalParams extends OperationOptions { contentType?: string; } @@ -132,7 +132,7 @@ export interface ReleaseResult { succeededLockTokens: string[]; } -// @public (undocumented) +// @public export type ServiceApiVersions = "2023-06-01-preview"; // (No @packageDocumentation comment for this package) diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts index befb6833e0..c9ec2e4d73 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { EventGridContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface EventGridClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts index a49314530e..f6990b465b 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { uint8ArrayToString } from "@azure/core-util"; +import { + CloudEvent as CloudEventRest, + AcknowledgeOptions as AcknowledgeOptionsRest, + ReleaseOptions as ReleaseOptionsRest, + RejectOptions as RejectOptionsRest, +} from "../rest/index.js"; + /** Properties of an event published to an Azure Messaging EventGrid Namespace topic using the CloudEvent 1.0 Schema. */ export interface CloudEvent { /** An identifier for the event. The combination of id and source must be unique for each distinct event. */ @@ -25,6 +33,24 @@ export interface CloudEvent { subject?: string; } +export function cloudEventSerializer(item: CloudEvent): CloudEventRest { + return { + id: item["id"], + source: item["source"], + data: item["data"], + data_base64: + item["dataBase64"] !== undefined + ? uint8ArrayToString(item["dataBase64"], "base64") + : undefined, + type: item["type"], + time: item["time"]?.toISOString(), + specversion: item["specversion"], + dataschema: item["dataschema"], + datacontenttype: item["datacontenttype"], + subject: item["subject"], + }; +} + /** The result of the Publish operation. */ export interface PublishResult {} @@ -56,6 +82,14 @@ export interface AcknowledgeOptions { lockTokens: string[]; } +export function acknowledgeOptionsSerializer( + item: AcknowledgeOptions, +): AcknowledgeOptionsRest { + return { + lockTokens: item["lockTokens"], + }; +} + /** The result of the Acknowledge operation. */ export interface AcknowledgeResult { /** Array of LockToken values for failed cloud events. Each LockToken includes the lock token value along with the related error information (namely, the error code and description). */ @@ -80,6 +114,14 @@ export interface ReleaseOptions { lockTokens: string[]; } +export function releaseOptionsSerializer( + item: ReleaseOptions, +): ReleaseOptionsRest { + return { + lockTokens: item["lockTokens"], + }; +} + /** The result of the Release operation. */ export interface ReleaseResult { /** Array of LockToken values for failed cloud events. Each LockToken includes the lock token value along with the related error information (namely, the error code and description). */ @@ -94,6 +136,14 @@ export interface RejectOptions { lockTokens: string[]; } +export function rejectOptionsSerializer( + item: RejectOptions, +): RejectOptionsRest { + return { + lockTokens: item["lockTokens"], + }; +} + /** The result of the Reject operation. */ export interface RejectResult { /** Array of LockToken values for failed cloud events. Each LockToken includes the lock token value along with the related error information (namely, the error code and description). */ @@ -102,5 +152,5 @@ export interface RejectResult { succeededLockTokens: string[]; } -/** */ +/** Type of ServiceApiVersions */ export type ServiceApiVersions = "2023-06-01-preview"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts index ac8bfff5f9..57d6274b5c 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/options.ts @@ -3,16 +3,19 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface PublishCloudEventOptionalParams extends OperationOptions { /** content type */ contentType?: string; } +/** Optional parameters. */ export interface PublishCloudEventsOptionalParams extends OperationOptions { /** content type */ contentType?: string; } +/** Optional parameters. */ export interface ReceiveCloudEventsOptionalParams extends OperationOptions { /** Max Events count to be received. Minimum value is 1, while maximum value is 100 events. If not specified, the default value is 1. */ maxEvents?: number; @@ -20,16 +23,19 @@ export interface ReceiveCloudEventsOptionalParams extends OperationOptions { maxWaitTime?: number; } +/** Optional parameters. */ export interface AcknowledgeCloudEventsOptionalParams extends OperationOptions { /** content type */ contentType?: string; } +/** Optional parameters. */ export interface ReleaseCloudEventsOptionalParams extends OperationOptions { /** content type */ contentType?: string; } +/** Optional parameters. */ export interface RejectCloudEventsOptionalParams extends OperationOptions { /** content type */ contentType?: string; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/rest/eventGridClient.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/rest/eventGridClient.ts index 0538530f05..e80e107d08 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/rest/eventGridClient.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/rest/eventGridClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { KeyCredential } from "@azure/core-auth"; import { EventGridContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface EventGridContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `EventGridContext` * @param endpointParam - The host name of the namespace, e.g. namespaceName1.westus-1.eventgrid.azure.net @@ -15,10 +21,12 @@ import { EventGridContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + { + apiVersion = "2023-06-01-preview", + ...options + }: EventGridContextOptions = {}, ): EventGridContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - options.apiVersion = options.apiVersion ?? "2023-06-01-preview"; const userAgentInfo = `azsdk-js-eventgrid-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -37,12 +45,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "SharedAccessKey", }, }; - const client = getClient( endpointUrl, credentials, options, ) as EventGridContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/package.json b/packages/typespec-test/test/faceai/generated/typespec-ts/package.json index 0c90bb48b7..b7c1e352f0 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0" + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2" }, "devDependencies": { "dotenv": "^16.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/review/ai-face-rest.api.md b/packages/typespec-test/test/faceai/generated/typespec-ts/review/ai-face-rest.api.md index a76ec71dee..83bc8beca5 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/review/ai-face-rest.api.md +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/review/ai-face-rest.api.md @@ -26,7 +26,7 @@ export interface AccessoryItemOutput { } // @public -export type AccessoryTypeOutput = string | "headwear" | "glasses" | "mask"; +export type AccessoryTypeOutput = string; // @public export interface AddFaceListFace200Response extends HttpResponse { @@ -582,7 +582,7 @@ export interface AddPersonGroupPersonFaceQueryParamProperties { } // @public -export type BlurLevelOutput = string | "low" | "medium" | "high"; +export type BlurLevelOutput = string; // @public export interface BlurPropertiesOutput { @@ -591,7 +591,7 @@ export interface BlurPropertiesOutput { } // @public -function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, options?: FaceClientOptions): FaceClient; +function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, { apiVersion, ...options }?: FaceClientOptions): FaceClient; export default createClient; // @public @@ -1672,7 +1672,7 @@ export interface DetectFromUrlQueryParamProperties { } // @public -export type DetectionModel = string | "detection_01" | "detection_02" | "detection_03"; +export type DetectionModel = string; // @public (undocumented) export interface DetectMediaTypesParam { @@ -1707,7 +1707,7 @@ export interface DynamicPersonGroupOutput { } // @public -export type ExposureLevelOutput = string | "underExposure" | "goodExposure" | "overExposure"; +export type ExposureLevelOutput = string; // @public export interface ExposurePropertiesOutput { @@ -1733,16 +1733,15 @@ export interface FaceAttributesOutput { } // @public -export type FaceAttributeType = string | "headPose" | "glasses" | "occlusion" | "accessories" | "blur" | "exposure" | "noise" | "mask" | "qualityForRecognition" | "age" | "smile" | "facialHair" | "hair"; +export type FaceAttributeType = string; // @public (undocumented) export type FaceClient = Client & { path: Routes; }; -// @public (undocumented) +// @public export interface FaceClientOptions extends ClientOptions { - // (undocumented) apiVersion?: Versions; } @@ -1829,7 +1828,7 @@ export interface FaceRectangleOutput { } // @public -export type FaceSessionStatusOutput = string | "NotStarted" | "Started" | "ResultAvailable"; +export type FaceSessionStatusOutput = string; // @public export interface FacialHairOutput { @@ -1954,7 +1953,7 @@ export interface FindSimilarFromLargeFaceListDefaultResponse extends HttpRespons export type FindSimilarFromLargeFaceListParameters = FindSimilarFromLargeFaceListBodyParam & RequestParameters; // @public -export type FindSimilarMatchMode = string | "matchPerson" | "matchFace"; +export type FindSimilarMatchMode = string; // @public (undocumented) export type FindSimilarParameters = FindSimilarBodyParam & RequestParameters; @@ -3172,7 +3171,7 @@ export interface GetPersonsQueryParamProperties { } // @public -export type GlassesTypeOutput = string | "noGlasses" | "readingGlasses" | "sunglasses" | "swimmingGoggles"; +export type GlassesTypeOutput = string; // @public (undocumented) export interface Group { @@ -3226,7 +3225,7 @@ export interface HairColorOutput { } // @public -export type HairColorTypeOutput = string | "unknown" | "white" | "gray" | "blond" | "brown" | "red" | "black" | "other"; +export type HairColorTypeOutput = string; // @public export interface HairPropertiesOutput { @@ -3411,7 +3410,7 @@ export interface IdentifyFromPersonGroupDefaultResponse extends HttpResponse { export type IdentifyFromPersonGroupParameters = IdentifyFromPersonGroupBodyParam & RequestParameters; // @public -export type ImageTypeOutput = string | "Color" | "Infrared" | "Depth"; +export type ImageTypeOutput = string; // @public (undocumented) export function isUnexpected(response: GetOperationResult200Response | GetOperationResultDefaultResponse): response is GetOperationResultDefaultResponse; @@ -3775,13 +3774,13 @@ export interface ListPersonResultOutput { } // @public -export type LivenessDecisionOutput = string | "uncertain" | "realface" | "spoofface"; +export type LivenessDecisionOutput = string; // @public -export type LivenessModelOutput = string | "2020-02-15-preview.01" | "2021-11-12-preview.03" | "2022-10-15-preview.04" | "2023-03-02-preview.05"; +export type LivenessModelOutput = string; // @public -export type LivenessOperationMode = string | "Passive"; +export type LivenessOperationMode = string; // @public export interface LivenessOutputsTargetOutput { @@ -3919,10 +3918,10 @@ export interface MaskPropertiesOutput { } // @public -export type MaskTypeOutput = string | "faceMask" | "noMask" | "otherMaskOrOcclusion" | "uncertain"; +export type MaskTypeOutput = string; // @public -export type NoiseLevelOutput = string | "low" | "medium" | "high"; +export type NoiseLevelOutput = string; // @public export interface NoisePropertiesOutput { @@ -3948,7 +3947,7 @@ export interface OperationResultOutput { } // @public -export type OperationStatusOutput = string | "notStarted" | "running" | "succeeded" | "failed"; +export type OperationStatusOutput = string; // @public export interface PersonDirectoryFaceOutput { @@ -3986,13 +3985,13 @@ export interface PersonGroupPersonOutput { } // @public -export type QualityForRecognitionOutput = string | "low" | "medium" | "high"; +export type QualityForRecognitionOutput = string; // @public -export type RecognitionModel = string | "recognition_01" | "recognition_02" | "recognition_03" | "recognition_04"; +export type RecognitionModel = string; // @public -export type RecognitionModelOutput = string | "recognition_01" | "recognition_02" | "recognition_03" | "recognition_04"; +export type RecognitionModelOutput = string; // @public (undocumented) export interface Routes { diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/src/faceClient.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/src/faceClient.ts index 9c39a3f25f..1806a4e039 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/src/faceClient.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/src/faceClient.ts @@ -7,7 +7,9 @@ import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { FaceClient } from "./clientDefinitions.js"; import { Versions } from "./models.js"; +/** The optional parameters for the client */ export interface FaceClientOptions extends ClientOptions { + /** API Version */ apiVersion?: Versions; } @@ -21,14 +23,12 @@ export interface FaceClientOptions extends ClientOptions { export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: FaceClientOptions = {}, + { apiVersion = "v1.1-preview.1", ...options }: FaceClientOptions = {}, ): FaceClient { - const apiVersion = options.apiVersion ?? "v1.1-preview.1"; const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/face/${apiVersion}`; - const userAgentInfo = `azsdk-js-ai-face-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -50,15 +50,9 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient(endpointUrl, credentials, options) as FaceClient; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - if (options.apiVersion) { - logger.warning( - "This client does not support client api-version, please change it at the operation level", - ); - } return client; } diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/src/models.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/src/models.ts index 9ba84592ae..e1b0117fd9 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/src/models.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/src/models.ts @@ -47,38 +47,15 @@ export interface LivenessSessionCreationContentForMultipart { } /** Alias for FaceAttributeType */ -export type FaceAttributeType = - | string - | "headPose" - | "glasses" - | "occlusion" - | "accessories" - | "blur" - | "exposure" - | "noise" - | "mask" - | "qualityForRecognition" - | "age" - | "smile" - | "facialHair" - | "hair"; +export type FaceAttributeType = string; /** Alias for RecognitionModel */ -export type RecognitionModel = - | string - | "recognition_01" - | "recognition_02" - | "recognition_03" - | "recognition_04"; +export type RecognitionModel = string; /** Alias for DetectionModel */ -export type DetectionModel = - | string - | "detection_01" - | "detection_02" - | "detection_03"; +export type DetectionModel = string; /** Alias for FindSimilarMatchMode */ -export type FindSimilarMatchMode = string | "matchPerson" | "matchFace"; +export type FindSimilarMatchMode = string; /** Alias for LivenessOperationMode */ -export type LivenessOperationMode = string | "Passive"; +export type LivenessOperationMode = string; /** Request of liveness with verify session creation. */ export type LivenessSessionWithVerifyImageCreationContent = | FormData diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/src/outputModels.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/src/outputModels.ts index c29ab484c3..5218e60e9d 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/src/outputModels.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/src/outputModels.ts @@ -636,76 +636,30 @@ export interface LivenessWithVerifySessionOutput { } /** Alias for OperationStatusOutput */ -export type OperationStatusOutput = - | string - | "notStarted" - | "running" - | "succeeded" - | "failed"; +export type OperationStatusOutput = string; /** Alias for RecognitionModelOutput */ -export type RecognitionModelOutput = - | string - | "recognition_01" - | "recognition_02" - | "recognition_03" - | "recognition_04"; +export type RecognitionModelOutput = string; /** Alias for GlassesTypeOutput */ -export type GlassesTypeOutput = - | string - | "noGlasses" - | "readingGlasses" - | "sunglasses" - | "swimmingGoggles"; +export type GlassesTypeOutput = string; /** Alias for HairColorTypeOutput */ -export type HairColorTypeOutput = - | string - | "unknown" - | "white" - | "gray" - | "blond" - | "brown" - | "red" - | "black" - | "other"; +export type HairColorTypeOutput = string; /** Alias for AccessoryTypeOutput */ -export type AccessoryTypeOutput = string | "headwear" | "glasses" | "mask"; +export type AccessoryTypeOutput = string; /** Alias for BlurLevelOutput */ -export type BlurLevelOutput = string | "low" | "medium" | "high"; +export type BlurLevelOutput = string; /** Alias for ExposureLevelOutput */ -export type ExposureLevelOutput = - | string - | "underExposure" - | "goodExposure" - | "overExposure"; +export type ExposureLevelOutput = string; /** Alias for NoiseLevelOutput */ -export type NoiseLevelOutput = string | "low" | "medium" | "high"; +export type NoiseLevelOutput = string; /** Alias for MaskTypeOutput */ -export type MaskTypeOutput = - | string - | "faceMask" - | "noMask" - | "otherMaskOrOcclusion" - | "uncertain"; +export type MaskTypeOutput = string; /** Alias for QualityForRecognitionOutput */ -export type QualityForRecognitionOutput = string | "low" | "medium" | "high"; +export type QualityForRecognitionOutput = string; /** Alias for FaceSessionStatusOutput */ -export type FaceSessionStatusOutput = - | string - | "NotStarted" - | "Started" - | "ResultAvailable"; +export type FaceSessionStatusOutput = string; /** Alias for LivenessDecisionOutput */ -export type LivenessDecisionOutput = - | string - | "uncertain" - | "realface" - | "spoofface"; +export type LivenessDecisionOutput = string; /** Alias for ImageTypeOutput */ -export type ImageTypeOutput = string | "Color" | "Infrared" | "Depth"; +export type ImageTypeOutput = string; /** Alias for LivenessModelOutput */ -export type LivenessModelOutput = - | string - | "2020-02-15-preview.01" - | "2021-11-12-preview.03" - | "2022-10-15-preview.04" - | "2023-03-02-preview.05"; +export type LivenessModelOutput = string; diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/src/pollingHelper.ts index 8695dc555e..69ec7c20b3 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/src/pollingHelper.ts @@ -235,7 +235,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -244,7 +244,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/faceai/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/package.json b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/package.json index aae143499c..b64d622202 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0" + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2" }, "devDependencies": { "dotenv": "^16.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/review/health-insights-radiologyinsights.api.md b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/review/health-insights-radiologyinsights.api.md index 05a8e91528..bd62d5a3f1 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/review/health-insights-radiologyinsights.api.md +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/review/health-insights-radiologyinsights.api.md @@ -48,6 +48,11 @@ export type AzureHealthInsightsClient = Client & { path: Routes; }; +// @public +export interface AzureHealthInsightsClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export type ClinicalDocumentType = "consultation" | "dischargeSummary" | "historyAndPhysical" | "radiologyReport" | "procedure" | "progress" | "laboratory" | "pathologyReport"; @@ -202,7 +207,7 @@ export type ContactPointUse = "home" | "work" | "temp" | "old" | "mobile"; export type ContactPointUseOutput = "home" | "work" | "temp" | "old" | "mobile"; // @public -function createClient(endpointParam: string, credentials: KeyCredential, options?: ClientOptions): AzureHealthInsightsClient; +function createClient(endpointParam: string, credentials: KeyCredential, { apiVersion, ...options }?: AzureHealthInsightsClientOptions): AzureHealthInsightsClient; export default createClient; // @public (undocumented) diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/azureHealthInsightsClient.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/azureHealthInsightsClient.ts index 55338dd11c..b08db6e0c3 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/azureHealthInsightsClient.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/azureHealthInsightsClient.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { KeyCredential } from "@azure/core-auth"; import { AzureHealthInsightsClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface AzureHealthInsightsClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `AzureHealthInsightsClient` * @param endpointParam - Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). @@ -15,11 +21,13 @@ import { AzureHealthInsightsClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + { + apiVersion = "2023-09-01-preview", + ...options + }: AzureHealthInsightsClientOptions = {}, ): AzureHealthInsightsClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/health-insights`; - options.apiVersion = options.apiVersion ?? "2023-09-01-preview"; const userAgentInfo = `azsdk-js-health-insights-radiologyinsights-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -38,12 +46,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as AzureHealthInsightsClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/pollingHelper.ts index d39b102bb5..23f60648de 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/pollingHelper.ts @@ -117,7 +117,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -126,7 +126,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/package.json b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/package.json index 90cfd229ba..d4f013a099 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0" + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2" }, "devDependencies": { "dotenv": "^16.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/review/health-insights-clinicalmatching.api.md b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/review/health-insights-clinicalmatching.api.md index 47f3499f29..d3fe9ad5cd 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/review/health-insights-clinicalmatching.api.md +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/review/health-insights-clinicalmatching.api.md @@ -191,7 +191,7 @@ export interface ContactDetailsOutput { } // @public -function createClient(endpointParam: string, credentials: KeyCredential, options?: ClientOptions): HealthInsightsClinicalMatchingClient; +function createClient(endpointParam: string, credentials: KeyCredential, { apiVersion, ...options }?: HealthInsightsClinicalMatchingClientOptions): HealthInsightsClinicalMatchingClient; export default createClient; // @public (undocumented) @@ -350,6 +350,11 @@ export type HealthInsightsClinicalMatchingClient = Client & { path: Routes; }; +// @public +export interface HealthInsightsClinicalMatchingClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public (undocumented) export function isUnexpected(response: GetJob200Response | GetJobDefaultResponse): response is GetJobDefaultResponse; diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/healthInsightsClinicalMatching.ts b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/healthInsightsClinicalMatching.ts index b7fee8d8db..39e6a8fdb0 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/healthInsightsClinicalMatching.ts +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/healthInsightsClinicalMatching.ts @@ -6,6 +6,13 @@ import { logger } from "./logger.js"; import { KeyCredential } from "@azure/core-auth"; import { HealthInsightsClinicalMatchingClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface HealthInsightsClinicalMatchingClientOptions + extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `HealthInsightsClinicalMatchingClient` * @param endpointParam - Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). @@ -15,11 +22,13 @@ import { HealthInsightsClinicalMatchingClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + { + apiVersion = "2023-03-01-preview", + ...options + }: HealthInsightsClinicalMatchingClientOptions = {}, ): HealthInsightsClinicalMatchingClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/healthinsights`; - options.apiVersion = options.apiVersion ?? "2023-03-01-preview"; const userAgentInfo = `azsdk-js-health-insights-clinicalmatching-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -38,12 +47,28 @@ export default function createClient( options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as HealthInsightsClinicalMatchingClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/pollingHelper.ts index 664f6a2e38..40b0a90f41 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/src/pollingHelper.ts @@ -121,7 +121,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -130,7 +130,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/healthInsights_trialmatcher/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json index 20968a9b21..bf70d06e92 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json @@ -46,7 +46,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -63,7 +63,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md index 73752ecbdc..fd0ed98db5 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/review/hierarchy-generic.api.md @@ -20,11 +20,11 @@ export interface BA { prop2: string; } -// @public (undocumented) +// @public export interface BCOp1OptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface BCOperations { // (undocumented) op1: (body: BA, options?: BCOp1OptionalParams) => Promise; @@ -36,27 +36,27 @@ export interface BEA { prop3: string; } -// @public (undocumented) +// @public export interface BECOp1OptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface BECOperations { // (undocumented) op1: (body: BEA, options?: BECOp1OptionalParams) => Promise; } -// @public (undocumented) +// @public export interface BEOperations { // (undocumented) c: BECOperations; } -// @public (undocumented) +// @public export interface BOp1OptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface BOperations { // (undocumented) c: BCOperations; @@ -66,11 +66,11 @@ export interface BOperations { op1: (body: BA, options?: BOp1OptionalParams) => Promise; } -// @public (undocumented) +// @public export interface DOp1OptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DOperations { // (undocumented) op1: (body: A, options?: DOp1OptionalParams) => Promise; @@ -86,11 +86,11 @@ export class FooClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface FooClientOptions extends ClientOptions { } -// @public (undocumented) +// @public export interface Op1OptionalParams extends OperationOptions { } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts index 35c1e5db0e..7026e7770c 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts @@ -5,6 +5,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { FooContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface FooClientOptions extends ClientOptions {} export { FooContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts index d5f39b7bb3..442d4309c1 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/c/index.ts @@ -6,6 +6,7 @@ import { BA } from "../../../models/models.js"; import { op1 } from "../../../api/b/c/index.js"; import { BCOp1OptionalParams } from "../../../models/options.js"; +/** Interface representing a BC operations. */ export interface BCOperations { op1: (body: BA, options?: BCOp1OptionalParams) => Promise; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts index b340af9c0e..13686dad55 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/c/index.ts @@ -6,6 +6,7 @@ import { BEA } from "../../../../models/models.js"; import { op1 } from "../../../../api/b/e/c/index.js"; import { BECOp1OptionalParams } from "../../../../models/options.js"; +/** Interface representing a BEC operations. */ export interface BECOperations { op1: (body: BEA, options?: BECOp1OptionalParams) => Promise; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/index.ts index 9e8a9c1697..df51b19045 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/e/index.ts @@ -4,6 +4,7 @@ import { FooContext } from "../../../api/fooContext.js"; import { BECOperations, getBECOperations } from "./c/index.js"; +/** Interface representing a BE operations. */ export interface BEOperations { c: BECOperations; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts index 9f0ec16c1c..696a0989c4 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts @@ -8,6 +8,7 @@ import { BOp1OptionalParams } from "../../models/options.js"; import { BCOperations, getBCOperations } from "./c/index.js"; import { BEOperations, getBEOperations } from "./e/index.js"; +/** Interface representing a B operations. */ export interface BOperations { op1: (body: BA, options?: BOp1OptionalParams) => Promise; e: BEOperations; diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts index abf39694da..8ee80c842c 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/d/index.ts @@ -6,6 +6,7 @@ import { A } from "../../models/models.js"; import { op1 } from "../../api/d/index.js"; import { DOp1OptionalParams } from "../../models/options.js"; +/** Interface representing a D operations. */ export interface DOperations { op1: (body: A, options?: DOp1OptionalParams) => Promise; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts index 06f3b30381..c5feb00097 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/models.ts @@ -1,14 +1,34 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { A as ARest, Ba as BaRest, Bea as BeaRest } from "../rest/index.js"; + export interface A { prop1: string; } +export function aSerializer(item: A): ARest { + return { + prop1: item["prop1"], + }; +} + export interface BA { prop2: string; } +export function bASerializer(item: BA): BaRest { + return { + prop2: item["prop2"], + }; +} + export interface BEA { prop3: string; } + +export function bEASerializer(item: BEA): BeaRest { + return { + prop3: item["prop3"], + }; +} diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts index a4f65f10e6..380b1da2e4 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/models/options.ts @@ -3,12 +3,17 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface Op1OptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface BOp1OptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface BECOp1OptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface BCOp1OptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DOp1OptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/rest/fooClient.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/rest/fooClient.ts index 7cc8a35cb3..d981f429bd 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/rest/fooClient.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/rest/fooClient.ts @@ -5,6 +5,9 @@ import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "../logger.js"; import { FooContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface FooContextOptions extends ClientOptions {} + /** * Initialize a new instance of `FooContext` * @param endpointParam - The parameter endpointParam @@ -12,10 +15,9 @@ import { FooContext } from "./clientDefinitions.js"; */ export default function createClient( endpointParam: string, - options: ClientOptions = {}, + options: FooContextOptions = {}, ): FooContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-hierarchy-generic-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -30,7 +32,6 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, }; - const client = getClient(endpointUrl, options) as FooContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/package.json b/packages/typespec-test/test/loadTest/generated/typespec-ts/package.json index 44532116ca..58eee34d26 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -60,7 +60,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadTest/generated/typespec-ts/review/load-testing.api.md index a56496118b..c2f9e65fab 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/review/load-testing.api.md @@ -49,6 +49,11 @@ export type AzureLoadTestingClient = Client & { path: Routes; }; +// @public +export interface AzureLoadTestingClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export interface CertificateMetadata { name?: string; @@ -70,7 +75,7 @@ export type CertificateType = "AKV_CERT_URI"; export type CertificateTypeOutput = "AKV_CERT_URI"; // @public -function createClient(endpointParam: string, credentials: TokenCredential, options?: ClientOptions): AzureLoadTestingClient; +function createClient(endpointParam: string, credentials: TokenCredential, { apiVersion, ...options }?: AzureLoadTestingClientOptions): AzureLoadTestingClient; export default createClient; // @public diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/src/azureLoadTesting.ts b/packages/typespec-test/test/loadTest/generated/typespec-ts/src/azureLoadTesting.ts index 9d6d3b72be..4ec205eac9 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/src/azureLoadTesting.ts +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/src/azureLoadTesting.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { TokenCredential } from "@azure/core-auth"; import { AzureLoadTestingClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface AzureLoadTestingClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `AzureLoadTestingClient` * @param endpointParam - A sequence of textual characters. @@ -15,11 +21,10 @@ import { AzureLoadTestingClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential, - options: ClientOptions = {}, + { apiVersion = "2022-11-01", ...options }: AzureLoadTestingClientOptions = {}, ): AzureLoadTestingClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - options.apiVersion = options.apiVersion ?? "2022-11-01"; const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -39,12 +44,27 @@ export default function createClient( ], }, }; - const client = getClient( endpointUrl, credentials, options, ) as AzureLoadTestingClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); return client; } diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/loadTest/generated/typespec-ts/src/pollingHelper.ts index 4b79865fe8..19a90195ba 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/src/pollingHelper.ts @@ -123,7 +123,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -132,7 +132,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/loadTest/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/loadTest/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json index 4e1705fc62..b2600369a1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json @@ -46,13 +46,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -66,7 +66,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index 23910811d9..28a417d96c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -4,22 +4,13 @@ ```ts -/// - import { AbortSignalLike } from '@azure/abort-controller'; -import { Client } from '@azure-rest/core-client'; import { ClientOptions } from '@azure-rest/core-client'; -import { ErrorResponse } from '@azure-rest/core-client'; -import { HttpResponse } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { OperationState } from '@azure/core-lro'; -import { Paged } from '@azure/core-paging'; import { PathUncheckedResponse } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { PollerLike } from '@azure/core-lro'; -import { RawHttpHeaders } from '@azure/core-rest-pipeline'; -import { RequestParameters } from '@azure-rest/core-client'; -import { StreamableMethod } from '@azure-rest/core-client'; import { TokenCredential } from '@azure/core-auth'; // @public (undocumented) @@ -40,15 +31,15 @@ export class AdministrationOperationsClient { uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptionalParams): Promise; } -// @public (undocumented) +// @public export interface AdministrationOperationsClientOptions extends ClientOptions { apiVersion?: string; } -// @public (undocumented) +// @public export type AggregationType = "Average" | "Count" | "None" | "Total" | "Percentile90" | "Percentile95" | "Percentile99"; -// @public (undocumented) +// @public export type APIVersions = "2022-11-01"; // @public @@ -69,7 +60,7 @@ export interface CertificateMetadata { value?: string; } -// @public (undocumented) +// @public export type CertificateType = "AKV_CERT_URI"; // @public @@ -77,33 +68,33 @@ export type ContinuablePage = TPage & { continuationToken?: string; }; -// @public (undocumented) +// @public export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface CreateOrUpdateTestOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface DeleteTestFileOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DeleteTestOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface DeleteTestRunOptionalParams extends OperationOptions { } @@ -140,56 +131,56 @@ export interface FileInfo { validationStatus?: FileStatus; } -// @public (undocumented) +// @public export type FileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; -// @public (undocumented) +// @public export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -// @public (undocumented) +// @public export interface GetAppComponentsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetServerMetricsConfigOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTestFileOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTestOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTestRunFileOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetTestRunOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; -// @public (undocumented) +// @public export interface ListMetricDefinitionsOptionalParams extends OperationOptions { metricNamespace?: string; } -// @public (undocumented) +// @public export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { interval?: TestRunOperationsClientInterval; metricName?: string; timespan?: string; } -// @public (undocumented) +// @public export interface ListMetricNamespacesOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ListMetricsOptionalParams extends OperationOptions { aggregation?: string; interval?: TestRunOperationsClientInterval; @@ -198,11 +189,11 @@ export interface ListMetricsOptionalParams extends OperationOptions { timespan?: string; } -// @public (undocumented) +// @public export interface ListTestFilesOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ListTestRunsOptionalParams extends OperationOptions { executionFrom?: string; executionTo?: string; @@ -213,7 +204,7 @@ export interface ListTestRunsOptionalParams extends OperationOptions { testId?: string; } -// @public (undocumented) +// @public export interface ListTestsOptionalParams extends OperationOptions { lastModifiedEndTime?: string; lastModifiedStartTime?: string; @@ -268,7 +259,7 @@ export interface MetricRequestPayload { filters?: DimensionFilter[]; } -// @public (undocumented) +// @public export type MetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; // @public @@ -298,36 +289,6 @@ export interface PagedAsyncIterableIterator>; } -// @public -export interface PagedDimensionValueList { - nextLink?: string; - value: DimensionValueList[]; -} - -// @public -export interface PagedFileInfo { - nextLink?: string; - value: FileInfo[]; -} - -// @public -export interface PagedTest { - nextLink?: string; - value: Test[]; -} - -// @public -export interface PagedTestRun { - nextLink?: string; - value: TestRun[]; -} - -// @public -export interface PagedTimeSeriesElement { - nextLink?: string; - value: TimeSeriesElement[]; -} - // @public export interface PageSettings { continuationToken?: string; @@ -350,19 +311,19 @@ export interface PassFailMetric { value?: number; } -// @public (undocumented) +// @public export type PFAction = "continue" | "stop"; -// @public (undocumented) +// @public export type PFAgFunc = "count" | "percentage" | "avg" | "p50" | "p90" | "p95" | "p99" | "min" | "max"; -// @public (undocumented) +// @public export type PFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; -// @public (undocumented) +// @public export type PFResult = "passed" | "undetermined" | "failed"; -// @public (undocumented) +// @public export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; // @public @@ -377,10 +338,8 @@ export interface ResourceMetric { unit?: string; } -// Warning: (ae-forgotten-export) The symbol "AzureLoadTestingContext" needs to be exported by the entry point index.d.ts -// // @public -export function restorePoller(client: AzureLoadTestingContext | TestRunOperationsClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; +export function restorePoller(client: TestRunOperationsClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; // @public (undocumented) export interface RestorePollerOptions extends OperationOptions { @@ -395,13 +354,13 @@ export interface Secret { value?: string; } -// @public (undocumented) +// @public export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; -// @public (undocumented) +// @public export type Status = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -// @public (undocumented) +// @public export interface StopTestRunOptionalParams extends OperationOptions { } @@ -518,10 +477,10 @@ export class TestRunOperationsClient { testRun(testRunId: string, resource: TestRunOperationsClientTestRun, options?: TestRunOptionalParams): PollerLike, TestRunOperationsClientTestRun>; } -// @public (undocumented) +// @public export type TestRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile90" | "Percentile95" | "Percentile99"; -// @public (undocumented) +// @public export type TestRunOperationsClientAPIVersions = "2022-11-01"; // @public @@ -542,7 +501,7 @@ export interface TestRunOperationsClientCertificateMetadata { value?: string; } -// @public (undocumented) +// @public export type TestRunOperationsClientCertificateType = "AKV_CERT_URI"; // @public @@ -550,13 +509,13 @@ export type TestRunOperationsClientContinuablePage continuationToken?: string; }; -// @public (undocumented) +// @public export interface TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { // (undocumented) contentType?: string; @@ -595,21 +554,21 @@ export interface TestRunOperationsClientFileInfo { validationStatus?: TestRunOperationsClientFileStatus; } -// @public (undocumented) +// @public export type TestRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; -// @public (undocumented) +// @public export type TestRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -// @public (undocumented) +// @public export interface TestRunOperationsClientGetAppComponentsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface TestRunOperationsClientGetServerMetricsConfigOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export type TestRunOperationsClientInterval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; // @public @@ -658,7 +617,7 @@ export interface TestRunOperationsClientMetricRequestPayload { filters?: TestRunOperationsClientDimensionFilter[]; } -// @public (undocumented) +// @public export type TestRunOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; // @public @@ -681,7 +640,7 @@ export interface TestRunOperationsClientOptionalLoadTestConfig { virtualUsers?: number; } -// @public (undocumented) +// @public export interface TestRunOperationsClientOptions extends ClientOptions { apiVersion?: string; } @@ -693,36 +652,6 @@ export interface TestRunOperationsClientPagedAsyncIterableIterator>; } -// @public -export interface TestRunOperationsClientPagedDimensionValueList { - nextLink?: string; - value: TestRunOperationsClientDimensionValueList[]; -} - -// @public -export interface TestRunOperationsClientPagedFileInfo { - nextLink?: string; - value: TestRunOperationsClientFileInfo[]; -} - -// @public -export interface TestRunOperationsClientPagedTest { - nextLink?: string; - value: TestRunOperationsClientTest[]; -} - -// @public -export interface TestRunOperationsClientPagedTestRun { - nextLink?: string; - value: TestRunOperationsClientTestRun[]; -} - -// @public -export interface TestRunOperationsClientPagedTimeSeriesElement { - nextLink?: string; - value: TestRunOperationsClientTimeSeriesElement[]; -} - // @public export interface TestRunOperationsClientPageSettings { continuationToken?: string; @@ -745,19 +674,19 @@ export interface TestRunOperationsClientPassFailMetric { value?: number; } -// @public (undocumented) +// @public export type TestRunOperationsClientPFAction = "continue" | "stop"; -// @public (undocumented) +// @public export type TestRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p90" | "p95" | "p99" | "min" | "max"; -// @public (undocumented) +// @public export type TestRunOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; -// @public (undocumented) +// @public export type TestRunOperationsClientPFResult = "passed" | "undetermined" | "failed"; -// @public (undocumented) +// @public export type TestRunOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; // @public @@ -778,10 +707,10 @@ export interface TestRunOperationsClientSecret { value?: string; } -// @public (undocumented) +// @public export type TestRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; -// @public (undocumented) +// @public export type TestRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; // @public @@ -921,7 +850,7 @@ export interface TestRunOperationsClientTestServerMetricConfig { readonly testId?: string; } -// @public (undocumented) +// @public export type TestRunOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; // @public @@ -930,7 +859,7 @@ export interface TestRunOperationsClientTimeSeriesElement { dimensionValues?: TestRunOperationsClientDimensionValue[]; } -// @public (undocumented) +// @public export interface TestRunOptionalParams extends OperationOptions { contentType?: string; oldTestRunId?: string; @@ -981,7 +910,7 @@ export interface TestServerMetricConfig { readonly testId?: string; } -// @public (undocumented) +// @public export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; // @public @@ -990,7 +919,7 @@ export interface TimeSeriesElement { dimensionValues?: DimensionValue[]; } -// @public (undocumented) +// @public export interface UploadTestFileOptionalParams extends OperationOptions { // (undocumented) contentType?: string; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index aba71240a2..b83a0d4a29 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -5,9 +5,7 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, - TestFileInfo, - FileType, - FileStatus, + FileInfo, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -29,7 +27,7 @@ import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createAdministrationOperations, AdministrationOperationsClientOptions, - LoadTestServiceContext, + AzureLoadTestingContext, createOrUpdateTest, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, @@ -47,7 +45,7 @@ import { export { AdministrationOperationsClientOptions } from "./api/administrationOperationsContext.js"; export class AdministrationOperationsClient { - private _client: LoadTestServiceContext; + private _client: AzureLoadTestingContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -64,7 +62,7 @@ export class AdministrationOperationsClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test by providing the test Id. */ + /** Create a new test or update an existing test. */ createOrUpdateTest( testId: string, body: Test, @@ -73,7 +71,7 @@ export class AdministrationOperationsClient { return createOrUpdateTest(this._client, testId, body, options); } - /** Add an app component to a test by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test */ createOrUpdateAppComponents( testId: string, body: TestAppComponents, @@ -114,7 +112,7 @@ export class AdministrationOperationsClient { return getServerMetricsConfig(this._client, testId, options); } - /** Get load test details by test Id */ + /** Get load test details by test name */ getTest( testId: string, options: GetTestOptionalParams = { requestOptions: {} }, @@ -122,18 +120,12 @@ export class AdministrationOperationsClient { return getTest(this._client, testId, options); } - /** Get all the files that are associated with a test. */ + /** Get test file by the file name. */ getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return getTestFile(this._client, testId, fileName, options); } @@ -141,7 +133,7 @@ export class AdministrationOperationsClient { listTestFiles( testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -156,7 +148,7 @@ export class AdministrationOperationsClient { } /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -165,13 +157,7 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return uploadTestFile(this._client, testId, fileName, body, options); } @@ -184,7 +170,7 @@ export class AdministrationOperationsClient { return deleteTestFile(this._client, testId, fileName, options); } - /** Delete a test by its test Id. */ + /** Delete a test by its name. */ deleteTest( testId: string, options: DeleteTestOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 318287a1eb..41e5e742a6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -3,21 +3,22 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { LoadTestServiceContext } from "../../rest/index.js"; +import { AzureLoadTestingContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; +/** Optional parameters for the client. */ export interface AdministrationOperationsClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; } -export { LoadTestServiceContext } from "../../rest/index.js"; +export { AzureLoadTestingContext } from "../../rest/index.js"; export function createAdministrationOperations( endpointParam: string, credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, -): LoadTestServiceContext { +): AzureLoadTestingContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts index 342aa50e7a..f7564cbffd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts @@ -4,7 +4,7 @@ export { createAdministrationOperations, AdministrationOperationsClientOptions, - LoadTestServiceContext, + AzureLoadTestingContext, } from "./administrationOperationsContext.js"; export { createOrUpdateTest, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index 78223a86d8..6c568e6bf2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -2,19 +2,24 @@ // Licensed under the MIT license. import { + passFailCriteriaSerializer, + secretSerializer, + certificateMetadataSerializer, + loadTestConfigurationSerializer, + appComponentSerializer, + resourceMetricSerializer, Test, - TestFileInfo, - FileType, - FileStatus, + FileInfo, TestAppComponents, TestServerMetricConfig, - PagedTestFileInfo, - PagedTest, + _PagedFileInfo, + _PagedTest, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, + AzureLoadTestingContext as Client, LoadTestAdministrationCreateOrUpdateAppComponents200Response, LoadTestAdministrationCreateOrUpdateAppComponents201Response, LoadTestAdministrationCreateOrUpdateAppComponentsDefaultResponse, @@ -42,13 +47,13 @@ import { LoadTestAdministrationListTestsDefaultResponse, LoadTestAdministrationUploadTestFile201Response, LoadTestAdministrationUploadTestFileDefaultResponse, - LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, @@ -82,67 +87,23 @@ export function _createOrUpdateTestSend( (options.contentType as any) ?? "application/merge-patch+json", body: { passFailCriteria: !body.passFailCriteria - ? undefined - : { passFailMetrics: body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !body.autoStopCriteria - ? undefined - : { - autoStopDisabled: body.autoStopCriteria?.["autoStopDisabled"], - errorRate: body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: body["secrets"], + ? body.passFailCriteria + : passFailCriteriaSerializer(body.passFailCriteria), + secrets: !body.secrets + ? body.secrets + : (serializeRecord(body.secrets as any, secretSerializer) as any), certificate: !body.certificate - ? undefined - : { - value: body.certificate?.["value"], - type: body.certificate?.["type"], - name: body.certificate?.["name"], - }, - environmentVariables: body["environmentVariables"], + ? body.certificate + : certificateMetadataSerializer(body.certificate), + environmentVariables: !body.environmentVariables + ? body.environmentVariables + : (serializeRecord(body.environmentVariables as any) as any), loadTestConfiguration: !body.loadTestConfiguration - ? undefined - : { - engineInstances: body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - }, - baselineTestRunId: body["baselineTestRunId"], + ? body.loadTestConfiguration + : loadTestConfigurationSerializer(body.loadTestConfiguration), description: body["description"], displayName: body["displayName"], subnetId: body["subnetId"], - kind: body["kind"], - publicIPDisabled: body["publicIPDisabled"], keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], }, @@ -163,14 +124,6 @@ export async function _createOrUpdateTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -195,14 +148,6 @@ export async function _createOrUpdateTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -217,28 +162,21 @@ export async function _createOrUpdateTestDeserialize( ], }, }, - baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -251,21 +189,15 @@ export async function _createOrUpdateTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -278,21 +210,15 @@ export async function _createOrUpdateTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -306,13 +232,13 @@ export async function _createOrUpdateTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -320,13 +246,7 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -336,49 +256,14 @@ export async function _createOrUpdateTestDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -387,24 +272,16 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create a new test or update an existing test by providing the test Id. */ +/** Create a new test or update an existing test. */ export async function createOrUpdateTest( context: Client, testId: string, @@ -431,7 +308,12 @@ export function _createOrUpdateAppComponentsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { components: body["components"] }, + body: { + components: serializeRecord( + body.components as any, + appComponentSerializer, + ) as any, + }, }); } @@ -448,20 +330,14 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Add an app component to a test by providing the resource Id, name and type. */ +/** Associate an app component (collection of azure resources) to a test */ export async function createOrUpdateAppComponents( context: Client, testId: string, @@ -495,7 +371,14 @@ export function _createOrUpdateServerMetricsConfigSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { metrics: body["metrics"] }, + body: { + metrics: !body.metrics + ? body.metrics + : (serializeRecord( + body.metrics as any, + resourceMetricSerializer, + ) as any), + }, }); } @@ -512,15 +395,9 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -568,15 +445,9 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -616,15 +487,9 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -665,14 +530,6 @@ export async function _getTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -697,14 +554,6 @@ export async function _getTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -719,28 +568,21 @@ export async function _getTestDeserialize( ], }, }, - baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -753,21 +595,15 @@ export async function _getTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -780,21 +616,15 @@ export async function _getTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -808,13 +638,13 @@ export async function _getTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -822,13 +652,7 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -838,49 +662,14 @@ export async function _getTestDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -889,24 +678,16 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get load test details by test Id */ +/** Get load test details by test name */ export async function getTest( context: Client, testId: string, @@ -934,42 +715,28 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } -/** Get all the files that are associated with a test. */ +/** Get test file by the file name. */ export async function getTestFile( context: Client, testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -991,20 +758,17 @@ export async function _listTestFilesDeserialize( result: | LoadTestAdministrationListTestFiles200Response | LoadTestAdministrationListTestFilesDefaultResponse, -): Promise { +): Promise<_PagedFileInfo> { if (isUnexpected(result)) { throw createRestError(result); } return { value: result.body["value"].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1017,7 +781,7 @@ export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), @@ -1040,8 +804,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), - lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), + lastModifiedStartTime: options?.lastModifiedStartTime, + lastModifiedEndTime: options?.lastModifiedEndTime, maxpagesize: options?.maxpagesize, }, }); @@ -1051,7 +815,7 @@ export async function _listTestsDeserialize( result: | LoadTestAdministrationListTests200Response | LoadTestAdministrationListTestsDefaultResponse, -): Promise { +): Promise<_PagedTest> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1061,14 +825,6 @@ export async function _listTestsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1092,14 +848,6 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1114,23 +862,17 @@ export async function _listTestsDeserialize( ], }, }, - baselineTestRunId: p["baselineTestRunId"], inputArtifacts: !p.inputArtifacts ? undefined : { configFileInfo: !p.inputArtifacts?.configFileInfo ? undefined : { - fileName: p.inputArtifacts?.configFileInfo?.["fileName"], url: p.inputArtifacts?.configFileInfo?.["url"], + fileName: p.inputArtifacts?.configFileInfo?.["fileName"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.configFileInfo?.["expireDateTime"], - ) - : undefined, + p.inputArtifacts?.configFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -1141,18 +883,11 @@ export async function _listTestsDeserialize( testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo ? undefined : { - fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], url: p.inputArtifacts?.testScriptFileInfo?.["url"], + fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: @@ -1163,18 +898,11 @@ export async function _listTestsDeserialize( userPropFileInfo: !p.inputArtifacts?.userPropFileInfo ? undefined : { - fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], url: p.inputArtifacts?.userPropFileInfo?.["url"], + fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -1186,21 +914,15 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -1210,44 +932,14 @@ export async function _listTestsDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], - url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: p.inputArtifacts?.["additionalFileInfo"] === undefined ? p.inputArtifacts?.["additionalFileInfo"] : p.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1256,19 +948,11 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], - kind: p["kind"], - publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, + createdDateTime: p["createdDateTime"], createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: p["lastModifiedDateTime"], lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -1315,31 +999,23 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -1349,13 +1025,7 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _uploadTestFileSend( context, testId, @@ -1428,7 +1098,7 @@ export async function _deleteTestDeserialize( return; } -/** Delete a test by its test Id. */ +/** Delete a test by its name. */ export async function deleteTest( context: Client, testId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index 657642a135..b0c78f4e9d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -13,7 +13,6 @@ export { PFAgFunc, PFAction, PFResult, - AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -21,10 +20,9 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - TestFileInfo, + FileInfo, FileType, FileStatus, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -35,14 +33,12 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -50,17 +46,14 @@ export { AggregationType, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - Metrics, TimeSeriesElement, MetricValue, DimensionValue, - PagedTestFileInfo, - PagedTest, - PagedTestRun, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index 82939ca23f..8385d30729 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -9,7 +9,6 @@ export { PFAgFunc, PFAction, PFResult, - AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -17,10 +16,9 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - TestFileInfo, + FileInfo, FileType, FileStatus, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -31,14 +29,12 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -46,17 +42,14 @@ export { AggregationType, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - Metrics, TimeSeriesElement, MetricValue, DimensionValue, - PagedTestFileInfo, - PagedTest, - PagedTestRun, } from "./models.js"; export { CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index 27018ab1f3..3a7491a214 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -1,12 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model. */ +import { serializeRecord } from "../../helpers/serializerHelpers.js"; +import { + Test as TestRest, + PassFailCriteria as PassFailCriteriaRest, + PassFailMetric as PassFailMetricRest, + Secret as SecretRest, + CertificateMetadata as CertificateMetadataRest, + LoadTestConfiguration as LoadTestConfigurationRest, + OptionalLoadTestConfig as OptionalLoadTestConfigRest, + TestAppComponents as TestAppComponentsRest, + AppComponent as AppComponentRest, + TestServerMetricConfig as TestServerMetricConfigRest, + ResourceMetric as ResourceMetricRest, + TestRun as TestRunRest, + TestRunAppComponents as TestRunAppComponentsRest, + TestRunServerMetricConfig as TestRunServerMetricConfigRest, + MetricRequestPayload as MetricRequestPayloadRest, + DimensionFilter as DimensionFilterRest, +} from "../../rest/index.js"; + +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,48 +33,80 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testSerializer(item: Test): TestRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + }; +} + /** Pass fail criteria for a test. */ export interface PassFailCriteria { /** Map of id and pass fail metrics { id : pass fail metrics }. */ passFailMetrics?: Record; } +export function passFailCriteriaSerializer( + item: PassFailCriteria, +): PassFailCriteriaRest { + return { + passFailMetrics: !item.passFailMetrics + ? item.passFailMetrics + : (serializeRecord( + item.passFailMetrics as any, + passFailMetricSerializer, + ) as any), + }; +} + /** Pass fail metric */ export interface PassFailMetric { /** The client metric on which the criteria should be applied. */ @@ -85,28 +135,41 @@ export interface PassFailMetric { readonly result?: PFResult; } -/** Metrics for pass/fail criteria. */ -/** "response_time_ms", "latency", "error", "requests", "requests_per_sec" */ -export type PFMetrics = string; -/** Aggregation functions for pass/fail criteria. */ -/** "count", "percentage", "avg", "p50", "p90", "p95", "p99", "min", "max" */ -export type PFAgFunc = string; -/** Action to take on failure of pass/fail criteria. */ -/** "continue", "stop" */ -export type PFAction = string; -/** Pass/fail criteria result. */ -/** "passed", "undetermined", "failed" */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} +export function passFailMetricSerializer( + item: PassFailMetric, +): PassFailMetricRest { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + }; +} + +/** Type of PFMetrics */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Type of PFAgFunc */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; +/** Type of PFAction */ +export type PFAction = "continue" | "stop"; +/** Type of PFResult */ +export type PFResult = "passed" | "undetermined" | "failed"; /** Secret */ export interface Secret { @@ -116,9 +179,15 @@ export interface Secret { type?: SecretType; } -/** Types of secrets supported. */ -/** "AKV_SECRET_URI", "SECRET_VALUE" */ -export type SecretType = string; +export function secretSerializer(item: Secret): SecretRest { + return { + value: item["value"], + type: item["type"], + }; +} + +/** Type of SecretType */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ export interface CertificateMetadata { @@ -130,13 +199,25 @@ export interface CertificateMetadata { name?: string; } -/** Types of certificates supported. */ -/** "AKV_CERT_URI" */ -export type CertificateType = string; +export function certificateMetadataSerializer( + item: CertificateMetadata, +): CertificateMetadataRest { + return { + value: item["value"], + type: item["type"], + name: item["name"], + }; +} + +/** Type of CertificateType */ +export type CertificateType = "AKV_CERT_URI"; -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -150,69 +231,90 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Configuration for quick load test */ +export function loadTestConfigurationSerializer( + item: LoadTestConfiguration, +): LoadTestConfigurationRest { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item.optionalLoadTestConfig + ? item.optionalLoadTestConfig + : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + }; +} + +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } +export function optionalLoadTestConfigSerializer( + item: OptionalLoadTestConfig, +): OptionalLoadTestConfigRest { + return { + endpointUrl: item["endpointUrl"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; + readonly additionalFileInfo?: FileInfo[]; } -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfo { /** File URL. */ - readonly url?: string; + url?: string; + /** Name of the file. */ + fileName?: string; /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; /** Validation status of the file */ - readonly validationStatus?: FileStatus; + validationStatus?: FileStatus; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Types of file supported. */ -/** "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG_JSON" */ -export type FileType = string; -/** File status. */ -/** "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" */ -export type FileStatus = string; -/** Test kind */ -/** "URL", "JMX" */ -export type TestKind = string; +/** Type of FileType */ +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +/** Type of FileStatus */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; -/** Test app components */ +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -222,24 +324,41 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +export function testAppComponentsSerializer( + item: TestAppComponents, +): TestAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -250,6 +369,15 @@ export interface AppComponent { kind?: string; } +export function appComponentSerializer(item: AppComponent): AppComponentRest { + return { + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + kind: item["kind"], + }; +} + /** Test server metrics configuration */ export interface TestServerMetricConfig { /** Test identifier */ @@ -259,17 +387,27 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testServerMetricConfigSerializer( + item: TestServerMetricConfig, +): TestServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + /** * Associated metric definition for particular metrics of the azure resource ( * Refer : @@ -294,18 +432,45 @@ export interface ResourceMetric { resourceType: string; } -/** Azure Load Testing API versions. */ -/** */ -export type APIVersions = "2022-11-01" | "2023-04-01-preview"; +export function resourceMetricSerializer( + item: ResourceMetric, +): ResourceMetricRest { + return { + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +/** Collection of files. */ +export interface _PagedFileInfo { + /** The FileInfo items on this page */ + value: FileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Collection of tests */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Type of APIVersions */ +export type APIVersions = "2022-11-01"; /** Load test run model */ export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -338,32 +503,51 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; + /** The test run start DateTime(ISO 8601 literal format). */ + readonly startDateTime?: string; + /** The test run end DateTime(ISO 8601 literal format). */ + readonly endDateTime?: string; /** Test run initiated time. */ - readonly executedDateTime?: Date; + readonly executedDateTime?: string; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testRunSerializer(item: TestRun): TestRunRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + }; +} + /** Error details if there is any failure in load test run */ export interface ErrorDetails { /** Error details in case test run was not successfully run. */ @@ -413,59 +597,45 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: FileInfo[]; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Test result based on pass/fail criteria. */ -/** "PASSED", "NOT_APPLICABLE", "FAILED" */ -export type PFTestResult = string; -/** Test run status. */ -/** "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" */ -export type Status = string; + logsFileInfo?: FileInfo; +} + +/** Type of PFTestResult */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Type of Status */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; /** Test run app component */ export interface TestRunAppComponents { @@ -477,16 +647,27 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testRunAppComponentsSerializer( + item: TestRunAppComponents, +): TestRunAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + /** Test run server metrics configuration */ export interface TestRunServerMetricConfig { /** Test run identifier */ @@ -497,28 +678,31 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** Time Grain */ -/** "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ -export type TimeGrain = string; +export function testRunServerMetricConfigSerializer( + item: TestRunServerMetricConfig, +): TestRunServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + +/** Type of Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; -/** Metrics dimension values. */ export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Represents collection of metric definitions. */ @@ -558,12 +742,25 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -/** "Average", "Count", "None", "Total", "Percentile90", "Percentile95", "Percentile99" */ -export type AggregationType = string; -/** Metric unit. */ -/** "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" */ -export type MetricUnit = string; +/** Type of AggregationType */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile90" + | "Percentile95" + | "Percentile99"; +/** Type of MetricUnit */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -574,6 +771,9 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } +/** Type of TimeGrain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -588,7 +788,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -599,6 +799,17 @@ export interface MetricRequestPayload { filters?: DimensionFilter[]; } +export function metricRequestPayloadSerializer( + item: MetricRequestPayload, +): MetricRequestPayloadRest { + return { + filters: + item["filters"] === undefined + ? item["filters"] + : item["filters"].map(dimensionFilterSerializer), + }; +} + /** Dimension name and values to filter */ export interface DimensionFilter { /** The dimension name */ @@ -607,8 +818,17 @@ export interface DimensionFilter { values?: string[]; } +export function dimensionFilterSerializer( + item: DimensionFilter, +): DimensionFilterRest { + return { + name: item["name"], + values: item["values"], + }; +} + /** The response to a metrics query. */ -export interface Metrics { +export interface _PagedTimeSeriesElement { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -625,8 +845,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; + /** The timestamp for the metric value in ISO 8601 format. */ + timestamp?: string; /** The metric value. */ value?: number; } @@ -639,26 +859,18 @@ export interface DimensionValue { value?: string; } -/** Paged collection of TestFileInfo items */ -export interface PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface PagedTest { - /** The Test items on this page */ - value: Test[]; +/** Collection of test runs */ +export interface _PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; /** The link to the next page of items */ nextLink?: string; } -/** Paged collection of TestRun items */ -export interface PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; +/** Paged collection of DimensionValueList items */ +export interface _PagedDimensionValueList { + /** The DimensionValueList items on this page */ + value: DimensionValueList[]; /** The link to the next page of items */ nextLink?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts index 62943adcc2..f6d6da0948 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts @@ -4,34 +4,40 @@ import { OperationOptions } from "@azure-rest/core-client"; import { FileType } from "./models.js"; +/** Optional parameters. */ export interface CreateOrUpdateTestOptionalParams extends OperationOptions { - /** This request has a JSON Merge Patch body. */ contentType?: string; } +/** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } +/** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } +/** Optional parameters. */ export interface GetAppComponentsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetServerMetricsConfigOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTestOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTestFileOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListTestFilesOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListTestsOptionalParams extends OperationOptions { /** * Sort on the supported fields in (field asc/desc) format. eg: @@ -44,21 +50,29 @@ export interface ListTestsOptionalParams extends OperationOptions { * the search parameter can be Login. */ search?: string; - /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedStartTime?: Date; - /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedEndTime?: Date; + /** + * Start DateTime(ISO 8601 literal format) of the last updated time range to + * filter tests. + */ + lastModifiedStartTime?: string; + /** + * End DateTime(ISO 8601 literal format) of the last updated time range to filter + * tests. + */ + lastModifiedEndTime?: string; /** Number of results in response. */ maxpagesize?: number; } +/** Optional parameters. */ export interface UploadTestFileOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; /** File type */ fileType?: FileType; } +/** Optional parameters. */ export interface DeleteTestFileOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface DeleteTestOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index d491e00954..d06253bb01 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -13,7 +13,6 @@ export { PFAgFunc, PFAction, PFResult, - AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -21,10 +20,9 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - TestFileInfo, + FileInfo, FileType, FileStatus, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -35,14 +33,12 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -50,17 +46,14 @@ export { AggregationType, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - Metrics, TimeSeriesElement, MetricValue, DimensionValue, - PagedTestFileInfo, - PagedTest, - PagedTestRun, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -81,6 +74,10 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperations/testRunOperationsClient.js"; +export { + restorePoller, + RestorePollerOptions, +} from "./testRunOperations/restorePollerHelpers.js"; export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, @@ -89,7 +86,6 @@ export { PFAgFunc as TestRunOperationsClientPFAgFunc, PFAction as TestRunOperationsClientPFAction, PFResult as TestRunOperationsClientPFResult, - AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, @@ -97,10 +93,9 @@ export { LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, - TestFileInfo as TestRunOperationsClientTestFileInfo, + FileInfo as TestRunOperationsClientFileInfo, FileType as TestRunOperationsClientFileType, FileStatus as TestRunOperationsClientFileStatus, - TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, TestServerMetricConfig as TestRunOperationsClientTestServerMetricConfig, @@ -111,14 +106,12 @@ export { TestRunStatistics as TestRunOperationsClientTestRunStatistics, TestRunArtifacts as TestRunOperationsClientTestRunArtifacts, TestRunInputArtifacts as TestRunOperationsClientTestRunInputArtifacts, - TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, PFTestResult as TestRunOperationsClientPFTestResult, Status as TestRunOperationsClientStatus, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, - TimeGrain as TestRunOperationsClientTimeGrain, + Interval as TestRunOperationsClientInterval, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, @@ -126,18 +119,15 @@ export { AggregationType as TestRunOperationsClientAggregationType, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, + TimeGrain as TestRunOperationsClientTimeGrain, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, MetricNamespace as TestRunOperationsClientMetricNamespace, MetricRequestPayload as TestRunOperationsClientMetricRequestPayload, DimensionFilter as TestRunOperationsClientDimensionFilter, - Metrics as TestRunOperationsClientMetrics, TimeSeriesElement as TestRunOperationsClientTimeSeriesElement, MetricValue as TestRunOperationsClientMetricValue, DimensionValue as TestRunOperationsClientDimensionValue, - PagedTestFileInfo as TestRunOperationsClientPagedTestFileInfo, - PagedTest as TestRunOperationsClientPagedTest, - PagedTestRun as TestRunOperationsClientPagedTestRun, - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts new file mode 100644 index 0000000000..01f53c8bc8 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { TokenCredential } from "@azure/core-auth"; +import { AzureLoadTestingContext } from "./clientDefinitions.js"; + +/** The optional parameters for the client */ +export interface AzureLoadTestingContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + +/** + * Initialize a new instance of `AzureLoadTestingContext` + * @param endpointParam - A sequence of textual characters. + * @param credentials - uniquely identify client credential + * @param options - the parameter for all optional parameters + */ +export default function createClient( + endpointParam: string, + credentials: TokenCredential, + { + apiVersion = "2022-11-01", + ...options + }: AzureLoadTestingContextOptions = {}, +): AzureLoadTestingContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; + const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://cnt-prod.loadtesting.azure.com/.default", + ], + }, + }; + const client = getClient( + endpointUrl, + credentials, + options, + ) as AzureLoadTestingContext; + + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts index a7c8c3ac30..2d1d85129a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -14,12 +14,12 @@ import { LoadTestAdministrationGetAppComponentsParameters, LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters, LoadTestAdministrationGetServerMetricsConfigParameters, - LoadTestRunGetTestRunParameters, - LoadTestRunCreateOrUpdateTestRunParameters, LoadTestRunDeleteTestRunParameters, - LoadTestRunListTestRunsParameters, + LoadTestRunCreateOrUpdateTestRunParameters, + LoadTestRunGetTestRunParameters, LoadTestRunGetTestRunFileParameters, - LoadTestRunStopParameters, + LoadTestRunListTestRunsParameters, + LoadTestRunStopTestRunParameters, LoadTestRunListMetricNamespacesParameters, LoadTestRunListMetricDefinitionsParameters, LoadTestRunListMetricsParameters, @@ -27,7 +27,7 @@ import { LoadTestRunCreateOrUpdateAppComponentsParameters, LoadTestRunGetAppComponentsParameters, LoadTestRunCreateOrUpdateServerMetricsConfigParameters, - LoadTestRunGetServerMetricsConfigParameters, + LoadTestRunTestRunListServerMetricsConfigParameters, } from "./parameters.js"; import { LoadTestAdministrationCreateOrUpdateTest200Response, @@ -57,19 +57,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, - LoadTestRunListTestRuns200Response, - LoadTestRunListTestRunsDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, LoadTestRunGetTestRunFileDefaultResponse, - LoadTestRunStop200Response, - LoadTestRunStopDefaultResponse, + LoadTestRunListTestRuns200Response, + LoadTestRunListTestRunsDefaultResponse, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -86,13 +86,13 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; export interface LoadTestAdministrationCreateOrUpdateTest { - /** Create a new test or update an existing test by providing the test Id. */ + /** Create a new test or update an existing test. */ patch( options: LoadTestAdministrationCreateOrUpdateTestParameters, ): StreamableMethod< @@ -100,14 +100,14 @@ export interface LoadTestAdministrationCreateOrUpdateTest { | LoadTestAdministrationCreateOrUpdateTest201Response | LoadTestAdministrationCreateOrUpdateTestDefaultResponse >; - /** Delete a test by its test Id. */ + /** Delete a test by its name. */ delete( options?: LoadTestAdministrationDeleteTestParameters, ): StreamableMethod< | LoadTestAdministrationDeleteTest204Response | LoadTestAdministrationDeleteTestDefaultResponse >; - /** Get load test details by test Id */ + /** Get load test details by test name */ get( options?: LoadTestAdministrationGetTestParameters, ): StreamableMethod< @@ -131,7 +131,7 @@ export interface LoadTestAdministrationListTests { export interface LoadTestAdministrationUploadTestFile { /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -141,7 +141,7 @@ export interface LoadTestAdministrationUploadTestFile { | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse >; - /** Get all the files that are associated with a test. */ + /** Get test file by the file name. */ get( options?: LoadTestAdministrationGetTestFileParameters, ): StreamableMethod< @@ -168,7 +168,7 @@ export interface LoadTestAdministrationListTestFiles { } export interface LoadTestAdministrationCreateOrUpdateAppComponents { - /** Add an app component to a test by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test */ patch( options: LoadTestAdministrationCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -203,14 +203,15 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfig { >; } -export interface LoadTestRunGetTestRun { - /** Get test run details by test run Id. */ - get( - options?: LoadTestRunGetTestRunParameters, +export interface LoadTestRunDeleteTestRun { + /** Delete a test run by its name. */ + delete( + options?: LoadTestRunDeleteTestRunParameters, ): StreamableMethod< - LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse >; - /** Create and start a new test run with the given test run Id. */ + /** Create and start a new test run with the given name. */ patch( options: LoadTestRunCreateOrUpdateTestRunParameters, ): StreamableMethod< @@ -218,21 +219,11 @@ export interface LoadTestRunGetTestRun { | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse >; - /** Delete an existing load test run by providing the testRunId. */ - delete( - options?: LoadTestRunDeleteTestRunParameters, - ): StreamableMethod< - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse - >; -} - -export interface LoadTestRunListTestRuns { - /** Get all test runs for the given filters. */ + /** Get test run details by name. */ get( - options?: LoadTestRunListTestRunsParameters, + options?: LoadTestRunGetTestRunParameters, ): StreamableMethod< - LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse + LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse >; } @@ -246,12 +237,21 @@ export interface LoadTestRunGetTestRunFile { >; } -export interface LoadTestRunStop { - /** Stop test run by test run Id. */ +export interface LoadTestRunListTestRuns { + /** Get all test runs with given filters */ + get( + options?: LoadTestRunListTestRunsParameters, + ): StreamableMethod< + LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse + >; +} + +export interface LoadTestRunStopTestRun { + /** Stop test run by name. */ post( - options?: LoadTestRunStopParameters, + options?: LoadTestRunStopTestRunParameters, ): StreamableMethod< - LoadTestRunStop200Response | LoadTestRunStopDefaultResponse + LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse >; } @@ -268,7 +268,7 @@ export interface LoadTestRunListMetricNamespaces { export interface LoadTestRunListMetricDefinitions { /** List the metric definitions for a load test run. */ get( - options: LoadTestRunListMetricDefinitionsParameters, + options?: LoadTestRunListMetricDefinitionsParameters, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response | LoadTestRunListMetricDefinitionsDefaultResponse @@ -295,7 +295,7 @@ export interface LoadTestRunListMetricDimensionValues { } export interface LoadTestRunCreateOrUpdateAppComponents { - /** Add an app component to a test run by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test run */ patch( options: LoadTestRunCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -324,12 +324,12 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfig { | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse >; - /** Get associated server metrics configuration for the given test run. */ + /** List server metrics configuration for the given test run. */ get( - options?: LoadTestRunGetServerMetricsConfigParameters, + options?: LoadTestRunTestRunListServerMetricsConfigParameters, ): StreamableMethod< - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse >; } @@ -362,18 +362,21 @@ export interface Routes { path: "/tests/{testId}/server-metrics-config", testId: string, ): LoadTestAdministrationCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: get, patch, delete */ - (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunGetTestRun; - /** Resource for '/test-runs' has methods for the following verbs: get */ - (path: "/test-runs"): LoadTestRunListTestRuns; + /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: delete, patch, get */ + (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunDeleteTestRun; /** Resource for '/test-runs/\{testRunId\}/files/\{fileName\}' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/files/{fileName}", testRunId: string, fileName: string, ): LoadTestRunGetTestRunFile; + /** Resource for '/test-runs' has methods for the following verbs: get */ + (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}:stop' has methods for the following verbs: post */ - (path: "/test-runs/{testRunId}:stop", testRunId: string): LoadTestRunStop; + ( + path: "/test-runs/{testRunId}:stop", + testRunId: string, + ): LoadTestRunStopTestRun; /** Resource for '/test-runs/\{testRunId\}/metric-namespaces' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/metric-namespaces", @@ -407,6 +410,6 @@ export interface Routes { ): LoadTestRunCreateOrUpdateServerMetricsConfig; } -export type LoadTestServiceContext = Client & { +export type AzureLoadTestingContext = Client & { path: Routes; }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts index b57cb81db2..a22d574c4f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import LoadTestServiceClient from "./loadTestServiceClient.js"; +import AzureLoadTestingClient from "./azureLoadTestingClient.js"; -export * from "./loadTestServiceClient.js"; +export * from "./azureLoadTestingClient.js"; export * from "./parameters.js"; export * from "./responses.js"; export * from "./clientDefinitions.js"; @@ -11,5 +11,6 @@ export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; export * from "./paginateHelper.js"; +export * from "./pollingHelper.js"; -export default LoadTestServiceClient; +export default AzureLoadTestingClient; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts index f57184edf4..e02ac644d2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts @@ -29,19 +29,20 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, - LoadTestRunListTestRuns200Response, - LoadTestRunListTestRunsDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, LoadTestRunGetTestRunFileDefaultResponse, - LoadTestRunStop200Response, - LoadTestRunStopDefaultResponse, + LoadTestRunListTestRuns200Response, + LoadTestRunListTestRunsDefaultResponse, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -58,8 +59,8 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -75,11 +76,11 @@ const responseMap: Record = { "GET /tests/{testId}/app-components": ["200"], "PATCH /tests/{testId}/server-metrics-config": ["200", "201"], "GET /tests/{testId}/server-metrics-config": ["200"], + "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs/{testRunId}": ["200"], "PATCH /test-runs/{testRunId}": ["200", "201"], - "DELETE /test-runs/{testRunId}": ["204"], - "GET /test-runs": ["200"], "GET /test-runs/{testRunId}/files/{fileName}": ["200"], + "GET /test-runs": ["200"], "POST /test-runs/{testRunId}:stop": ["200"], "GET /test-runs/{testRunId}/metric-namespaces": ["200"], "GET /test-runs/{testRunId}/metric-definitions": ["200"], @@ -156,20 +157,26 @@ export function isUnexpected( ): response is LoadTestAdministrationGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse, -): response is LoadTestRunGetTestRunDefaultResponse; + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse, +): response is LoadTestRunDeleteTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): response is LoadTestRunCreateOrUpdateTestRunDefaultResponse; export function isUnexpected( response: - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse, -): response is LoadTestRunDeleteTestRunDefaultResponse; + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse, +): response is LoadTestRunGetTestRunDefaultResponse; +export function isUnexpected( + response: + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse, +): response is LoadTestRunGetTestRunFileDefaultResponse; export function isUnexpected( response: | LoadTestRunListTestRuns200Response @@ -177,12 +184,9 @@ export function isUnexpected( ): response is LoadTestRunListTestRunsDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse, -): response is LoadTestRunGetTestRunFileDefaultResponse; -export function isUnexpected( - response: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, -): response is LoadTestRunStopDefaultResponse; + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse, +): response is LoadTestRunStopTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunListMetricNamespaces200Response @@ -222,9 +226,9 @@ export function isUnexpected( ): response is LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse, -): response is LoadTestRunGetServerMetricsConfigDefaultResponse; + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, +): response is LoadTestRunTestRunListServerMetricsConfigDefaultResponse; export function isUnexpected( response: | LoadTestAdministrationCreateOrUpdateTest200Response @@ -254,19 +258,20 @@ export function isUnexpected( | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfig200Response | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunListTestRuns200Response - | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse - | LoadTestRunStop200Response - | LoadTestRunStopDefaultResponse + | LoadTestRunListTestRuns200Response + | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse | LoadTestRunListMetricNamespaces200Response | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitions200Response @@ -283,8 +288,8 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateServerMetricsConfig200Response | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse, + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, ): response is | LoadTestAdministrationCreateOrUpdateTestDefaultResponse | LoadTestAdministrationDeleteTestDefaultResponse @@ -298,12 +303,12 @@ export function isUnexpected( | LoadTestAdministrationGetAppComponentsDefaultResponse | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunGetTestRunFileDefaultResponse - | LoadTestRunStopDefaultResponse + | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunStopTestRunDefaultResponse | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitionsDefaultResponse | LoadTestRunListMetricsDefaultResponse @@ -311,7 +316,7 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateAppComponentsDefaultResponse | LoadTestRunGetAppComponentsDefaultResponse | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunGetServerMetricsConfigDefaultResponse { + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index 51d22d4827..a102d07cb8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -1,12 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model. */ +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,24 +13,18 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ @@ -69,16 +61,6 @@ export interface PassFailMetric { action?: PFAction; } -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - /** Secret */ export interface Secret { /** The value of the secret for the respective type */ @@ -97,9 +79,12 @@ export interface CertificateMetadata { name?: string; } -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -113,47 +98,54 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; } -/** Test file info. */ -export interface TestFileInfo { +/** File info */ +export interface FileInfo { + /** File URL. */ + url?: string; /** Name of the file. */ - fileName: string; + fileName?: string; + /** File type */ + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; + /** Validation status of the file */ + validationStatus?: FileStatus; + /** Validation failure error details */ + validationFailureDetails?: string; } -/** Test app components */ +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -163,12 +155,15 @@ export interface TestAppComponents { components: Record; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Kind of Azure resource type */ @@ -182,7 +177,7 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; + metrics?: Record; } /** @@ -211,8 +206,6 @@ export interface ResourceMetric { export interface TestRun { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -250,42 +243,24 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; + inputArtifactsZipFileInfo?: FileInfo; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date | string; + logsFileInfo?: FileInfo; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -326,7 +301,6 @@ export interface TestRunServerMetricConfig { /** Alias for PFMetrics */ export type PFMetrics = - | string | "response_time_ms" | "latency" | "error" @@ -334,7 +308,6 @@ export type PFMetrics = | "requests_per_sec"; /** Alias for PFAgFunc */ export type PFAgFunc = - | string | "count" | "percentage" | "avg" @@ -345,36 +318,26 @@ export type PFAgFunc = | "min" | "max"; /** Alias for PFAction */ -export type PFAction = string | "continue" | "stop"; +export type PFAction = "continue" | "stop"; /** Alias for PFResult */ -export type PFResult = string | "passed" | "undetermined" | "failed"; +export type PFResult = "passed" | "undetermined" | "failed"; /** Alias for SecretType */ -export type SecretType = string | "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateType */ -export type CertificateType = string | "AKV_CERT_URI"; +export type CertificateType = "AKV_CERT_URI"; /** Alias for FileType */ -export type FileType = - | string - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG_JSON"; +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; /** Alias for FileStatus */ export type FileStatus = - | string | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; -/** Alias for TestKind */ -export type TestKind = string | "URL" | "JMX"; /** Alias for PFTestResult */ -export type PFTestResult = string | "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; /** Alias for Status */ export type Status = - | string | "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" @@ -391,5 +354,5 @@ export type Status = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -/** Alias for TimeGrain */ -export type TimeGrain = string | "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Alias for Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index 62a3c3841b..392e850e81 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -3,12 +3,10 @@ import { Paged } from "@azure/core-paging"; -/** Load test model. */ +/** Load test model */ export interface TestOutput { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -17,37 +15,31 @@ export interface TestOutput { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadataOutput; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifactsOutput; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKindOutput; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -87,16 +79,6 @@ export interface PassFailMetricOutput { readonly result?: PFResultOutput; } -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteriaOutput { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - /** Secret */ export interface SecretOutput { /** The value of the secret for the respective type */ @@ -115,9 +97,12 @@ export interface CertificateMetadataOutput { name?: string; } -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfigurationOutput { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -131,59 +116,56 @@ export interface LoadTestConfigurationOutput { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfigOutput; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfigOutput { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } /** The input artifacts for the test. */ export interface TestInputArtifactsOutput { /** File info */ - configFileInfo?: TestFileInfoOutput; + configFileInfo?: FileInfoOutput; /** File info */ - testScriptFileInfo?: TestFileInfoOutput; + testScriptFileInfo?: FileInfoOutput; /** File info */ - userPropFileInfo?: TestFileInfoOutput; + userPropFileInfo?: FileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfoOutput; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfoOutput; + inputArtifactsZipFileInfo?: FileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; } -/** Test file info. */ -export interface TestFileInfoOutput { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfoOutput { /** File URL. */ - readonly url?: string; + url?: string; + /** Name of the file. */ + fileName?: string; /** File type */ - readonly fileType?: FileTypeOutput; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: string; + fileType?: FileTypeOutput; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; /** Validation status of the file */ - readonly validationStatus?: FileStatusOutput; + validationStatus?: FileStatusOutput; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Test app components */ +/** Test app component */ export interface TestAppComponentsOutput { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -193,24 +175,30 @@ export interface TestAppComponentsOutput { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponentOutput { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -230,12 +218,12 @@ export interface TestServerMetricConfigOutput { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -267,12 +255,10 @@ export interface ResourceMetricOutput { /** Load test run model */ export interface TestRunOutput { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -305,9 +291,9 @@ export interface TestRunOutput { description?: string; /** The test run status. */ readonly status?: StatusOutput; - /** The test run start DateTime(RFC 3339 literal format). */ + /** The test run start DateTime(ISO 8601 literal format). */ readonly startDateTime?: string; - /** The test run end DateTime(RFC 3339 literal format). */ + /** The test run end DateTime(ISO 8601 literal format). */ readonly endDateTime?: string; /** Test run initiated time. */ readonly executedDateTime?: string; @@ -317,15 +303,11 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKindOutput; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -380,51 +362,23 @@ export interface TestRunArtifactsOutput { /** The input artifacts for the test run. */ export interface TestRunInputArtifactsOutput { /** File info */ - configFileInfo?: TestRunFileInfoOutput; + configFileInfo?: FileInfoOutput; /** File info */ - testScriptFileInfo?: TestRunFileInfoOutput; + testScriptFileInfo?: FileInfoOutput; /** File info */ - userPropFileInfo?: TestRunFileInfoOutput; + userPropFileInfo?: FileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfoOutput; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfoOutput; + inputArtifactsZipFileInfo?: FileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; -} - -/** Test run file info. */ -export interface TestRunFileInfoOutput { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileTypeOutput; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: string; - /** Validation status of the file */ - readonly validationStatus?: FileStatusOutput; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: Array; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifactsOutput { /** File info */ - resultFileInfo?: TestRunFileInfoOutput; + resultFileInfo?: FileInfoOutput; /** File info */ - logsFileInfo?: TestRunFileInfoOutput; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfoOutput; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfoOutput { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: string; + logsFileInfo?: FileInfoOutput; } /** Represents collection of metric namespaces. */ @@ -497,7 +451,7 @@ export interface TimeSeriesElementOutput { /** Represents a metric value. */ export interface MetricValueOutput { - /** The timestamp for the metric value in RFC 3339 format. */ + /** The timestamp for the metric value in ISO 8601 format. */ timestamp?: string; /** The metric value. */ value?: number; @@ -511,14 +465,8 @@ export interface DimensionValueOutput { value?: string; } -/** Metrics dimension values. */ export interface DimensionValueListOutput { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Test run app component */ @@ -531,11 +479,11 @@ export interface TestRunAppComponentsOutput { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -551,11 +499,11 @@ export interface TestRunServerMetricConfigOutput { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -563,7 +511,6 @@ export interface TestRunServerMetricConfigOutput { /** Alias for PFMetricsOutput */ export type PFMetricsOutput = - | string | "response_time_ms" | "latency" | "error" @@ -571,7 +518,6 @@ export type PFMetricsOutput = | "requests_per_sec"; /** Alias for PFAgFuncOutput */ export type PFAgFuncOutput = - | string | "count" | "percentage" | "avg" @@ -582,44 +528,33 @@ export type PFAgFuncOutput = | "min" | "max"; /** Alias for PFActionOutput */ -export type PFActionOutput = string | "continue" | "stop"; +export type PFActionOutput = "continue" | "stop"; /** Alias for PFResultOutput */ -export type PFResultOutput = string | "passed" | "undetermined" | "failed"; +export type PFResultOutput = "passed" | "undetermined" | "failed"; /** Alias for SecretTypeOutput */ -export type SecretTypeOutput = string | "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretTypeOutput = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateTypeOutput */ -export type CertificateTypeOutput = string | "AKV_CERT_URI"; +export type CertificateTypeOutput = "AKV_CERT_URI"; /** Alias for FileTypeOutput */ export type FileTypeOutput = - | string | "JMX_FILE" | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG_JSON"; + | "ADDITIONAL_ARTIFACTS"; /** Alias for FileStatusOutput */ export type FileStatusOutput = - | string | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; -/** Alias for TestKindOutput */ -export type TestKindOutput = string | "URL" | "JMX"; -/** Paged collection of Test items */ +/** Collection of tests */ export type PagedTestOutput = Paged; -/** Paged collection of TestFileInfo items */ -export type PagedTestFileInfoOutput = Paged; +/** Collection of files. */ +export type PagedFileInfoOutput = Paged; /** Alias for PFTestResultOutput */ -export type PFTestResultOutput = - | string - | "PASSED" - | "NOT_APPLICABLE" - | "FAILED"; +export type PFTestResultOutput = "PASSED" | "NOT_APPLICABLE" | "FAILED"; /** Alias for StatusOutput */ export type StatusOutput = - | string | "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" @@ -636,11 +571,10 @@ export type StatusOutput = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -/** Paged collection of TestRun items */ +/** Collection of test runs */ export type PagedTestRunOutput = Paged; /** Alias for AggregationTypeOutput */ export type AggregationTypeOutput = - | string | "Average" | "Count" | "None" @@ -650,7 +584,6 @@ export type AggregationTypeOutput = | "Percentile99"; /** Alias for MetricUnitOutput */ export type MetricUnitOutput = - | string | "NotSpecified" | "Percent" | "Count" @@ -660,12 +593,8 @@ export type MetricUnitOutput = | "BytesPerSecond" | "CountPerSecond"; /** Alias for TimeGrainOutput */ -export type TimeGrainOutput = - | string - | "PT5S" - | "PT10S" - | "PT1M" - | "PT5M" - | "PT1H"; +export type TimeGrainOutput = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; /** The response to a metrics query. */ -export type MetricsOutput = Paged; +export type PagedTimeSeriesElementOutput = Paged; +/** Paged collection of DimensionValueList items */ +export type PagedDimensionValueListOutput = Paged; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 81ba59af51..9437426616 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -8,22 +8,21 @@ import { TestAppComponents, TestServerMetricConfig, TestRun, - TimeGrain, + Interval, MetricRequestPayload, TestRunAppComponents, TestRunServerMetricConfig, } from "./models.js"; -/** The resource instance. */ +/** Load test model */ export type TestResourceMergeAndPatch = Partial; export interface LoadTestAdministrationCreateOrUpdateTestBodyParam { - /** The resource instance. */ + /** Load test model */ body: TestResourceMergeAndPatch; } export interface LoadTestAdministrationCreateOrUpdateTestMediaTypesParam { - /** This request has a JSON Merge Patch body. */ contentType: "application/merge-patch+json"; } @@ -46,10 +45,16 @@ export interface LoadTestAdministrationListTestsQueryParamProperties { * the search parameter can be Login. */ search?: string; - /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedStartTime?: Date | string; - /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedEndTime?: Date | string; + /** + * Start DateTime(ISO 8601 literal format) of the last updated time range to + * filter tests. + */ + lastModifiedStartTime?: string; + /** + * End DateTime(ISO 8601 literal format) of the last updated time range to filter + * tests. + */ + lastModifiedEndTime?: string; /** Number of results in response. */ maxpagesize?: number; } @@ -84,7 +89,6 @@ export interface LoadTestAdministrationUploadTestFileQueryParam { } export interface LoadTestAdministrationUploadTestFileMediaTypesParam { - /** Content type. */ contentType: "application/octet-stream"; } @@ -105,7 +109,6 @@ export interface LoadTestAdministrationCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestAdministrationCreateOrUpdateAppComponentsMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -125,7 +128,6 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigBodyPara } export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -135,7 +137,7 @@ export type LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters = RequestParameters; export type LoadTestAdministrationGetServerMetricsConfigParameters = RequestParameters; -export type LoadTestRunGetTestRunParameters = RequestParameters; +export type LoadTestRunDeleteTestRunParameters = RequestParameters; /** The resource instance. */ export type TestRunResourceMergeAndPatch = Partial; @@ -168,7 +170,8 @@ export type LoadTestRunCreateOrUpdateTestRunParameters = LoadTestRunCreateOrUpdateTestRunMediaTypesParam & LoadTestRunCreateOrUpdateTestRunBodyParam & RequestParameters; -export type LoadTestRunDeleteTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunFileParameters = RequestParameters; export interface LoadTestRunListTestRunsQueryParamProperties { /** @@ -184,10 +187,10 @@ export interface LoadTestRunListTestRunsQueryParamProperties { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionFrom?: Date | string; - /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionTo?: Date | string; + /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionFrom?: string; + /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionTo?: string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -200,17 +203,16 @@ export interface LoadTestRunListTestRunsQueryParam { export type LoadTestRunListTestRunsParameters = LoadTestRunListTestRunsQueryParam & RequestParameters; -export type LoadTestRunGetTestRunFileParameters = RequestParameters; -export type LoadTestRunStopParameters = RequestParameters; +export type LoadTestRunStopTestRunParameters = RequestParameters; export type LoadTestRunListMetricNamespacesParameters = RequestParameters; export interface LoadTestRunListMetricDefinitionsQueryParamProperties { /** Metric namespace to query metric definitions for. */ - metricNamespace: string; + metricNamespace?: string; } export interface LoadTestRunListMetricDefinitionsQueryParam { - queryParameters: LoadTestRunListMetricDefinitionsQueryParamProperties; + queryParameters?: LoadTestRunListMetricDefinitionsQueryParamProperties; } export type LoadTestRunListMetricDefinitionsParameters = @@ -218,24 +220,27 @@ export type LoadTestRunListMetricDefinitionsParameters = export interface LoadTestRunListMetricsBodyParam { /** Metric dimension filter */ - body?: MetricRequestPayload; + body: MetricRequestPayload; } export interface LoadTestRunListMetricsQueryParamProperties { /** The aggregation */ aggregation?: string; - /** Metric name */ - metricname: string; /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; /** Metric namespace to query metric definitions for. */ - metricNamespace: string; - /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ - timespan: string; + metricNamespace?: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } export interface LoadTestRunListMetricsQueryParam { - queryParameters: LoadTestRunListMetricsQueryParamProperties; + queryParameters?: LoadTestRunListMetricsQueryParamProperties; } export type LoadTestRunListMetricsParameters = @@ -244,14 +249,17 @@ export type LoadTestRunListMetricsParameters = RequestParameters; export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { - /** Metric name */ - metricname: string; /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; /** Metric namespace to query metric definitions for. */ metricNamespace: string; - /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ - timespan: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } export interface LoadTestRunListMetricDimensionValuesQueryParam { @@ -270,7 +278,6 @@ export interface LoadTestRunCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestRunCreateOrUpdateAppComponentsMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -289,7 +296,6 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam { } export interface LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -297,4 +303,5 @@ export type LoadTestRunCreateOrUpdateServerMetricsConfigParameters = LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam & LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam & RequestParameters; -export type LoadTestRunGetServerMetricsConfigParameters = RequestParameters; +export type LoadTestRunTestRunListServerMetricsConfigParameters = + RequestParameters; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts new file mode 100644 index 0000000000..19a90195ba --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Client, HttpResponse } from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { + CancelOnProgress, + CreateHttpPollerOptions, + RunningOperation, + OperationResponse, + OperationState, + createHttpPoller, +} from "@azure/core-lro"; +import { + LoadTestRunCreateOrUpdateTestRun200Response, + LoadTestRunCreateOrUpdateTestRun201Response, + LoadTestRunCreateOrUpdateTestRunDefaultResponse, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, +} from "./responses.js"; + +/** + * A simple poller that can be used to poll a long running operation. + */ +export interface SimplePollerLike< + TState extends OperationState, + TResult, +> { + /** + * Returns true if the poller has finished polling. + */ + isDone(): boolean; + /** + * Returns the state of the operation. + */ + getOperationState(): TState; + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult(): TResult | undefined; + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + */ + poll(options?: { abortSignal?: AbortSignalLike }): Promise; + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + pollUntilDone(pollOptions?: { + abortSignal?: AbortSignalLike; + }): Promise; + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback: (state: TState) => void): CancelOnProgress; + + /** + * Returns a promise that could be used for serialized version of the poller's operation + * by invoking the operation's serialize method. + */ + serialize(): Promise; + + /** + * Wait the poller to be submitted. + */ + submitted(): Promise; + + /** + * Returns a string representation of the poller's operation. Similar to serialize but returns a string. + * @deprecated Use serialize() instead. + */ + toString(): string; + + /** + * Stops the poller from continuing to poll. Please note this will only stop the client-side polling + * @deprecated Use abortSignal to stop polling instead. + */ + stopPolling(): void; + + /** + * Returns true if the poller is stopped. + * @deprecated Use abortSignal status to track this instead. + */ + isStopped(): boolean; +} + +/** + * Helper function that builds a Poller object to help polling a long running operation. + * @param client - Client to use for sending the request to get additional pages. + * @param initialResponse - The initial response. + * @param options - Options to set a resume state or custom polling interval. + * @returns - A poller object to poll for operation state updates and eventually get the final response. + */ +export async function getLongRunningPoller< + TResult extends + | LoadTestRunCreateOrUpdateTestRunLogicalResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, +>( + client: Client, + initialResponse: + | LoadTestRunCreateOrUpdateTestRun200Response + | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, + options?: CreateHttpPollerOptions>, +): Promise, TResult>>; +export async function getLongRunningPoller( + client: Client, + initialResponse: TResult, + options: CreateHttpPollerOptions> = {}, +): Promise, TResult>> { + const abortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + // In the case of Rest Clients we are building the LRO poller object from a response that's the reason + // we are not triggering the initial request here, just extracting the information from the + // response we were provided. + return getLroResponse(initialResponse); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { abortSignal?: AbortSignalLike }, + ) => { + // This is the callback that is going to be called to poll the service + // to get the latest status. We use the client provided and the polling path + // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location + // depending on the lro pattern that the service implements. If non is provided we default to the initial path. + function abortListener(): void { + abortController.abort(); + } + const inputAbortSignal = pollOptions?.abortSignal; + const abortSignal = abortController.signal; + if (inputAbortSignal?.aborted) { + abortController.abort(); + } else if (!abortSignal.aborted) { + inputAbortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client + .pathUnchecked(path ?? initialResponse.request.url) + .get({ abortSignal }); + } finally { + inputAbortSignal?.removeEventListener("abort", abortListener); + } + const lroResponse = getLroResponse(response as TResult); + lroResponse.rawResponse.headers["x-ms-original-url"] = + initialResponse.request.url; + return lroResponse; + }, + }; + + options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; + const httpPoller = createHttpPoller(poller, options); + const simplePoller: SimplePollerLike, TResult> = { + isDone() { + return httpPoller.isDone; + }, + isStopped() { + return abortController.signal.aborted; + }, + getOperationState() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + return httpPoller.operationState; + }, + getResult() { + return httpPoller.result; + }, + toString() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + return JSON.stringify({ + state: httpPoller.operationState, + }); + }, + stopPolling() { + abortController.abort(); + }, + onProgress: httpPoller.onProgress, + poll: httpPoller.poll, + pollUntilDone: httpPoller.pollUntilDone, + serialize: httpPoller.serialize, + submitted: httpPoller.submitted, + }; + return simplePoller; +} + +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResult, +): OperationResponse { + if (Number.isNaN(response.status)) { + throw new TypeError( + `Status code of the response is not a number. Value: ${response.status}`, + ); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index d8f4cd2d58..2c79e0b52c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,17 +6,16 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - FileTypeOutput, - FileStatusOutput, - PagedTestFileInfoOutput, + FileInfoOutput, + PagedFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, - MetricsOutput, - DimensionValueListOutput, + PagedTimeSeriesElementOutput, + PagedDimensionValueListOutput, TestRunAppComponentsOutput, TestRunServerMetricConfigOutput, } from "./outputModels.js"; @@ -107,13 +106,7 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: FileInfoOutput; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -132,13 +125,7 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: FileInfoOutput; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -175,7 +162,7 @@ export interface LoadTestAdministrationDeleteTestFileDefaultResponse export interface LoadTestAdministrationListTestFiles200Response extends HttpResponse { status: "200"; - body: PagedTestFileInfoOutput; + body: PagedFileInfoOutput; } export interface LoadTestAdministrationListTestFilesDefaultHeaders { @@ -284,21 +271,25 @@ export interface LoadTestAdministrationGetServerMetricsConfigDefaultResponse LoadTestAdministrationGetServerMetricsConfigDefaultHeaders; } -/** The request has succeeded. */ -export interface LoadTestRunGetTestRun200Response extends HttpResponse { - status: "200"; - body: TestRunOutput; +/** There is no content to send for this request, but the headers may be useful. */ +export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { + status: "204"; } -export interface LoadTestRunGetTestRunDefaultHeaders { +export interface LoadTestRunDeleteTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; +} + +export interface LoadTestRunCreateOrUpdateTestRun200Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; } /** The request has succeeded. */ @@ -306,6 +297,12 @@ export interface LoadTestRunCreateOrUpdateTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; + headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun200Headers; +} + +export interface LoadTestRunCreateOrUpdateTestRun201Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; } /** The request has succeeded and a new resource has been created as a result. */ @@ -313,6 +310,7 @@ export interface LoadTestRunCreateOrUpdateTestRun201Response extends HttpResponse { status: "201"; body: TestRunOutput; + headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun201Headers; } export interface LoadTestRunCreateOrUpdateTestRunDefaultHeaders { @@ -327,77 +325,79 @@ export interface LoadTestRunCreateOrUpdateTestRunDefaultResponse headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRunDefaultHeaders; } -/** There is no content to send for this request, but the headers may be useful. */ -export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { - status: "204"; +/** The final response for long-running CreateOrUpdateTestRun operation */ +export interface LoadTestRunCreateOrUpdateTestRunLogicalResponse + extends HttpResponse { + status: "200"; + body: TestRunOutput; } -export interface LoadTestRunDeleteTestRunDefaultHeaders { +/** The request has succeeded. */ +export interface LoadTestRunGetTestRun200Response extends HttpResponse { + status: "200"; + body: TestRunOutput; +} + +export interface LoadTestRunGetTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunListTestRuns200Response extends HttpResponse { +export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: PagedTestRunOutput; + body: FileInfoOutput; } -export interface LoadTestRunListTestRunsDefaultHeaders { +export interface LoadTestRunGetTestRunFileDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { +export interface LoadTestRunListTestRuns200Response extends HttpResponse { status: "200"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: PagedTestRunOutput; } -export interface LoadTestRunGetTestRunFileDefaultHeaders { +export interface LoadTestRunListTestRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { +export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunStop200Response extends HttpResponse { +export interface LoadTestRunStopTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; } -export interface LoadTestRunStopDefaultHeaders { +export interface LoadTestRunStopTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunStopDefaultResponse extends HttpResponse { +export interface LoadTestRunStopTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunStopDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunStopTestRunDefaultHeaders; } /** The request has succeeded. */ @@ -441,7 +441,7 @@ export interface LoadTestRunListMetricDefinitionsDefaultResponse /** The request has succeeded. */ export interface LoadTestRunListMetrics200Response extends HttpResponse { status: "200"; - body: MetricsOutput; + body: PagedTimeSeriesElementOutput; } export interface LoadTestRunListMetricsDefaultHeaders { @@ -459,7 +459,7 @@ export interface LoadTestRunListMetricsDefaultResponse extends HttpResponse { export interface LoadTestRunListMetricDimensionValues200Response extends HttpResponse { status: "200"; - body: DimensionValueListOutput; + body: PagedDimensionValueListOutput; } export interface LoadTestRunListMetricDimensionValuesDefaultHeaders { @@ -547,20 +547,21 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse } /** The request has succeeded. */ -export interface LoadTestRunGetServerMetricsConfig200Response +export interface LoadTestRunTestRunListServerMetricsConfig200Response extends HttpResponse { status: "200"; body: TestRunServerMetricConfigOutput; } -export interface LoadTestRunGetServerMetricsConfigDefaultHeaders { +export interface LoadTestRunTestRunListServerMetricsConfigDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetServerMetricsConfigDefaultResponse +export interface LoadTestRunTestRunListServerMetricsConfigDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetServerMetricsConfigDefaultHeaders; + headers: RawHttpHeaders & + LoadTestRunTestRunListServerMetricsConfigDefaultHeaders; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index de60e781ee..53a26b11df 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. export { - createOrUpdateTestRun, + testRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -20,5 +20,5 @@ export { export { createTestRunOperations, TestRunOperationsClientOptions, - LoadTestServiceContext, + AzureLoadTestingContext, } from "./testRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 43442bfd65..4d72bc85cd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -1,9 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { getLongRunningPoller } from "./pollingHelpers.js"; +import { PollerLike, OperationState } from "@azure/core-lro"; import { - FileType, - FileStatus, + passFailCriteriaSerializer, + secretSerializer, + certificateMetadataSerializer, + loadTestConfigurationSerializer, + appComponentSerializer, + resourceMetricSerializer, + dimensionFilterSerializer, + FileInfo, TestRun, TestRunAppComponents, TestRunServerMetricConfig, @@ -11,14 +19,16 @@ import { MetricDefinitionCollection, MetricNamespaceCollection, MetricRequestPayload, - Metrics, TimeSeriesElement, - PagedTestRun, + _PagedDimensionValueList, + _PagedTestRun, + _PagedTimeSeriesElement, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, + AzureLoadTestingContext as Client, LoadTestRunCreateOrUpdateAppComponents200Response, LoadTestRunCreateOrUpdateAppComponents201Response, LoadTestRunCreateOrUpdateAppComponentsDefaultResponse, @@ -28,12 +38,11 @@ import { LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunDeleteTestRun204Response, LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunGetAppComponents200Response, LoadTestRunGetAppComponentsDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, LoadTestRunGetTestRun200Response, LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, @@ -48,15 +57,19 @@ import { LoadTestRunListMetricsDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestServiceContext as Client, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "../../rest/index.js"; import { StreamableMethod, operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -72,15 +85,16 @@ import { StopTestRunOptionalParams, } from "../models/options.js"; -export function _createOrUpdateTestRunSend( +export function _testRunSend( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunCreateOrUpdateTestRunLogicalResponse > { return context .path("/test-runs/{testRunId}", testRunId) @@ -90,92 +104,45 @@ export function _createOrUpdateTestRunSend( (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, body: { - passFailCriteria: !body.passFailCriteria - ? undefined - : { passFailMetrics: body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !body.autoStopCriteria - ? undefined - : { - autoStopDisabled: body.autoStopCriteria?.["autoStopDisabled"], - errorRate: body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: body["secrets"], - certificate: !body.certificate - ? undefined - : { - value: body.certificate?.["value"], - type: body.certificate?.["type"], - name: body.certificate?.["name"], - }, - environmentVariables: body["environmentVariables"], - loadTestConfiguration: !body.loadTestConfiguration - ? undefined - : { - engineInstances: body.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: body.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: body.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !body.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - }, - displayName: body["displayName"], - testId: body["testId"], - description: body["description"], + passFailCriteria: !resource.passFailCriteria + ? resource.passFailCriteria + : passFailCriteriaSerializer(resource.passFailCriteria), + secrets: !resource.secrets + ? resource.secrets + : (serializeRecord(resource.secrets as any, secretSerializer) as any), + certificate: !resource.certificate + ? resource.certificate + : certificateMetadataSerializer(resource.certificate), + environmentVariables: !resource.environmentVariables + ? resource.environmentVariables + : (serializeRecord(resource.environmentVariables as any) as any), + loadTestConfiguration: !resource.loadTestConfiguration + ? resource.loadTestConfiguration + : loadTestConfigurationSerializer(resource.loadTestConfiguration), + displayName: resource["displayName"], + testId: resource["testId"], + description: resource["description"], }, }); } -export async function _createOrUpdateTestRunDeserialize( +export async function _testRunDeserialize( result: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunCreateOrUpdateTestRunLogicalResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); } + result = result as LoadTestRunCreateOrUpdateTestRunLogicalResponse; return { testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -205,14 +172,6 @@ export async function _createOrUpdateTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -237,22 +196,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -264,22 +218,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -291,22 +240,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -318,23 +262,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -344,34 +282,6 @@ export async function _createOrUpdateTestRunDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -382,13 +292,10 @@ export async function _createOrUpdateTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -400,22 +307,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -427,22 +329,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -450,22 +347,6 @@ export async function _createOrUpdateTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, }, }, testResult: result.body["testResult"], @@ -474,50 +355,32 @@ export async function _createOrUpdateTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create and start a new test run with the given test run Id. */ -export async function createOrUpdateTestRun( +/** Create and start a new test run with the given name. */ +export function testRun( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateTestRunSend( - context, - testRunId, - body, - options, - ); - return _createOrUpdateTestRunDeserialize(result); + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, +): PollerLike, TestRun> { + return getLongRunningPoller(context, _testRunDeserialize, { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _testRunSend(context, testRunId, resource, options), + }) as PollerLike, TestRun>; } export function _createOrUpdateAppComponentsSend( @@ -536,7 +399,12 @@ export function _createOrUpdateAppComponentsSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { components: body["components"] }, + body: { + components: serializeRecord( + body.components as any, + appComponentSerializer, + ) as any, + }, }); } @@ -553,20 +421,14 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Add an app component to a test run by providing the resource Id, name and type. */ +/** Associate an app component (collection of azure resources) to a test run */ export async function createOrUpdateAppComponents( context: Client, testRunId: string, @@ -600,7 +462,14 @@ export function _createOrUpdateServerMetricsConfigSend( ...operationOptionsToRequestParameters(options), contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { metrics: body["metrics"] }, + body: { + metrics: !body.metrics + ? body.metrics + : (serializeRecord( + body.metrics as any, + resourceMetricSerializer, + ) as any), + }, }); } @@ -617,15 +486,9 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -672,7 +535,7 @@ export async function _deleteTestRunDeserialize( return; } -/** Delete an existing load test run by providing the testRunId. */ +/** Delete a test run by its name. */ export async function deleteTestRun( context: Client, testRunId: string, @@ -707,15 +570,9 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -738,8 +595,8 @@ export function _getServerMetricsConfigSend( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod< - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse > { return context .path("/test-runs/{testRunId}/server-metrics-config", testRunId) @@ -748,8 +605,8 @@ export function _getServerMetricsConfigSend( export async function _getServerMetricsConfigDeserialize( result: - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse, + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -758,20 +615,14 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get associated server metrics configuration for the given test run. */ +/** List server metrics configuration for the given test run. */ export async function getServerMetricsConfig( context: Client, testRunId: string, @@ -807,14 +658,6 @@ export async function _getTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -844,14 +687,6 @@ export async function _getTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -876,22 +711,17 @@ export async function _getTestRunDeserialize( ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -903,22 +733,17 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -930,22 +755,17 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -957,23 +777,17 @@ export async function _getTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -983,34 +797,6 @@ export async function _getTestRunDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1021,13 +807,10 @@ export async function _getTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -1039,22 +822,17 @@ export async function _getTestRunDeserialize( ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1066,22 +844,17 @@ export async function _getTestRunDeserialize( ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1089,22 +862,6 @@ export async function _getTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, }, }, testResult: result.body["testResult"], @@ -1113,37 +870,20 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get test run details by test run Id. */ +/** Get test run details by name. */ export async function getTestRun( context: Client, testRunId: string, @@ -1171,24 +911,16 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -1200,13 +932,7 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _getTestRunFileSend( context, testRunId, @@ -1220,9 +946,7 @@ export function _listMetricDimensionValuesSend( context: Client, testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDimensionValues200Response @@ -1237,10 +961,10 @@ export function _listMetricDimensionValuesSend( .get({ ...operationOptionsToRequestParameters(options), queryParameters: { - metricname: metricname, interval: options?.interval, + metricName: options?.metricName, metricNamespace: metricNamespace, - timespan: timespan, + timespan: options?.timespan, }, }); } @@ -1249,44 +973,43 @@ export async function _listMetricDimensionValuesDeserialize( result: | LoadTestRunListMetricDimensionValues200Response | LoadTestRunListMetricDimensionValuesDefaultResponse, -): Promise { +): Promise<_PagedDimensionValueList> { if (isUnexpected(result)) { throw createRestError(result); } return { - name: result.body["name"], - value: result.body["value"], + value: result.body["value"].map((p) => ({ value: p["value"] })), nextLink: result.body["nextLink"], }; } /** List the dimension values for the given metric dimension name. */ -export async function listMetricDimensionValues( +export function listMetricDimensionValues( context: Client, testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMetricDimensionValuesSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testRunId, - name, - metricname, - metricNamespace, - timespan, - options, + () => + _listMetricDimensionValuesSend( + context, + testRunId, + name, + metricNamespace, + options, + ), + _listMetricDimensionValuesDeserialize, + { itemName: "value", nextLinkName: "nextLink" }, ); - return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( context: Client, testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response @@ -1296,7 +1019,7 @@ export function _listMetricDefinitionsSend( .path("/test-runs/{testRunId}/metric-definitions", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: metricNamespace }, + queryParameters: { metricNamespace: options?.metricNamespace }, }); } @@ -1338,15 +1061,9 @@ export async function _listMetricDefinitionsDeserialize( export async function listMetricDefinitions( context: Client, testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _listMetricDefinitionsSend( - context, - testRunId, - metricNamespace, - options, - ); + const result = await _listMetricDefinitionsSend(context, testRunId, options); return _listMetricDefinitionsDeserialize(result); } @@ -1393,10 +1110,7 @@ export async function listMetricNamespaces( export function _listMetricsSend( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse @@ -1407,23 +1121,17 @@ export function _listMetricsSend( ...operationOptionsToRequestParameters(options), queryParameters: { aggregation: options?.aggregation, - metricname: metricname, interval: options?.interval, - metricNamespace: metricNamespace, - timespan: timespan, + metricName: options?.metricName, + metricNamespace: options?.metricNamespace, + timespan: options?.timespan, + }, + body: { + filters: + body["filters"] === undefined + ? body["filters"] + : body["filters"].map(dimensionFilterSerializer), }, - body: - body === undefined - ? body - : { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map((p) => ({ - name: p["name"], - values: p["values"], - })), - }, }); } @@ -1431,7 +1139,7 @@ export async function _listMetricsDeserialize( result: | LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse, -): Promise { +): Promise<_PagedTimeSeriesElement> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1442,10 +1150,7 @@ export async function _listMetricsDeserialize( p["data"] === undefined ? p["data"] : p["data"].map((p) => ({ - timestamp: - p["timestamp"] !== undefined - ? new Date(p["timestamp"]) - : undefined, + timestamp: p["timestamp"], value: p["value"], })), dimensionValues: @@ -1464,24 +1169,12 @@ export async function _listMetricsDeserialize( export function listMetrics( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => - _listMetricsSend( - context, - testRunId, - metricname, - metricNamespace, - timespan, - body, - options, - ), + () => _listMetricsSend(context, testRunId, body, options), _listMetricsDeserialize, { itemName: "value", nextLinkName: "nextLink" }, ); @@ -1501,8 +1194,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom?.toISOString(), - executionTo: options?.executionTo?.toISOString(), + executionFrom: options?.executionFrom, + executionTo: options?.executionTo, status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1513,7 +1206,7 @@ export async function _listTestRunsDeserialize( result: | LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse, -): Promise { +): Promise<_PagedTestRun> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1524,14 +1217,6 @@ export async function _listTestRunsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1560,14 +1245,6 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1592,13 +1269,13 @@ export async function _listTestRunsDeserialize( ?.configFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "url" + ], fileName: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileName" ], - url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "url" - ], fileType: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileType" @@ -1606,12 +1283,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1625,12 +1297,12 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "fileName" ], - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "fileType" @@ -1638,12 +1310,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -1657,12 +1324,12 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileName" ], - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileType" @@ -1670,12 +1337,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1689,25 +1351,17 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1717,36 +1371,6 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] === undefined @@ -1754,13 +1378,10 @@ export async function _listTestRunsDeserialize( : p.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1773,13 +1394,13 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo ? undefined : { + url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "url" + ], fileName: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileName" ], - url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "url" - ], fileType: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileType" @@ -1787,12 +1408,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1805,13 +1421,13 @@ export async function _listTestRunsDeserialize( logsFileInfo: !p.testArtifacts?.outputArtifacts?.logsFileInfo ? undefined : { + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" + ], fileName: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileName" ], - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], fileType: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileType" @@ -1819,12 +1435,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1834,22 +1445,6 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, - artifactsContainerInfo: !p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo - ? undefined - : { - url: p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, }, }, testResult: p["testResult"], @@ -1858,37 +1453,22 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, - executedDateTime: - p["executedDateTime"] !== undefined - ? new Date(p["executedDateTime"]) - : undefined, + startDateTime: p["startDateTime"], + endDateTime: p["endDateTime"], + executedDateTime: p["executedDateTime"], portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - kind: p["kind"], - publicIPDisabled: p["publicIPDisabled"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, + createdDateTime: p["createdDateTime"], createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: p["lastModifiedDateTime"], lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], }; } -/** Get all test runs for the given filters. */ +/** Get all test runs with given filters */ export function listTestRuns( context: Client, options: ListTestRunsOptionalParams = { requestOptions: {} }, @@ -1905,13 +1485,19 @@ export function _stopTestRunSend( context: Client, testRunId: string, options: StopTestRunOptionalParams = { requestOptions: {} }, -): StreamableMethod { +): StreamableMethod< + LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse +> { return context - .path("/test-runs/{testRunId}:stopTestRun", testRunId) + .path("/test-runs/{testRunId}:stop", testRunId) .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestRunDeserialize(result): Promise { +export async function _stopTestRunDeserialize( + result: + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse, +): Promise { if (isUnexpected(result)) { throw createRestError(result); } @@ -1921,14 +1507,6 @@ export async function _stopTestRunDeserialize(result): Promise { passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -1958,14 +1536,6 @@ export async function _stopTestRunDeserialize(result): Promise { result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1990,22 +1560,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -2017,22 +1582,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -2044,22 +1604,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -2071,23 +1626,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -2097,34 +1646,6 @@ export async function _stopTestRunDeserialize(result): Promise { "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -2135,13 +1656,10 @@ export async function _stopTestRunDeserialize(result): Promise { : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], })), @@ -2153,22 +1671,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -2180,22 +1693,17 @@ export async function _stopTestRunDeserialize(result): Promise { ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -2203,22 +1711,6 @@ export async function _stopTestRunDeserialize(result): Promise { result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, }, }, testResult: result.body["testResult"], @@ -2227,37 +1719,20 @@ export async function _stopTestRunDeserialize(result): Promise { testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Stop test run by test run Id. */ +/** Stop test run by name. */ export async function stopTestRun( context: Client, testRunId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts new file mode 100644 index 0000000000..d4d54d4e32 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + PollerLike, + OperationState, + ResourceLocationConfig, + RunningOperation, + createHttpPoller, + OperationResponse, +} from "@azure/core-lro"; + +import { + Client, + PathUncheckedResponse, + createRestError, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { isUnexpected } from "../../rest/index.js"; + +export interface GetLongRunningPollerOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * The potential location of the result of the LRO if specified by the LRO extension in the swagger. + */ + resourceLocationConfig?: ResourceLocationConfig; + /** + * The original url of the LRO + * Should not be null when restoreFrom is set + */ + initialRequestUrl?: string; + /** + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. + */ + restoreFrom?: string; + /** + * The function to get the initial response + */ + getInitialResponse?: () => PromiseLike; +} +export function getLongRunningPoller< + TResponse extends PathUncheckedResponse, + TResult = void, +>( + client: Client, + processResponseBody: (result: TResponse) => Promise, + options: GetLongRunningPollerOptions, +): PollerLike, TResult> { + const { restoreFrom, getInitialResponse } = options; + if (!restoreFrom && !getInitialResponse) { + throw new Error( + "Either restoreFrom or getInitialResponse must be specified", + ); + } + let initialResponse: TResponse | undefined = undefined; + const pollAbortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + if (!getInitialResponse) { + throw new Error( + "getInitialResponse is required when initializing a new poller", + ); + } + initialResponse = await getInitialResponse(); + return getLroResponse(initialResponse); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { + abortSignal?: AbortSignalLike; + }, + ) => { + // The poll request would both listen to the user provided abort signal and the poller's own abort signal + function abortListener(): void { + pollAbortController.abort(); + } + const abortSignal = pollAbortController.signal; + if (options.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (pollOptions?.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (!abortSignal.aborted) { + options.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + pollOptions?.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client.pathUnchecked(path).get({ abortSignal }); + } finally { + options.abortSignal?.removeEventListener("abort", abortListener); + pollOptions?.abortSignal?.removeEventListener("abort", abortListener); + } + if (options.initialRequestUrl || initialResponse) { + response.headers["x-ms-original-url"] = + options.initialRequestUrl ?? initialResponse!.request.url; + } + + return getLroResponse(response as TResponse); + }, + }; + return createHttpPoller(poller, { + intervalInMs: options?.updateIntervalInMs, + resourceLocationConfig: options?.resourceLocationConfig, + restoreFrom: options?.restoreFrom, + processResult: (result: unknown) => { + return processResponseBody(result as TResponse); + }, + }); +} +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @param deserializeFn - deserialize function to convert Rest response to modular output + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResponse, +): OperationResponse { + if (isUnexpected(response as PathUncheckedResponse)) { + throw createRestError(response); + } + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index a4b3912b22..df5682bd18 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -3,21 +3,22 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { LoadTestServiceContext } from "../../rest/index.js"; +import { AzureLoadTestingContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; +/** Optional parameters for the client. */ export interface TestRunOperationsClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; } -export { LoadTestServiceContext } from "../../rest/index.js"; +export { AzureLoadTestingContext } from "../../rest/index.js"; export function createTestRunOperations( endpointParam: string, credential: TokenCredential, options: TestRunOperationsClientOptions = {}, -): LoadTestServiceContext { +): AzureLoadTestingContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index 9a6a3e5cf2..d5ab0cdb96 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -5,6 +5,7 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperationsClient.js"; +export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Test, PassFailCriteria, @@ -13,7 +14,6 @@ export { PFAgFunc, PFAction, PFResult, - AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -21,10 +21,9 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - TestFileInfo, + FileInfo, FileType, FileStatus, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -35,14 +34,12 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -50,18 +47,15 @@ export { AggregationType, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - Metrics, TimeSeriesElement, MetricValue, DimensionValue, - PagedTestFileInfo, - PagedTest, - PagedTestRun, - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index bb92ef1f85..cfa3ac60f4 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -9,7 +9,6 @@ export { PFAgFunc, PFAction, PFResult, - AutoStopCriteria, Secret, SecretType, CertificateMetadata, @@ -17,10 +16,9 @@ export { LoadTestConfiguration, OptionalLoadTestConfig, TestInputArtifacts, - TestFileInfo, + FileInfo, FileType, FileStatus, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -31,14 +29,12 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, PFTestResult, Status, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -46,20 +42,17 @@ export { AggregationType, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, DimensionFilter, - Metrics, TimeSeriesElement, MetricValue, DimensionValue, - PagedTestFileInfo, - PagedTest, - PagedTestRun, } from "./models.js"; export { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index 27018ab1f3..3a7491a214 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -1,12 +1,30 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model. */ +import { serializeRecord } from "../../helpers/serializerHelpers.js"; +import { + Test as TestRest, + PassFailCriteria as PassFailCriteriaRest, + PassFailMetric as PassFailMetricRest, + Secret as SecretRest, + CertificateMetadata as CertificateMetadataRest, + LoadTestConfiguration as LoadTestConfigurationRest, + OptionalLoadTestConfig as OptionalLoadTestConfigRest, + TestAppComponents as TestAppComponentsRest, + AppComponent as AppComponentRest, + TestServerMetricConfig as TestServerMetricConfigRest, + ResourceMetric as ResourceMetricRest, + TestRun as TestRunRest, + TestRunAppComponents as TestRunAppComponentsRest, + TestRunServerMetricConfig as TestRunServerMetricConfigRest, + MetricRequestPayload as MetricRequestPayloadRest, + DimensionFilter as DimensionFilterRest, +} from "../../rest/index.js"; + +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,48 +33,80 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testSerializer(item: Test): TestRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + }; +} + /** Pass fail criteria for a test. */ export interface PassFailCriteria { /** Map of id and pass fail metrics { id : pass fail metrics }. */ passFailMetrics?: Record; } +export function passFailCriteriaSerializer( + item: PassFailCriteria, +): PassFailCriteriaRest { + return { + passFailMetrics: !item.passFailMetrics + ? item.passFailMetrics + : (serializeRecord( + item.passFailMetrics as any, + passFailMetricSerializer, + ) as any), + }; +} + /** Pass fail metric */ export interface PassFailMetric { /** The client metric on which the criteria should be applied. */ @@ -85,28 +135,41 @@ export interface PassFailMetric { readonly result?: PFResult; } -/** Metrics for pass/fail criteria. */ -/** "response_time_ms", "latency", "error", "requests", "requests_per_sec" */ -export type PFMetrics = string; -/** Aggregation functions for pass/fail criteria. */ -/** "count", "percentage", "avg", "p50", "p90", "p95", "p99", "min", "max" */ -export type PFAgFunc = string; -/** Action to take on failure of pass/fail criteria. */ -/** "continue", "stop" */ -export type PFAction = string; -/** Pass/fail criteria result. */ -/** "passed", "undetermined", "failed" */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} +export function passFailMetricSerializer( + item: PassFailMetric, +): PassFailMetricRest { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + }; +} + +/** Type of PFMetrics */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Type of PFAgFunc */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; +/** Type of PFAction */ +export type PFAction = "continue" | "stop"; +/** Type of PFResult */ +export type PFResult = "passed" | "undetermined" | "failed"; /** Secret */ export interface Secret { @@ -116,9 +179,15 @@ export interface Secret { type?: SecretType; } -/** Types of secrets supported. */ -/** "AKV_SECRET_URI", "SECRET_VALUE" */ -export type SecretType = string; +export function secretSerializer(item: Secret): SecretRest { + return { + value: item["value"], + type: item["type"], + }; +} + +/** Type of SecretType */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ export interface CertificateMetadata { @@ -130,13 +199,25 @@ export interface CertificateMetadata { name?: string; } -/** Types of certificates supported. */ -/** "AKV_CERT_URI" */ -export type CertificateType = string; +export function certificateMetadataSerializer( + item: CertificateMetadata, +): CertificateMetadataRest { + return { + value: item["value"], + type: item["type"], + name: item["name"], + }; +} + +/** Type of CertificateType */ +export type CertificateType = "AKV_CERT_URI"; -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -150,69 +231,90 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; } -/** Configuration for quick load test */ +export function loadTestConfigurationSerializer( + item: LoadTestConfiguration, +): LoadTestConfigurationRest { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item.optionalLoadTestConfig + ? item.optionalLoadTestConfig + : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + }; +} + +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } +export function optionalLoadTestConfigSerializer( + item: OptionalLoadTestConfig, +): OptionalLoadTestConfigRest { + return { + endpointUrl: item["endpointUrl"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; + readonly additionalFileInfo?: FileInfo[]; } -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfo { /** File URL. */ - readonly url?: string; + url?: string; + /** Name of the file. */ + fileName?: string; /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; /** Validation status of the file */ - readonly validationStatus?: FileStatus; + validationStatus?: FileStatus; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Types of file supported. */ -/** "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG_JSON" */ -export type FileType = string; -/** File status. */ -/** "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" */ -export type FileStatus = string; -/** Test kind */ -/** "URL", "JMX" */ -export type TestKind = string; +/** Type of FileType */ +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +/** Type of FileStatus */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; -/** Test app components */ +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -222,24 +324,41 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +export function testAppComponentsSerializer( + item: TestAppComponents, +): TestAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -250,6 +369,15 @@ export interface AppComponent { kind?: string; } +export function appComponentSerializer(item: AppComponent): AppComponentRest { + return { + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + kind: item["kind"], + }; +} + /** Test server metrics configuration */ export interface TestServerMetricConfig { /** Test identifier */ @@ -259,17 +387,27 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testServerMetricConfigSerializer( + item: TestServerMetricConfig, +): TestServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + /** * Associated metric definition for particular metrics of the azure resource ( * Refer : @@ -294,18 +432,45 @@ export interface ResourceMetric { resourceType: string; } -/** Azure Load Testing API versions. */ -/** */ -export type APIVersions = "2022-11-01" | "2023-04-01-preview"; +export function resourceMetricSerializer( + item: ResourceMetric, +): ResourceMetricRest { + return { + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +/** Collection of files. */ +export interface _PagedFileInfo { + /** The FileInfo items on this page */ + value: FileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Collection of tests */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Type of APIVersions */ +export type APIVersions = "2022-11-01"; /** Load test run model */ export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -338,32 +503,51 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; + /** The test run start DateTime(ISO 8601 literal format). */ + readonly startDateTime?: string; + /** The test run end DateTime(ISO 8601 literal format). */ + readonly endDateTime?: string; /** Test run initiated time. */ - readonly executedDateTime?: Date; + readonly executedDateTime?: string; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testRunSerializer(item: TestRun): TestRunRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + }; +} + /** Error details if there is any failure in load test run */ export interface ErrorDetails { /** Error details in case test run was not successfully run. */ @@ -413,59 +597,45 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: FileInfo[]; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Test result based on pass/fail criteria. */ -/** "PASSED", "NOT_APPLICABLE", "FAILED" */ -export type PFTestResult = string; -/** Test run status. */ -/** "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" */ -export type Status = string; + logsFileInfo?: FileInfo; +} + +/** Type of PFTestResult */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Type of Status */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; /** Test run app component */ export interface TestRunAppComponents { @@ -477,16 +647,27 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +export function testRunAppComponentsSerializer( + item: TestRunAppComponents, +): TestRunAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + /** Test run server metrics configuration */ export interface TestRunServerMetricConfig { /** Test run identifier */ @@ -497,28 +678,31 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** Time Grain */ -/** "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ -export type TimeGrain = string; +export function testRunServerMetricConfigSerializer( + item: TestRunServerMetricConfig, +): TestRunServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + +/** Type of Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; -/** Metrics dimension values. */ export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Represents collection of metric definitions. */ @@ -558,12 +742,25 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -/** "Average", "Count", "None", "Total", "Percentile90", "Percentile95", "Percentile99" */ -export type AggregationType = string; -/** Metric unit. */ -/** "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" */ -export type MetricUnit = string; +/** Type of AggregationType */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile90" + | "Percentile95" + | "Percentile99"; +/** Type of MetricUnit */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -574,6 +771,9 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } +/** Type of TimeGrain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -588,7 +788,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -599,6 +799,17 @@ export interface MetricRequestPayload { filters?: DimensionFilter[]; } +export function metricRequestPayloadSerializer( + item: MetricRequestPayload, +): MetricRequestPayloadRest { + return { + filters: + item["filters"] === undefined + ? item["filters"] + : item["filters"].map(dimensionFilterSerializer), + }; +} + /** Dimension name and values to filter */ export interface DimensionFilter { /** The dimension name */ @@ -607,8 +818,17 @@ export interface DimensionFilter { values?: string[]; } +export function dimensionFilterSerializer( + item: DimensionFilter, +): DimensionFilterRest { + return { + name: item["name"], + values: item["values"], + }; +} + /** The response to a metrics query. */ -export interface Metrics { +export interface _PagedTimeSeriesElement { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -625,8 +845,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; + /** The timestamp for the metric value in ISO 8601 format. */ + timestamp?: string; /** The metric value. */ value?: number; } @@ -639,26 +859,18 @@ export interface DimensionValue { value?: string; } -/** Paged collection of TestFileInfo items */ -export interface PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface PagedTest { - /** The Test items on this page */ - value: Test[]; +/** Collection of test runs */ +export interface _PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; /** The link to the next page of items */ nextLink?: string; } -/** Paged collection of TestRun items */ -export interface PagedTestRun { - /** The TestRun items on this page */ - value: TestRun[]; +/** Paged collection of DimensionValueList items */ +export interface _PagedDimensionValueList { + /** The DimensionValueList items on this page */ + value: DimensionValueList[]; /** The link to the next page of items */ nextLink?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index 8e9fd54c34..965a8a192f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -2,9 +2,12 @@ // Licensed under the MIT license. import { OperationOptions } from "@azure-rest/core-client"; -import { TimeGrain } from "./models.js"; +import { Interval } from "./models.js"; -export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { +/** Optional parameters. */ +export interface TestRunOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; /** This request has a JSON Merge Patch body. */ contentType?: string; /** @@ -16,46 +19,75 @@ export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { oldTestRunId?: string; } +/** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } +/** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } +/** Optional parameters. */ export interface DeleteTestRunOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetAppComponentsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetServerMetricsConfigOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTestRunOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetTestRunFileOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } -export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} +/** Optional parameters. */ +export interface ListMetricDefinitionsOptionalParams extends OperationOptions { + /** Metric namespace to query metric definitions for. */ + metricNamespace?: string; +} +/** Optional parameters. */ export interface ListMetricNamespacesOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ListMetricsOptionalParams extends OperationOptions { /** The aggregation */ aggregation?: string; /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; + /** Metric namespace to query metric definitions for. */ + metricNamespace?: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } +/** Optional parameters. */ export interface ListTestRunsOptionalParams extends OperationOptions { /** * Sort on the supported fields in (field asc/desc) format. eg: executedDateTime @@ -70,14 +102,15 @@ export interface ListTestRunsOptionalParams extends OperationOptions { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionFrom?: Date; - /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionTo?: Date; + /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionFrom?: string; + /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionTo?: string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ maxpagesize?: number; } +/** Optional parameters. */ export interface StopTestRunOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts new file mode 100644 index 0000000000..a96372d9f9 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + PollerLike, + OperationState, + deserializeState, + ResourceLocationConfig, +} from "@azure/core-lro"; +import { TestRunOperationsClient } from "./testRunOperationsClient.js"; +import { getLongRunningPoller } from "./api/pollingHelpers.js"; +import { _testRunDeserialize } from "./api/operations.js"; +import { + PathUncheckedResponse, + OperationOptions, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; + +export interface RestorePollerOptions< + TResult, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +> extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** Deserialization function for raw response body */ + processResponseBody?: (result: TResponse) => Promise; +} + +/** + * Creates a poller from the serialized state of another poller. This can be + * useful when you want to create pollers on a different host or a poller + * needs to be constructed after the original one is not in scope. + */ +export function restorePoller( + client: TestRunOperationsClient, + serializedState: string, + sourceOperation: ( + ...args: any[] + ) => PollerLike, TResult>, + options?: RestorePollerOptions, +): PollerLike, TResult> { + const pollerConfig = deserializeState(serializedState).config; + const { initialRequestUrl, requestMethod, metadata } = pollerConfig; + if (!initialRequestUrl || !requestMethod) { + throw new Error( + `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, + ); + } + const resourceLocationConfig = metadata?.["resourceLocationConfig"] as + | ResourceLocationConfig + | undefined; + const deserializeHelper = + options?.processResponseBody ?? + getDeserializationHelper(initialRequestUrl, requestMethod); + if (!deserializeHelper) { + throw new Error( + `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, + ); + } + return getLongRunningPoller( + (client as any)["_client"] ?? client, + deserializeHelper as (result: TResponse) => Promise, + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + resourceLocationConfig, + restoreFrom: serializedState, + initialRequestUrl, + }, + ); +} + +const deserializeMap: Record = { + "PATCH /test-runs/{testRunId}": _testRunDeserialize, +}; + +function getDeserializationHelper( + urlStr: string, + method: string, +): ((result: unknown) => Promise) | undefined { + const path = new URL(urlStr).pathname; + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: ((result: unknown) => Promise) | undefined; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(deserializeMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value as (result: unknown) => Promise; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index 70f670a240..af36f1eef8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { PollerLike, OperationState } from "@azure/core-lro"; import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - FileType, - FileStatus, + FileInfo, TestRun, TestRunAppComponents, TestRunServerMetricConfig, @@ -16,7 +16,7 @@ import { TimeSeriesElement, } from "./models/models.js"; import { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -33,7 +33,7 @@ import { } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { - createOrUpdateTestRun, + testRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -49,13 +49,13 @@ import { stopTestRun, createTestRunOperations, TestRunOperationsClientOptions, - LoadTestServiceContext, + AzureLoadTestingContext, } from "./api/index.js"; export { TestRunOperationsClientOptions } from "./api/testRunOperationsContext.js"; export class TestRunOperationsClient { - private _client: LoadTestServiceContext; + private _client: AzureLoadTestingContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -68,16 +68,16 @@ export class TestRunOperationsClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given test run Id. */ - createOrUpdateTestRun( + /** Create and start a new test run with the given name. */ + testRun( testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateTestRun(this._client, testRunId, body, options); + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, + ): PollerLike, TestRun> { + return testRun(this._client, testRunId, resource, options); } - /** Add an app component to a test run by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test run */ createOrUpdateAppComponents( testRunId: string, body: TestRunAppComponents, @@ -102,7 +102,7 @@ export class TestRunOperationsClient { ); } - /** Delete an existing load test run by providing the testRunId. */ + /** Delete a test run by its name. */ deleteTestRun( testRunId: string, options: DeleteTestRunOptionalParams = { requestOptions: {} }, @@ -121,7 +121,7 @@ export class TestRunOperationsClient { return getAppComponents(this._client, testRunId, options); } - /** Get associated server metrics configuration for the given test run. */ + /** List server metrics configuration for the given test run. */ getServerMetricsConfig( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, @@ -129,7 +129,7 @@ export class TestRunOperationsClient { return getServerMetricsConfig(this._client, testRunId, options); } - /** Get test run details by test run Id. */ + /** Get test run details by name. */ getTestRun( testRunId: string, options: GetTestRunOptionalParams = { requestOptions: {} }, @@ -142,13 +142,7 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -156,18 +150,14 @@ export class TestRunOperationsClient { listMetricDimensionValues( testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, - ): Promise { + ): PagedAsyncIterableIterator { return listMetricDimensionValues( this._client, testRunId, name, - metricname, metricNamespace, - timespan, options, ); } @@ -175,15 +165,9 @@ export class TestRunOperationsClient { /** List the metric definitions for a load test run. */ listMetricDefinitions( testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - return listMetricDefinitions( - this._client, - testRunId, - metricNamespace, - options, - ); + return listMetricDefinitions(this._client, testRunId, options); } /** List the metric namespaces for a load test run. */ @@ -197,31 +181,20 @@ export class TestRunOperationsClient { /** List the metric values for a load test run. */ listMetrics( testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { - return listMetrics( - this._client, - testRunId, - metricname, - metricNamespace, - timespan, - body, - options, - ); + return listMetrics(this._client, testRunId, body, options); } - /** Get all test runs for the given filters. */ + /** Get all test runs with given filters */ listTestRuns( options: ListTestRunsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } - /** Stop test run by test run Id. */ + /** Stop test run by name. */ stopTestRun( testRunId: string, options: StopTestRunOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp index 8f2d6060a0..203666d54f 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp @@ -3,58 +3,47 @@ import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Versioning; using Azure.ClientGenerator.Core; -using Microsoft.LoadTestService; +using AzureLoadTesting; @useDependency(APIVersions.v2022_11_01) -@useDependency(APIVersions.v2023_04_01_preview) namespace Customizations; -#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestAdministrationClient", - service: Microsoft.LoadTestService, + name: "LoadTestAdministrationClient", + service: AzureLoadTesting, }) interface AdministrationOperations { - createOrUpdateTest is LoadTestAdministration.createOrUpdateTest; - createOrUpdateAppComponents is LoadTestAdministration.createOrUpdateAppComponents; - createOrUpdateServerMetricsConfig is LoadTestAdministration.createOrUpdateServerMetricsConfig; - getAppComponents is LoadTestAdministration.getAppComponents; - getServerMetricsConfig is LoadTestAdministration.getServerMetricsConfig; - getTest is LoadTestAdministration.getTest; - getTestFile is LoadTestAdministration.getTestFile; - listTestFiles is LoadTestAdministration.listTestFiles; - listTests is LoadTestAdministration.listTests; - #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." - @clientName("BeginUploadTestFile", "python") - uploadTestFile is LoadTestAdministration.uploadTestFile; - deleteTestFile is LoadTestAdministration.deleteTestFile; - deleteTest is LoadTestAdministration.deleteTest; -} + CreateOrUpdateTest is LoadTestAdministration.CreateOrUpdateTest; + CreateOrUpdateAppComponents is LoadTestAdministration.CreateOrUpdateAppComponents; + CreateOrUpdateServerMetricsConfig is LoadTestAdministration.CreateOrUpdateServerMetricsConfig; + GetAppComponents is LoadTestAdministration.GetAppComponents; + GetServerMetricsConfig is LoadTestAdministration.GetServerMetricsConfig; + GetTest is LoadTestAdministration.GetTest; + GetTestFile is LoadTestAdministration.GetTestFile; + ListTestFiles is LoadTestAdministration.ListTestFiles; + ListTests is LoadTestAdministration.ListTests; + UploadTestFile is LoadTestAdministration.UploadTestFile; + DeleteTestFile is LoadTestAdministration.DeleteTestFile; + DeleteTest is LoadTestAdministration.DeleteTest; +}; -#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestRunClient", - service: Microsoft.LoadTestService, + name: "LoadTestRunClient", + service: AzureLoadTesting, }) interface TestRunOperations { - @clientName("BeginTestRun", "python") - createOrUpdateTestRun is LoadTestRun.createOrUpdateTestRun; - createOrUpdateAppComponents is LoadTestRun.createOrUpdateAppComponents; - createOrUpdateServerMetricsConfig is LoadTestRun.createOrUpdateServerMetricsConfig; - deleteTestRun is LoadTestRun.deleteTestRun; - getAppComponents is LoadTestRun.getAppComponents; - getServerMetricsConfig is LoadTestRun.getServerMetricsConfig; - getTestRun is LoadTestRun.getTestRun; - getTestRunFile is LoadTestRun.getTestRunFile; - listMetricDimensionValues is LoadTestRun.listMetricDimensionValues; - @clientName("get_metric_definitions", "python") - @clientName("getMetricDefinitions", "java") - listMetricDefinitions is LoadTestRun.listMetricDefinitions; - @clientName("get_metric_namespaces", "python") - @clientName("getMetricNamespaces", "java") - listMetricNamespaces is LoadTestRun.listMetricNamespaces; - listMetrics is LoadTestRun.listMetrics; - listTestRuns is LoadTestRun.listTestRuns; - #suppress "@azure-tools/typespec-azure-core/no-operation-id" - stopTestRun is LoadTestRun.stop; -} + TestRun is LoadTestRun.CreateOrUpdateTestRun; + CreateOrUpdateAppComponents is LoadTestRun.CreateOrUpdateAppComponents; + CreateOrUpdateServerMetricsConfig is LoadTestRun.CreateOrUpdateServerMetricsConfig; + DeleteTestRun is LoadTestRun.DeleteTestRun; + GetAppComponents is LoadTestRun.GetAppComponents; + GetServerMetricsConfig is LoadTestRun.GetServerMetricsConfig; + GetTestRun is LoadTestRun.GetTestRun; + GetTestRunFile is LoadTestRun.GetTestRunFile; + ListMetricDimensionValues is LoadTestRun.ListMetricDimensionValues; + ListMetricDefinitions is LoadTestRun.ListMetricDefinitions; + ListMetricNamespaces is LoadTestRun.ListMetricNamespaces; + ListMetrics is LoadTestRun.ListMetrics; + ListTestRuns is LoadTestRun.ListTestRuns; + StopTestRun is LoadTestRun.StopTestRun; +}; diff --git a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp index db65771939..6fc3242049 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp @@ -1,6 +1,5 @@ import "@typespec/rest"; import "@typespec/http"; -import "@typespec/versioning"; import "./routes.tsp"; using TypeSpec.Rest; @@ -10,9 +9,7 @@ using Azure.Core; @versioned(APIVersions) @useAuth(Oauth2) -@service({ - title: "Azure Load Testing", -}) +@service({title: "Azure Load Testing"}) @server( "https://{endpoint}", "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", @@ -21,22 +18,17 @@ using Azure.Core; } ) @doc(""" -These APIs allow end users to create, view and run load tests using Azure Load Test Service. +These APIs allow end users to create, view and run load tests using Azure Load +Test Service. """) -namespace Microsoft.LoadTestService; +namespace AzureLoadTesting; -@doc("Azure Load Testing API versions.") enum APIVersions { - @doc("The 2022-11-01 version of the Azure Load Testing API.") @useDependency(Azure.Core.Versions.v1_0_Preview_2) v2022_11_01: "2022-11-01", - - @doc("The 2023-04-01-preview version of the Azure Load Testing API.") - @useDependency(Azure.Core.Versions.v1_0_Preview_2) - v2023_04_01_preview: "2023-04-01-preview", } -@doc("OAuth 2.0 Flow with Microsoft Entra ID.") +@doc("The Azure Active Directory OAuth2 Flow") model Oauth2 is OAuth2Auth<[ { @@ -44,4 +36,4 @@ model Oauth2 authorizationUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; scopes: ["https://cnt-prod.loadtesting.azure.com/.default"]; } - ]>; + ]>; \ No newline at end of file diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp index eab85f74cd..cb943d38b7 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp @@ -1,204 +1,142 @@ import "@typespec/rest"; import "@typespec/http"; import "@azure-tools/typespec-azure-core"; -import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Rest; using TypeSpec.Http; -using TypeSpec.Versioning; -using Azure.ClientGenerator.Core; -namespace Microsoft.LoadTestService; +namespace AzureLoadTesting; -@doc("Metrics for pass/fail criteria.") -union PFMetrics { - string, - - @doc("Pass fail criteria for response time metric in milliseconds.") - "response_time_ms", - - @doc("Pass fail criteria for latency metric in milliseconds.") "latency", - @doc("Pass fail criteria for error metric.") "error", - @doc("Pass fail criteria for total requests.") "requests", - @doc("Pass fail criteria for request per second.") "requests_per_sec", -} - -@doc("Aggregation functions for pass/fail criteria.") -union PFAgFunc { - string, - @doc("Criteria applies for count value.") "count", - @doc("Criteria applies for given percentage value.") "percentage", - @doc("Criteria applies for avg value.") "avg", - @doc("Criteria applies for 50th percentile value.") "p50", - @doc("Criteria applies for 90th percentile value.") "p90", - @doc("Criteria applies for 95th percentile value.") "p95", - @doc("Criteria applies for 99th percentile value.") "p99", - @doc("Criteria applies for minimum value.") "min", - @doc("Criteria applies for maximum value.") "max", -} - -@doc("Action to take on failure of pass/fail criteria.") -union PFAction { - string, - - @doc("Test will continue to run even if pass fail metric criteria metric gets failed.") - continue: "continue", - - @doc("Test run will stop if pass fail criteria metric is not passed.") - stop: "stop", -} - -@doc("Pass/fail criteria result.") -union PFResult { - string, - @doc("Given pass fail criteria metric has passed.") "passed", - @doc("Given pass fail criteria metric couldn't determine.") "undetermined", - @doc("Given pass fail criteria metric has failed.") "failed", -} - -@doc("Types of secrets supported.") -union SecretType { - string, - @doc("If the secret is stored in an Azure Key Vault.") "AKV_SECRET_URI", - @doc("If the secret value provided as plain text.") "SECRET_VALUE", -} - -@doc("Types of certificates supported.") -union CertificateType { - string, - @doc("If the certificate is stored in an Azure Key Vault.") "AKV_CERT_URI", -} - -@doc("Types of file supported.") -union FileType { - string, - @doc("If the file is a JMX script.") "JMX_FILE", - @doc("If the file is a user properties file.") "USER_PROPERTIES", - - @doc("If the file is not among any of the other supported file types.") - "ADDITIONAL_ARTIFACTS", - - @added(APIVersions.v2023_04_01_preview) - @doc("If the file is a compressed archive containing a collection of various artifacts or resources.") - "ZIPPED_ARTIFACTS", - - @added(APIVersions.v2023_04_01_preview) - @doc("If the file is a JSON config file to define the requests for a URL test.") - "URL_TEST_CONFIG_JSON", -} - -@doc("File status.") -union FileStatus { - string, - @doc("File is not validated.") "NOT_VALIDATED", - @doc("File is validated.") "VALIDATION_SUCCESS", - @doc("File validation is failed.") "VALIDATION_FAILURE", - @doc("File validation is in progress.") "VALIDATION_INITIATED", - @doc("Validation is not required.") "VALIDATION_NOT_REQUIRED", -} - -@doc("Test result based on pass/fail criteria.") -union PFTestResult { - string, - @doc("Pass/fail criteria has passed.") "PASSED", - @doc("Pass/fail criteria is not applicable.") "NOT_APPLICABLE", - @doc("Pass/fail criteria has failed.") "FAILED", -} - -@doc("Test run status.") -union Status { - string, - @doc("Test run request is accepted.") "ACCEPTED", - @doc("Test run is not yet started.") "NOTSTARTED", - @doc("Test run is provisioning.") "PROVISIONING", - @doc("Test run is provisioned.") "PROVISIONED", - @doc("Test run is getting configured.") "CONFIGURING", - @doc("Test run configuration is done.") "CONFIGURED", - @doc("Test run has started executing.") "EXECUTING", - @doc("Test run execution is completed.") "EXECUTED", - @doc("Test run is getting deprovisioned.") "DEPROVISIONING", - @doc("Test run is deprovisioned.") "DEPROVISIONED", - @doc("Test run is completed.") "DONE", - @doc("Test run is being cancelled.") "CANCELLING", - @doc("Test run request is cancelled.") "CANCELLED", - @doc("Test run request is failed.") "FAILED", - @doc("Test run JMX file is validated.") "VALIDATION_SUCCESS", - @doc("Test run JMX file validation is failed.") "VALIDATION_FAILURE", -} - -@doc("Aggregation type.") -union AggregationType { - string, - @doc("Average value.") "Average", - @doc("Total count.") "Count", - @doc("Aggregation will be average in this case.") "None", - @doc("Total sum.") "Total", - @doc("90th percentile.") "Percentile90", - @doc("95th percentile.") "Percentile95", - @doc("99th percentile.") "Percentile99", -} - -@doc("Metric unit.") -union MetricUnit { - string, - @doc("No unit specified.") "NotSpecified", - @doc("Percentage.") "Percent", - @doc("Value count.") "Count", - @doc("Seconds.") "Seconds", - @doc("Milliseconds") "Milliseconds", - @doc("Bytes") "Bytes", - @doc("Bytes per second") "BytesPerSecond", - @doc("Count per second") "CountPerSecond", -} - -@doc("Time Grain") -union TimeGrain { - string, - - @doc("5 seconds, available only if test run duration is less than 10 minutes.") - PT5S: "PT5S", - - @doc("10 seconds, available only if test run duration is less than 10 minutes.") - PT10S: "PT10S", - - @doc("1 minute") - PT1M: "PT1M", - - @doc("5 minutes, available only if test run duration is greater than 1 minute.") - PT5M: "PT5M", - - @doc("1 hour, available only if test run duration is greater than 1 minute.") - PT1H: "PT1H", -} - -@added(APIVersions.v2023_04_01_preview) -@doc("Test kind") -union TestKind { - string, - @doc("URL Test") "URL", - @doc("JMX Test") "JMX", -} - -@doc("Test file info.") -@resource("files") -@parentResource(Test) -model TestFileInfo is FileInfo; - -@doc("Test run file info.") -@resource("files") -@parentResource(TestRun) -model TestRunFileInfo is FileInfo; - -@doc("Load test model.") -@resource("tests") +enum PFMetrics { + @doc("Pass fail criteria for response time metric") response_time_ms, + @doc("Pass fail criteria for response time metric") latency, + @doc("Pass fail criteria for error metric") error, + @doc("Pass fail criteria for total requests") requests, + @doc("Pass fail criteria for request rate.") requests_per_sec, +} + +enum PFAgFunc { + @doc("Criteria applies for count value") count, + @doc("Criteria applies for given percentage value") percentage, + @doc("Criteria applies for avg value") avg, + @doc("Criteria applies for 50th percentile value") p50, + @doc("Criteria applies for 90th percentile value") p90, + @doc("Criteria applies for 95th percentile value") p95, + @doc("Criteria applies for 99th percentile value") p99, + @doc("Criteria applies for minimum value") min, + @doc("Criteria applies for maximum value") max, +} + +enum PFAction { + @doc("Test will continue to run even if pass fail metric criteria metric gets failed") + continue, + @doc("Test run will stop if pass fail criteria metric is not passed.") stop, +} + +enum PFResult { + @doc("Given pass fail criteria metric has passed.") passed, + @doc("Given pass fail criteria metric couldn't determine.") undetermined, + @doc("Given pass fail criteria metric has failed.") failed, +} + +enum SecretType { + @doc("If the secret is stored in an Azure Key Vault") AKV_SECRET_URI, + @doc("If the Plain text secret value provided") SECRET_VALUE, +} + +enum CertificateType { + @doc("If the certificate is stored in an Azure Key Vault") AKV_CERT_URI, +} + +enum FileType { + @doc("If file is jmx script") JMX_FILE, + @doc("If file is user properties") USER_PROPERTIES, + @doc("If file is not any of other supported type") ADDITIONAL_ARTIFACTS, +} + +enum FileStatus { + @doc("File is not validated.") NOT_VALIDATED, + @doc("File is validated.") VALIDATION_SUCCESS, + @doc("File validation is failed.") VALIDATION_FAILURE, + @doc("File validation is in progress.") VALIDATION_INITIATED, + @doc("Validation is not required.") VALIDATION_NOT_REQUIRED, +} + +enum PFTestResult { + @doc("Pass/fail criteria has passed.") PASSED, + @doc("Pass/fail criteria is not applicable.") NOT_APPLICABLE, + @doc("Pass/fail criteria has failed.") FAILED, +} + +enum Status { + @doc("Test run request is accepted") ACCEPTED, + @doc("Test run is not yet started.") NOTSTARTED, + @doc("Test run is getting provision") PROVISIONING, + @doc("Test run is provisioned") PROVISIONED, + @doc("Test run is getting configure") CONFIGURING, + @doc("Test run configuration is done") CONFIGURED, + @doc("Test run has started executing") EXECUTING, + @doc("Test run has been executed") EXECUTED, + @doc("Test run is getting deprovision") DEPROVISIONING, + @doc("Test run request is deprovisioned") DEPROVISIONED, + @doc("Test run request is finished") DONE, + @doc("Test run request is getting cancelled") CANCELLING, + @doc("Test run request is cancelled") CANCELLED, + @doc("Test run request is failed") FAILED, + @doc("Test run JMX file is validated") VALIDATION_SUCCESS, + @doc("Test run JMX file validation is failed") VALIDATION_FAILURE, +} + +enum AggregationType { + @doc("Average value") Average, + @doc("Total count") Count, + @doc("Aggregation will be average in this case") None, + @doc("Total sum") Total, + @doc("90th percentile") Percentile90, + @doc("95th percentile") Percentile95, + @doc("99th percentile") Percentile99, +} + +enum MetricUnit { + @doc("No unit specified") NotSpecified, + @doc("Percentage") Percent, + @doc("Value count") Count, + @doc("Seconds") Seconds, + @doc("Milliseconds") Milliseconds, + @doc("Bytes") Bytes, + @doc("Bytes per second") BytesPerSecond, + @doc("Count per second") CountPerSecond, +} + +enum TimeGrain { + @doc("5 seconds, available only if test run duration is less than 10 minutes") + PT5S, + @doc("10 seconds, available only if test run duration is less than 10 minutes") + PT10S, + @doc("1 minute") PT1M, + @doc("5 minutes, available only if test run duration is greater than 1 minute") + PT5M, + @doc("1 hour, available only if test run duration is greater than 1 minute") + PT1H, +} + +enum Interval { + @doc("5 seconds, available only if test run duration is less than 10 minutes") + PT5S, + @doc("10 seconds, available only if test run duration is less than 10 minutes") + PT10S, + @doc("1 minute") PT1M, + @doc("5 minutes, available only if test run duration is greater than 1 minute") + PT5M, + @doc("1 hour, available only if test run duration is greater than 1 minute") + PT1H, +} + +@doc("Load test model") model Test { @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; - @added(APIVersions.v2023_04_01_preview) - @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") - autoStopCriteria?: AutoStopCriteria; - @doc(""" Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret @@ -208,7 +146,7 @@ SECRET_VALUE. """) secrets?: Record; - @doc("Certificates metadata.") + @doc("Certificates metadata") certificate?: CertificateMetadata; @doc("Environment variables which are defined as a set of pairs.") @@ -217,44 +155,44 @@ SECRET_VALUE. @doc("The load test configuration.") loadTestConfiguration?: LoadTestConfiguration; - @added(APIVersions.v2023_04_01_preview) - @doc("Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs") - baselineTestRunId?: string; - @doc("The input artifacts for the test.") @visibility("read") inputArtifacts?: TestInputArtifacts; - ...TestIdPathParameter; + @doc("Unique test name as identifier.") + @visibility("read") + testId?: string; - @maxLength(100) @doc("The test description.") description?: string; - @maxLength(50) - @minLength(2) @doc("Display name of a test.") displayName?: string; @doc("Subnet ID on which the load test instances should run.") subnetId?: string; - @added(APIVersions.v2023_04_01_preview) - @doc("Kind of test.") - kind?: TestKind; - - #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" - @added(APIVersions.v2023_04_01_preview) - @doc("Inject load test engines without deploying public IP for outbound access") - publicIPDisabled?: boolean; - @doc("Type of the managed identity referencing the Key vault.") keyvaultReferenceIdentityType?: string; @doc("Resource Id of the managed identity referencing the Key vault.") keyvaultReferenceIdentityId?: string; - ...SystemMetaData; + @doc("The creation datetime(ISO 8601 literal format).") + @visibility("read") + createdDateTime?: offsetDateTime; + + @doc("The user that created.") + @visibility("read") + createdBy?: string; + + @doc("The last Modified datetime(ISO 8601 literal format).") + @visibility("read") + lastModifiedDateTime?: offsetDateTime; + + @doc("The user that last modified.") + @visibility("read") + lastModifiedBy?: string; } @doc("Pass fail criteria for a test.") @@ -286,14 +224,14 @@ The aggregation function to be applied on the client metric. Allowed functions The value to compare with the client metric. Allowed values - ‘error : [0.0 , 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. """) - value?: float64; + value?: float32; @doc("Action taken after the threshold is met. Default is ‘continue’.") - action?: PFAction = PFAction.continue; + action?: PFAction; @doc("The actual value of the client metric for the test run.") @visibility("read") - actualValue?: float64; + actualValue?: float32; @doc("Outcome of the test run.") @visibility("read") @@ -321,121 +259,119 @@ model CertificateMetadata { name?: string; } -@added(APIVersions.v2023_04_01_preview) -@doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") -model AutoStopCriteria { - @doc("Whether auto-stop should be disabled. The default value is false.") - autoStopDisabled?: boolean = false; - - @doc("Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0") - errorRate?: float32 = 90; - - @doc("Time window during which the error percentage should be evaluated in seconds.") - errorRateTimeWindowInSeconds?: int32 = 60; -} - -@doc("Configurations for the load test.") +@doc("The load test configuration.") model LoadTestConfiguration { @doc(""" -The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. +The number of engine instances to execute load test. Supported values are in +range of 1-45. Required for creating a new test. """) engineInstances?: int32; - #suppress "@azure-tools/typespec-azure-core/casing-style" "CSV is an abbervation and should be all caps" @doc(""" If false, Azure Load Testing copies and processes your input files unmodified across all test engine instances. If true, Azure Load Testing splits the CSV input data evenly across all engine instances. If you provide multiple CSV files, each file will be split evenly. """) - splitAllCSVs?: boolean = false; + splitAllCSVs?: boolean; @doc(""" If true, optionalLoadTestConfig is required and JMX script for the load test is not required to upload. """) - quickStartTest?: boolean = false; + quickStartTest?: boolean; - @doc("Configuration for quick load test") + @doc("Optional load test config") optionalLoadTestConfig?: OptionalLoadTestConfig; } -@doc("Configuration for quick load test") +@doc("Optional load test config") model OptionalLoadTestConfig { - @doc("Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login") + @doc(""" +Test URL. Provide the complete HTTP URL. For example, +http://contoso-app.azurewebsites.net/login +""") endpointUrl?: string; - @doc("Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it.") - @added(APIVersions.v2023_04_01_preview) - requestsPerSecond?: int32; - - @doc("Maximum response time in milliseconds of the API/endpoint.") - @added(APIVersions.v2023_04_01_preview) - maxResponseTimeInMs?: int32; - - @doc("No of concurrent virtual users.") + @doc("No of concurrent virtual users") virtualUsers?: int32; - @doc("Ramp up time in seconds.") + @doc("Ramp up time") rampUpTime?: int32; - @doc("Test run duration in seconds.") + @doc("Test run duration") duration?: int32; } @doc("The input artifacts for the test.") model TestInputArtifacts { @doc("File info") - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; @doc("File info") - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; @doc("File info") - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; @doc("File info") - inputArtifactsZipFileInfo?: TestFileInfo; - - @added(APIVersions.v2023_04_01_preview) - @doc("The config json file for url based test") - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: TestFileInfo[]; + additionalFileInfo?: FileInfo[]; } @doc("File info") model FileInfo { - @doc("Name of the file.") - @key - @visibility - fileName: string; - @doc("File URL.") - //update description - @visibility("read") - url?: url; + url?: string; + + @doc("Name of the file.") + fileName?: string; @doc("File type") - @visibility("read") fileType?: FileType; - @doc("Expiry time of the file (RFC 3339 literal format)") - @visibility("read") - expireDateTime?: utcDateTime; + @doc("Expiry time of the file (ISO 8601 literal format)") + expireDateTime?: offsetDateTime; @doc("Validation status of the file") - @visibility("read") validationStatus?: FileStatus; @doc("Validation failure error details") - @visibility("read") validationFailureDetails?: string; } -@doc("Test app components") +@doc("The definition of an error object.") +@error +model ErrorResponseBody { + @doc("Error from a REST request.") + error: Error; +} + +@doc("Error from a REST request.") +model Error { + @doc("The error code.") + code: string; + + @doc("The error message.") + message: string; + + @doc("The error target.") + target?: string; + + @doc("Additional details and inner errors.") + details?: Error[]; +} + +@doc("Collection of tests") +model TestsList is Azure.Core.Page; + +@doc("Collection of files.") +model FileInfoList is Azure.Core.Page; + +@doc("Test app component") model TestAppComponents { @doc(""" Azure resource collection { resource id (fully qualified resource Id e.g @@ -448,24 +384,40 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo @visibility("read") testId?: string; - ...SystemMetaData; + @doc("The creation datetime(ISO 8601 literal format).") + @visibility("read") + createdDateTime?: offsetDateTime; + + @doc("The user that created.") + @visibility("read") + createdBy?: string; + + @doc("The last Modified datetime(ISO 8601 literal format).") + @visibility("read") + lastModifiedDateTime?: offsetDateTime; + + @doc("The user that last modified.") + @visibility("read") + lastModifiedBy?: string; } @doc(""" -An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) +An Azure resource object (Refer azure generic resource model : +https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) """) model AppComponent { @doc(""" -fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} +fully qualified resource Id e.g +subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} """) @visibility("read") - resourceId: string; + resourceId?: string; @doc("Azure resource name, required while creating the app component.") - resourceName: string; + resourceName?: string; @doc("Azure resource type, required while creating the app component.") - resourceType: string; + resourceType?: string; @doc("Azure resource display name") displayName?: string; @@ -493,9 +445,23 @@ Azure resource metrics collection {metric id : metrics object} (Refer : https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition for metric id). """) - metrics: Record; + metrics?: Record; + + @doc("The creation datetime(ISO 8601 literal format).") + @visibility("read") + createdDateTime?: offsetDateTime; - ...SystemMetaData; + @doc("The user that created.") + @visibility("read") + createdBy?: string; + + @doc("The last Modified datetime(ISO 8601 literal format).") + @visibility("read") + lastModifiedDateTime?: offsetDateTime; + + @doc("The user that last modified.") + @visibility("read") + lastModifiedBy?: string; } @doc(""" @@ -532,16 +498,21 @@ model ResourceMetric { @doc("Load test run model") @resource("test-runs") +model TestRuns { + // FIXME: is testRunId optional or required in the response? Resource key and path params cannot be optional + @key + @doc("Unique test run name as identifier") + @visibility("read") + testRunId: string; +} + +@doc("Load test run model") model TestRun { - ...TestRunIdPathParameter; + ...TestRuns, @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; - @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") - @added(APIVersions.v2023_04_01_preview) - autoStopCriteria?: AutoStopCriteria; - @doc(""" Secrets can be stored in an Azure Key Vault or any other secret store. If the secret is stored in an Azure Key Vault, the value should be the secret @@ -580,17 +551,12 @@ SECRET_VALUE. @visibility("read") virtualUsers?: int32; - @maxLength(50) - @minLength(2) @doc("Display name of a testRun.") displayName?: string; - @maxLength(50) - @minLength(2) @doc("Associated test Id.") testId?: string; - @maxLength(100) @doc("The test run description.") description?: string; @@ -598,17 +564,17 @@ SECRET_VALUE. @visibility("read") status?: Status; - @doc("The test run start DateTime(RFC 3339 literal format).") + @doc("The test run start DateTime(ISO 8601 literal format).") @visibility("read") - startDateTime?: utcDateTime; + startDateTime?: offsetDateTime; - @doc("The test run end DateTime(RFC 3339 literal format).") + @doc("The test run end DateTime(ISO 8601 literal format).") @visibility("read") - endDateTime?: utcDateTime; + endDateTime?: offsetDateTime; @doc("Test run initiated time.") @visibility("read") - executedDateTime?: utcDateTime; + executedDateTime?: offsetDateTime; @doc("Portal url.") @visibility("read") @@ -616,24 +582,27 @@ SECRET_VALUE. @doc("Test run duration in milliseconds.") @visibility("read") - duration?: int64; + duration?: int32; @doc("Subnet ID on which the load test instances should run.") @visibility("read") subnetId?: string; - @added(APIVersions.v2023_04_01_preview) - @doc("Type of test.") + @doc("The creation datetime(ISO 8601 literal format).") @visibility("read") - kind?: TestKind; + createdDateTime?: offsetDateTime; - #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" - @added(APIVersions.v2023_04_01_preview) - @doc("Inject load test engines without deploying public IP for outbound access") + @doc("The user that created.") @visibility("read") - publicIPDisabled?: boolean; + createdBy?: string; - ...SystemMetaData; + @doc("The last Modified datetime(ISO 8601 literal format).") + @visibility("read") + lastModifiedDateTime?: offsetDateTime; + + @doc("The user that last modified.") + @visibility("read") + lastModifiedBy?: string; } @doc("Error details if there is any failure in load test run") @@ -651,57 +620,55 @@ model TestRunStatistics { @doc("Sampler count.") @visibility("read") - sampleCount?: float64; + sampleCount?: float32; @doc("Error count.") @visibility("read") - errorCount?: float64; + errorCount?: float32; @doc("Error percentage.") @visibility("read") - errorPct?: float64; + errorPct?: float32; @doc("Mean response time.") @visibility("read") - meanResTime?: float64; + meanResTime?: float32; @doc("Median response time.") @visibility("read") - medianResTime?: float64; + medianResTime?: float32; @doc("Max response time.") @visibility("read") - maxResTime?: float64; + maxResTime?: float32; @doc("Minimum response time.") @visibility("read") - minResTime?: float64; + minResTime?: float32; @doc("90 percentile response time.") @visibility("read") - pct1ResTime?: float64; + pct1ResTime?: float32; @doc("95 percentile response time.") @visibility("read") - pct2ResTime?: float64; + pct2ResTime?: float32; @doc("99 percentile response time.") @visibility("read") - pct3ResTime?: float64; + pct3ResTime?: float32; @doc("Throughput.") @visibility("read") - throughput?: float64; + throughput?: float32; - #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Received network bytes.") @visibility("read") - receivedKBytesPerSec?: float64; + receivedKBytesPerSec?: float32; - #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Send network bytes.") @visibility("read") - sentKBytesPerSec?: float64; + sentKBytesPerSec?: float32; } @doc("Collection of test run artifacts") @@ -717,48 +684,33 @@ model TestRunArtifacts { @doc("The input artifacts for the test run.") model TestRunInputArtifacts { @doc("File info") - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; @doc("File info") - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; @doc("File info") - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; @doc("File info") - inputArtifactsZipFileInfo?: TestRunFileInfo; - - @added(APIVersions.v2023_04_01_preview) - @doc("The config json file for url based test") - urlTestConfigFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: FileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: TestRunFileInfo[]; + additionalFileInfo?: FileInfo[]; } @doc("The output artifacts for the test run.") model TestRunOutputArtifacts { @doc("File info") - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; @doc("File info") - logsFileInfo?: TestRunFileInfo; - - @doc("The container for test run artifacts.") - @added(APIVersions.v2023_04_01_preview) - artifactsContainerInfo?: ArtifactsContainerInfo; + logsFileInfo?: FileInfo; } -@doc("Artifacts container info.") -@added(APIVersions.v2023_04_01_preview) -model ArtifactsContainerInfo { - @doc("This is a SAS URI to an Azure Storage Container that contains the test run artifacts.") - url?: url; - - @doc("Expiry time of the container (RFC 3339 literal format)") - expireDateTime?: utcDateTime; -} +@doc("Collection of test runs") +model TestRunsList is Azure.Core.Page; @doc("Represents collection of metric namespaces.") model MetricNamespaceCollection { @@ -829,7 +781,7 @@ a duration 'PT1M', 'PT1H', etc. timeGrain?: TimeGrain; } -@doc("Filters to fetch the set of metric.") +@doc("Filters to fetch the set of metric") model MetricRequestPayload { @doc(""" Get metrics for specific dimension values. Example: Metric contains dimension @@ -850,8 +802,6 @@ model DimensionFilter { } @doc("The response to a metrics query.") -@friendlyName("Metrics") -// using friendlyName to change the name of the model due to issue in using projectedName '@encodedName("application/json", "Metrics")' https://github.com/microsoft/typespec/issues/2276 model Metrics is Azure.Core.Page; @doc("The time series returned when a data query is performed.") @@ -865,11 +815,11 @@ model TimeSeriesElement { @doc("Represents a metric value.") model MetricValue { - @doc("The timestamp for the metric value in RFC 3339 format.") - timestamp?: utcDateTime; + @doc("The timestamp for the metric value in ISO 8601 format.") + timestamp?: string; @doc("The metric value.") - value?: float64; + value?: float32; } @doc("Represents a metric dimension value.") @@ -881,41 +831,42 @@ model DimensionValue { value?: string; } -@doc("Metrics dimension values.") +@resource("values") +@parentResource(Dimension) model DimensionValueList { - @doc("The dimension name") - @visibility("read") - @added(APIVersions.v2023_04_01_preview) - name?: string; - - @doc("The dimension value") - value?: string[]; + @key + value: string[]; +} - @doc("Link for the next set of values in case of paginated results, if applicable.") - nextLink?: ResourceLocation; +@resource("metric-dimensions") +@parentResource(TestRuns) +model Dimension { + @key + @doc("Dimension name") + @visibility("query") + name: string; } -@doc("Metric Dimensions") -model MetricDimensionsRequest { - @doc("Metric name") +model MetricDimensions { + @doc("The interval (i.e. timegrain) of the query.") @query - metricname: string; + interval?: Interval; - @doc("The interval (i.e. timegrain) of the query.") + @doc("Metric name") @query - interval?: TimeGrain = TimeGrain.PT1M; + metricName?: string; @doc("Metric namespace to query metric definitions for.") @query metricNamespace: string; @doc(""" - The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. + The timespan of the query. It is a string with the following format + 'startDateTime_ISO/endDateTime_ISO'. """) @query - @clientName("time_interval", "python") - timespan: string; -} + timespan?: string; +}; @doc("Test run app component") model TestRunAppComponents { @@ -930,7 +881,21 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo @visibility("read") testRunId?: string; - ...SystemMetaData; + @doc("The creation datetime(ISO 8601 literal format).") + @visibility("read") + createdDateTime?: offsetDateTime; + + @doc("The user that created.") + @visibility("read") + createdBy?: string; + + @doc("The last Modified datetime(ISO 8601 literal format).") + @visibility("read") + lastModifiedDateTime?: offsetDateTime; + + @doc("The user that last modified.") + @visibility("read") + lastModifiedBy?: string; } @doc("Test run server metrics configuration") @@ -946,136 +911,23 @@ for metric id). """) metrics?: Record; - ...SystemMetaData; -} - -@doc("Query parameters for list test run operation") -model OldTestRunIdQueryParam { - @doc(""" -Existing test run identifier that should be rerun, if this is provided, the -test will run with the JMX file, configuration and app components from the -existing test run. You can override the configuration values for new test run -in the request body. -""") - @query - oldTestRunId?: string; -} - -@doc("Parameters for list test run operation") -model ListTestRunQueryParams { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: executedDateTime -asc. Supported fields - executedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - description, -executedUser. For example, to search for a test run, with description 500 VUs, -the search parameter can be 500. -""") - @query - search?: string; - - @doc("Unique name of an existing load test.") - @query - testId?: string; - - @doc("Start DateTime(RFC 3339 literal format) of test-run execution time filter range.") - @query - executionFrom?: utcDateTime; - - @doc("End DateTime(RFC 3339 literal format) of test-run execution time filter range.") - @query - executionTo?: utcDateTime; - - @doc("Comma separated list of test run status.") - @query - status?: string; - - @doc("Number of results in response.") - @query - maxpagesize?: int32 = 50; -} - -@doc("Parameters for list test operation") -model ListTestQueryParams { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: -lastModifiedDateTime asc. Supported fields - lastModifiedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - displayName, -createdBy. For example, to search for a test, with display name is Login Test, -the search parameter can be Login. -""") - @query - search?: string; - - @doc(""" -Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. -""") - @query - lastModifiedStartTime?: utcDateTime; - - @doc(""" -End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. -""") - @query - lastModifiedEndTime?: utcDateTime; - - @doc("Number of results in response.") - @query - maxpagesize?: int32 = 50; -} - -@doc("System metadata.") -model SystemMetaData { - @doc("The creation datetime(RFC 3339 literal format).") + @doc("The creation datetime(ISO 8601 literal format).") @visibility("read") - createdDateTime?: utcDateTime; + createdDateTime?: offsetDateTime; @doc("The user that created.") @visibility("read") createdBy?: string; - @doc("The last Modified datetime(RFC 3339 literal format).") + @doc("The last Modified datetime(ISO 8601 literal format).") @visibility("read") - lastModifiedDateTime?: utcDateTime; + lastModifiedDateTime?: offsetDateTime; @doc("The user that last modified.") @visibility("read") lastModifiedBy?: string; } -@doc("Test Id path parameter.") -model TestIdPathParameter { - @doc("Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") - @maxLength(50) - @minLength(2) - @key - @visibility("read") - @pattern("^[a-z0-9_-]*$") - testId: string; -} - -@doc("Test run Id path parameter.") -model TestRunIdPathParameter { - @doc("Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") - @visibility("read") - @maxLength(50) - @minLength(2) - @key - @pattern("^[a-z0-9_-]*$") - testRunId: string; -} - -alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & - T; +alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & T; -alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | (TypeSpec.Http.Response<200> & - T); +alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | TypeSpec.Http.Response<200> & T; diff --git a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp index e767bbc297..fd8f628931 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp @@ -1,39 +1,67 @@ import "@azure-tools/typespec-azure-core"; import "@typespec/rest"; -import "@typespec/http"; -import "@typespec/openapi"; -import "@azure-tools/typespec-client-generator-core"; import "./models.tsp"; using Azure.Core; using Azure.Core.Traits; using TypeSpec.Rest; using TypeSpec.Http; -using TypeSpec.Versioning; -using OpenAPI; -using Azure.ClientGenerator.Core; -namespace Microsoft.LoadTestService; +namespace AzureLoadTesting; -@@encodedName(Azure.Core.Foundations.ResourceBody.resource, - "application/json", - "body" -); -@@clientName(Azure.Core.Foundations.ResourceBody.resource, "body"); - -@tag("Test") interface LoadTestAdministration { - @summary("Create a new test or update an existing test by providing the test Id.") - @doc("Create a new test or update an existing test by providing the test Id.") - createOrUpdateTest is StandardResourceOperations.ResourceCreateOrUpdate; + @summary("Create a new test or update an existing test.") + @doc("Create a new test or update an existing test.") + @route("/tests/{testId}") + @patch + CreateOrUpdateTest is Azure.Core.Foundations.Operation< + { + @header contentType: "application/merge-patch+json", + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; - @summary("Delete a test by its test Id.") - @doc("Delete a test by its test Id.") - deleteTest is StandardResourceOperations.ResourceDelete; + @doc("Load test model") + @body + body: Test; + }, + ResourceCreatedOrOkResponse + >; - @summary("Get load test details by test Id") - @doc("Get load test details by test Id") - getTest is StandardResourceOperations.ResourceRead; + @summary("Delete a test by its name.") + @doc("Delete a test by its name.") + @route("/tests/{testId}") + @delete + DeleteTest is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; + }, + void + >; + + @summary("Get load test details by test name") + @doc("Get load test details by test name") + @route("/tests/{testId}") + @get + GetTest is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; + }, + Test + >; @summary(""" Get all load tests by the fully qualified resource Id e.g @@ -43,39 +71,66 @@ subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/lo Get all load tests by the fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. """) - listTests is StandardResourceOperations.ResourceList< - Test, - ListQueryParametersTrait + @route("/tests") + @get + ListTests is Azure.Core.Foundations.Operation< + { + @doc(""" +Sort on the supported fields in (field asc/desc) format. eg: +lastModifiedDateTime asc. Supported fields - lastModifiedDateTime +""") + @query + orderby?: string; + + @doc(""" +Prefix based, case sensitive search on searchable fields - displayName, +createdBy. For example, to search for a test, with display name is Login Test, +the search parameter can be Login. +""") + @query + search?: string; + + @doc(""" +Start DateTime(ISO 8601 literal format) of the last updated time range to +filter tests. +""") + @query + lastModifiedStartTime?: offsetDateTime; + + @doc(""" +End DateTime(ISO 8601 literal format) of the last updated time range to filter +tests. +""") + @query + lastModifiedEndTime?: offsetDateTime; + + @doc("Number of results in response.") + @query + maxpagesize?: int32; + }, + TestsList >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Our operation is not following the standard put behavior https://github.com/Azure/typespec-azure/issues/3743" - #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." @summary(""" -Upload input file for a given test Id. File size can't be more than 50 MB. +Upload input file for a given test name. File size can't be more than 50 MB. Existing file with same name for the given test will be overwritten. File should be provided in the request body as application/octet-stream. """) @doc(""" -Upload input file for a given test Id. File size can't be more than 50 MB. +Upload input file for a given test name. File size can't be more than 50 MB. Existing file with same name for the given test will be overwritten. File should be provided in the request body as application/octet-stream. """) @route("/tests/{testId}/files/{fileName}") @put - uploadTestFile is Azure.Core.Foundations.Operation< + UploadTestFile is Azure.Core.Foundations.Operation< { - @header - @doc("Content type.") - contentType: "application/octet-stream"; - + @header contentType: "application/octet-stream", @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testId: string; @doc("Unique name for test file with file extension like : App.jmx") @@ -90,40 +145,77 @@ numeric, underscore or hyphen characters. @body body: bytes; }, - ResourceCreatedResponse + ResourceCreatedResponse >; - @summary("Get all the files that are associated with a test.") - @doc("Get all the files that are associated with a test.") - getTestFile is StandardResourceOperations.ResourceRead; + @summary("Get test file by the file name.") + @doc("Get test file by the file name.") + @route("/tests/{testId}/files/{fileName}") + @get + GetTestFile is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; + + @doc("File name with file extension like app.jmx") + @path + fileName: string; + }, + FileInfo + >; @summary("Delete file by the file name for a test") @doc("Delete file by the file name for a test") - deleteTestFile is StandardResourceOperations.ResourceDelete; + @route("/tests/{testId}/files/{fileName}") + @delete + DeleteTestFile is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; + + @doc("File name with file extension like app.jmx") + @path + fileName: string; + }, + void + >; @summary("Get all test files.") @doc("Get all test files.") - listTestFiles is StandardResourceOperations.ResourceList; + @route("/tests/{testId}/files") + @get + ListTestFiles is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testId: string; + }, + FileInfoList + >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" - @summary("Add an app component to a test.") - @doc("Add an app component to a test by providing the resource Id, name and type.") + @summary("Associate an app component (collection of azure resources) to a test") + @doc("Associate an app component (collection of azure resources) to a test") @route("/tests/{testId}/app-components") @patch - createOrUpdateAppComponents is Azure.Core.Foundations.Operation< + CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header - @doc("Content type.") - contentType: "application/merge-patch+json"; - + @header contentType: "application/merge-patch+json", @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testId: string; @doc("App Component model.") @@ -133,45 +225,34 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Get associated app component (collection of azure resources) for the given test.") @doc("Get associated app component (collection of azure resources) for the given test.") @route("/tests/{testId}/app-components") @get - getAppComponents is Azure.Core.Foundations.Operation< + GetAppComponents is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testId: string; }, TestAppComponents >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test") @doc("Configure server metrics for a test") @route("/tests/{testId}/server-metrics-config") @patch - createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header - @doc("Content type.") - contentType: "application/merge-patch+json"; - + @header contentType: "application/merge-patch+json", @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testId: string; @doc("Server metric configuration model.") @@ -181,180 +262,253 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List server metrics configuration for the given test.") @doc("List server metrics configuration for the given test.") @route("/tests/{testId}/server-metrics-config") @get - getServerMetricsConfig is Azure.Core.Foundations.Operation< + GetServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testId: string; }, TestServerMetricConfig >; } -@tag("TestRun") interface LoadTestRun { - @summary("Get test run details by test run Id.") - @doc("Get test run details by test run Id.") - getTestRun is StandardResourceOperations.ResourceRead; - - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" - @summary("Create and start a new test run with the given test run Id.") - @doc("Create and start a new test run with the given test run Id.") - createOrUpdateTestRun is StandardResourceOperations.ResourceCreateOrUpdate< - TestRun, - QueryParametersTrait + @summary("Delete a test run by its name.") + @doc("Delete a test run by its name.") + @route("/test-runs/{testRunId}") + @delete + DeleteTestRun is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test run, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testRunId: string; + }, + void + >; + + @summary("Create and start a new test run with the given name.") + @doc("Create and start a new test run with the given name.") + // @pollingOperation(LoadTestRun.GetTestRun) + CreateOrUpdateTestRun is LongRunningResourceCreateOrUpdate< + TestRun, + QueryParametersTrait< + { + @doc(""" + Existing test run identifier that should be rerun, if this is provided, the + test will run with the JMX file, configuration and app components from the + existing test run. You can override the configuration values for new test run + in the request body. + """) + @query + oldTestRunId?: string; + } + > >; - @summary("Delete an existing load test run.") - @doc("Delete an existing load test run by providing the testRunId.") - deleteTestRun is StandardResourceOperations.ResourceDelete; - @summary("Get all test runs for the given filters.") - @doc("Get all test runs for the given filters.") - listTestRuns is StandardResourceOperations.ResourceList< - TestRun, - ListQueryParametersTrait + @summary("Get test run details by name.") + @doc("Get test run details by name.") + @route("/test-runs/{testRunId}") + @get + GetTestRun is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test run, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testRunId: string; + }, + TestRun >; @summary("Get test run file by file name.") @doc("Get test run file by file name.") - getTestRunFile is StandardResourceOperations.ResourceRead; + @route("/test-runs/{testRunId}/files/{fileName}") + @get + GetTestRunFile is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test run, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testRunId: string; + + @doc("Test run file name with file extension") + @path + fileName: string; + }, + FileInfo + >; - #suppress "@azure-tools/typespec-azure-core/no-operation-id" - @summary("Stop test run by test run Id.") - @doc("Stop test run by test run Id.") - @operationId("LoadTestRun_StopTestRun") - stop is StandardResourceOperations.ResourceAction; + @summary("Get all test runs with given filters") + @doc("Get all test runs with given filters") + @route("/test-runs") + @get + ListTestRuns is Azure.Core.Foundations.Operation< + { + @doc(""" +Sort on the supported fields in (field asc/desc) format. eg: executedDateTime +asc. Supported fields - executedDateTime +""") + @query + orderby?: string; + + @doc(""" +Prefix based, case sensitive search on searchable fields - description, +executedUser. For example, to search for a test run, with description 500 VUs, +the search parameter can be 500. +""") + @query + search?: string; + + @doc("Unique name of an existing load test.") + @query + testId?: string; + + @doc("Start DateTime(ISO 8601 literal format) of test-run execution time filter range.") + @query + executionFrom?: offsetDateTime; + + @doc("End DateTime(ISO 8601 literal format) of test-run execution time filter range.") + @query + executionTo?: offsetDateTime; + + @doc("Comma separated list of test run status.") + @query + status?: string; + + @doc("Number of results in response.") + @query + maxpagesize?: int32; + }, + TestRunsList + >; + + @summary("Stop test run by name.") + @doc("Stop test run by name.") + @route("/test-runs/{testRunId}:stop") + @post + StopTestRun is Azure.Core.Foundations.Operation< + { + @doc(""" +Unique name for the load test run, must contain only lower-case alphabetic, +numeric, underscore or hyphen characters. +""") + @path + testRunId: string; + }, + TestRun + >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric namespaces for a load test run.") @doc("List the metric namespaces for a load test run.") @route("/test-runs/{testRunId}/metric-namespaces") @get - listMetricNamespaces is Azure.Core.Foundations.Operation< + ListMetricNamespaces is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; }, MetricNamespaceCollection >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric definitions for a load test run.") @doc("List the metric definitions for a load test run.") @route("/test-runs/{testRunId}/metric-definitions") @get - listMetricDefinitions is Azure.Core.Foundations.Operation< + ListMetricDefinitions is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Metric namespace to query metric definitions for.") @query - metricNamespace: string; + metricNamespace?: string; }, MetricDefinitionCollection >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric values for a load test run.") @doc("List the metric values for a load test run.") @route("/test-runs/{testRunId}/metrics") @post - listMetrics is Azure.Core.Foundations.Operation< + ListMetrics is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("The aggregation") @query aggregation?: string; - ...MetricDimensionsRequest; + @doc("The interval (i.e. timegrain) of the query.") + @query + interval?: Interval; + + @doc("Metric name") + @query + metricName?: string; + + @doc("Metric namespace to query metric definitions for.") + @query + metricNamespace?: string; + + @doc(""" +The timespan of the query. It is a string with the following format +'startDateTime_ISO/endDateTime_ISO'. +""") + @query + timespan?: string; @doc("Metric dimension filter ") @body - body?: MetricRequestPayload; + body: MetricRequestPayload; }, Metrics >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the dimension values for the given metric dimension name.") @doc("List the dimension values for the given metric dimension name.") - @route("/test-runs/{testRunId}/metric-dimensions/{name}/values") - listMetricDimensionValues is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") - testRunId: string; - - @doc("Dimension name") - @path - name: string; - - ...MetricDimensionsRequest; - }, - DimensionValueList + ListMetricDimensionValues is Azure.Core.ResourceList< + DimensionValueList, QueryParametersTrait >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" - @summary("Add an app component to a test run.") - @doc("Add an app component to a test run by providing the resource Id, name and type.") + @summary("Associate an app component (collection of azure resources) to a test run") + @doc("Associate an app component (collection of azure resources) to a test run") @route("/test-runs/{testRunId}/app-components") @patch - createOrUpdateAppComponents is Azure.Core.Foundations.Operation< + CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header - @doc("Content type.") - contentType: "application/merge-patch+json"; - + @header contentType: "application/merge-patch+json", @doc(""" -Unique Id for the load test run, must contain only lower-case alphabetic, +Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("App Component model.") @@ -364,7 +518,6 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary(""" Get associated app component (collection of azure resources) for the given test run. @@ -375,40 +528,30 @@ run. """) @route("/test-runs/{testRunId}/app-components") @get - getAppComponents is Azure.Core.Foundations.Operation< + GetAppComponents is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunAppComponents >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test run") @doc("Configure server metrics for a test run") @route("/test-runs/{testRunId}/server-metrics-config") @patch - createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header - @doc("Content type.") - contentType: "application/merge-patch+json"; - + @header contentType: "application/merge-patch+json", @doc(""" -Unique Id for the load test run, must contain only lower-case alphabetic, +Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Server metric configuration model.") @@ -418,23 +561,20 @@ numeric, underscore or hyphen characters. ResourceCreatedOrOkResponse >; - #suppress "@azure-tools/typespec-azure-core/use-standard-operations" - @summary("Get associated server metrics configuration for the given test run.") - @doc("Get associated server metrics configuration for the given test run.") + @summary("List server metrics configuration for the given test run.") + @doc("List server metrics configuration for the given test run.") @route("/test-runs/{testRunId}/server-metrics-config") @get - getServerMetricsConfig is Azure.Core.Foundations.Operation< + @encodedName("application/json", "TestRun_ListServerMetricsConfig") + GetServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" Unique name for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. """) @path - @maxLength(50) - @minLength(2) - @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunServerMetricConfig >; -} +}; diff --git a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml index bffc1bfd71..180c5d487a 100644 --- a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml +++ b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml @@ -3,7 +3,6 @@ emit: # Uncomment this line and add "@azure-tools/typespec-python" to your package.json to generate Python code # - "@azure-tools/typespec-python" - "@azure-tools/typespec-ts" - - "@typespec/openapi3" options: "@azure-tools/typespec-ts": "emitter-output-dir": "{project-root}/generated/typespec-ts" @@ -17,6 +16,3 @@ options: name: "@azure/load-testing" description: This package contains Microsoft Azure LoadTestingClient client library. version: 1.0.1 - "@typespec/openapi3": - "emitter-output-dir": "{project-root}/generated/openapi" - "file-type": "json" diff --git a/packages/typespec-test/test/openai/generated/openapi/2022-12-01/openapi.json b/packages/typespec-test/test/openai/generated/openapi/2022-12-01/openapi.json index a79f8f890b..c67f6b08c6 100644 --- a/packages/typespec-test/test/openai/generated/openapi/2022-12-01/openapi.json +++ b/packages/typespec-test/test/openai/generated/openapi/2022-12-01/openapi.json @@ -226,7 +226,7 @@ ], "x-ms-enum": { "name": "AzureOpenAIOperationState", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "notRunning", @@ -426,7 +426,7 @@ ], "x-ms-enum": { "name": "ChatRole", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "system", @@ -526,7 +526,7 @@ ], "x-ms-enum": { "name": "CompletionsFinishReason", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "stopped", diff --git a/packages/typespec-test/test/openai/generated/openapi/2023-05-15/openapi.json b/packages/typespec-test/test/openai/generated/openapi/2023-05-15/openapi.json index f95aaa766f..aa2e052bc7 100644 --- a/packages/typespec-test/test/openai/generated/openapi/2023-05-15/openapi.json +++ b/packages/typespec-test/test/openai/generated/openapi/2023-05-15/openapi.json @@ -272,7 +272,7 @@ ], "x-ms-enum": { "name": "AzureOpenAIOperationState", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "notRunning", @@ -472,7 +472,7 @@ ], "x-ms-enum": { "name": "ChatRole", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "system", @@ -572,7 +572,7 @@ ], "x-ms-enum": { "name": "CompletionsFinishReason", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "stopped", diff --git a/packages/typespec-test/test/openai/generated/openapi/2023-06-01-preview/openapi.json b/packages/typespec-test/test/openai/generated/openapi/2023-06-01-preview/openapi.json index c9cb979d37..bcb40001c9 100644 --- a/packages/typespec-test/test/openai/generated/openapi/2023-06-01-preview/openapi.json +++ b/packages/typespec-test/test/openai/generated/openapi/2023-06-01-preview/openapi.json @@ -357,7 +357,7 @@ ], "x-ms-enum": { "name": "AzureOpenAIOperationState", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "notRunning", @@ -608,7 +608,7 @@ ], "x-ms-enum": { "name": "ChatRole", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "system", @@ -722,7 +722,7 @@ ], "x-ms-enum": { "name": "CompletionsFinishReason", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "stopped", @@ -968,7 +968,7 @@ ], "x-ms-enum": { "name": "ContentFilterSeverity", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "safe", @@ -1123,7 +1123,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", @@ -1166,7 +1166,7 @@ ], "x-ms-enum": { "name": "ImageGenerationResponseFormat", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Url", @@ -1237,7 +1237,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", diff --git a/packages/typespec-test/test/openai/generated/openapi/2023-07-01-preview/openapi.json b/packages/typespec-test/test/openai/generated/openapi/2023-07-01-preview/openapi.json index e5dd8a1dea..c25b46cf3c 100644 --- a/packages/typespec-test/test/openai/generated/openapi/2023-07-01-preview/openapi.json +++ b/packages/typespec-test/test/openai/generated/openapi/2023-07-01-preview/openapi.json @@ -357,7 +357,7 @@ ], "x-ms-enum": { "name": "AzureOpenAIOperationState", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "notRunning", @@ -630,7 +630,7 @@ ], "x-ms-enum": { "name": "ChatRole", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "system", @@ -750,7 +750,7 @@ ], "x-ms-enum": { "name": "CompletionsFinishReason", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "stopped", @@ -1001,7 +1001,7 @@ ], "x-ms-enum": { "name": "ContentFilterSeverity", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "safe", @@ -1158,7 +1158,7 @@ ], "x-ms-enum": { "name": "FunctionCallPreset", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "auto", @@ -1231,7 +1231,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", @@ -1274,7 +1274,7 @@ ], "x-ms-enum": { "name": "ImageGenerationResponseFormat", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Url", @@ -1345,7 +1345,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", diff --git a/packages/typespec-test/test/openai/generated/openapi/2023-08-01-preview/openapi.json b/packages/typespec-test/test/openai/generated/openapi/2023-08-01-preview/openapi.json index 796b5d4241..279f438f02 100644 --- a/packages/typespec-test/test/openai/generated/openapi/2023-08-01-preview/openapi.json +++ b/packages/typespec-test/test/openai/generated/openapi/2023-08-01-preview/openapi.json @@ -416,7 +416,7 @@ ], "x-ms-enum": { "name": "AzureChatExtensionType", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "azureCognitiveSearch", @@ -550,7 +550,7 @@ ], "x-ms-enum": { "name": "AzureCognitiveSearchQueryType", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "simple", @@ -592,7 +592,7 @@ ], "x-ms-enum": { "name": "AzureOpenAIOperationState", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "notRunning", @@ -878,7 +878,7 @@ ], "x-ms-enum": { "name": "ChatRole", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "system", @@ -1003,7 +1003,7 @@ ], "x-ms-enum": { "name": "CompletionsFinishReason", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "stopped", @@ -1254,7 +1254,7 @@ ], "x-ms-enum": { "name": "ContentFilterSeverity", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "safe", @@ -1411,7 +1411,7 @@ ], "x-ms-enum": { "name": "FunctionCallPreset", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "auto", @@ -1484,7 +1484,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", @@ -1527,7 +1527,7 @@ ], "x-ms-enum": { "name": "ImageGenerationResponseFormat", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Url", @@ -1598,7 +1598,7 @@ ], "x-ms-enum": { "name": "ImageSize", - "modelAsString": true, + "modelAsString": false, "values": [ { "name": "Size256x256", diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/package.json b/packages/typespec-test/test/openai/generated/typespec-ts/package.json index 2c7e7008b8..49638f1fd4 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/openai/generated/typespec-ts/package.json @@ -40,13 +40,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0" + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2" }, "devDependencies": { "dotenv": "^16.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/review/openai.api.md b/packages/typespec-test/test/openai/generated/typespec-ts/review/openai.api.md index f588aa5c47..4ee970948e 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/review/openai.api.md +++ b/packages/typespec-test/test/openai/generated/typespec-ts/review/openai.api.md @@ -237,7 +237,7 @@ export interface ContentFilterResultsOutput { export type ContentFilterSeverityOutput = "safe" | "low" | "medium" | "high"; // @public -function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, options?: ClientOptions): OpenAIClient; +function createClient(endpointParam: string, credentials: TokenCredential | KeyCredential, { apiVersion, ...options }?: OpenAIClientOptions): OpenAIClient; export default createClient; // @public @@ -528,6 +528,11 @@ export type OpenAIClient = Client & { path: Routes; }; +// @public +export interface OpenAIClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export interface PromptFilterResultOutput { content_filter_results?: ContentFilterResultsOutput; diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai/generated/typespec-ts/src/openAIClient.ts index d50917702d..32fd3fd681 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai/generated/typespec-ts/src/openAIClient.ts @@ -6,6 +6,12 @@ import { logger } from "./logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { OpenAIClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface OpenAIClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `OpenAIClient` * @param endpointParam - Supported Cognitive Services endpoints (protocol and hostname, for example: @@ -16,11 +22,10 @@ import { OpenAIClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {}, + { apiVersion = "2023-08-01-preview", ...options }: OpenAIClientOptions = {}, ): OpenAIClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/openai`; - options.apiVersion = options.apiVersion ?? "2023-08-01-preview"; const userAgentInfo = `azsdk-js-openai-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -41,8 +46,24 @@ export default function createClient( apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "api-key", }, }; - const client = getClient(endpointUrl, credentials, options) as OpenAIClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/src/pollingHelper.ts b/packages/typespec-test/test/openai/generated/typespec-ts/src/pollingHelper.ts index 5517559590..2db7933264 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/src/pollingHelper.ts +++ b/packages/typespec-test/test/openai/generated/typespec-ts/src/pollingHelper.ts @@ -121,7 +121,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -130,7 +130,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/openai/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/openai/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/openai/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/openai/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/openai/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/openai/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/openai/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json b/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json index 7bfffb8df8..3b34bc841e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json @@ -54,7 +54,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -71,7 +71,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md index ab8a03898d..2d3741b329 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md @@ -9,7 +9,7 @@ import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -// @public (undocumented) +// @public export interface AudioOperations { // (undocumented) transcriptions: AudioTranscriptionsOperations; @@ -17,25 +17,25 @@ export interface AudioOperations { translations: AudioTranslationsOperations; } -// @public (undocumented) +// @public export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface AudioTranscriptionsOperations { // (undocumented) create: (audio: CreateTranscriptionRequest, options?: AudioTranscriptionsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface AudioTranslationsCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface AudioTranslationsOperations { // (undocumented) create: (audio: CreateTranslationRequest, options?: AudioTranslationsCreateOptionalParams) => Promise; @@ -78,27 +78,27 @@ export interface ChatCompletionResponseMessage { role: "system" | "user" | "assistant" | "function"; } -// @public (undocumented) +// @public export interface ChatCompletionsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ChatCompletionsOperations { // (undocumented) create: (body: CreateChatCompletionRequest, options?: ChatCompletionsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ChatOperations { // (undocumented) completions: ChatCompletionsOperations; } -// @public (undocumented) +// @public export interface CompletionsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface CompletionsOperations { // (undocumented) create: (body: CreateCompletionRequest, options?: CompletionsCreateOptionalParams) => Promise; @@ -116,7 +116,7 @@ export interface CreateChatCompletionRequest { frequencyPenalty?: number | null; functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; functions?: ChatCompletionFunctions[]; - logitBias?: Record; + logitBias?: Record | null; maxTokens?: number | null; messages: ChatCompletionRequestMessage[]; model: string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; @@ -149,7 +149,7 @@ export interface CreateCompletionRequest { bestOf?: number | null; echo?: boolean | null; frequencyPenalty?: number | null; - logitBias?: Record; + logitBias?: Record | null; logprobs?: number | null; maxTokens?: number | null; model: string | "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; @@ -384,11 +384,11 @@ export interface DeleteModelResponse { object: string; } -// @public (undocumented) +// @public export interface EditsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface EditsOperations { // (undocumented) create: (edit: CreateEditRequest, options?: EditsCreateOptionalParams) => Promise; @@ -401,11 +401,11 @@ export interface Embedding { object: "embedding"; } -// @public (undocumented) +// @public export interface EmbeddingsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface EmbeddingsOperations { // (undocumented) create: (embedding: CreateEmbeddingRequest, options?: EmbeddingsCreateOptionalParams) => Promise; @@ -429,29 +429,28 @@ export interface ErrorResponse { error: ErrorModel; } -// @public (undocumented) +// @public export interface FilesCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface FilesDeleteOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesDownloadOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesOperations { // (undocumented) create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => Promise; - // (undocumented) delete: (fileId: string, options?: FilesDeleteOptionalParams) => Promise; // (undocumented) download: (fileId: string, options?: FilesDownloadOptionalParams) => Promise; @@ -461,7 +460,7 @@ export interface FilesOperations { retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FilesRetrieveOptionalParams extends OperationOptions { } @@ -502,24 +501,24 @@ export interface FineTuneEvent { object: string; } -// @public (undocumented) +// @public export interface FineTunesCancelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesListEventsOptionalParams extends OperationOptions { stream?: boolean; } -// @public (undocumented) +// @public export interface FineTunesListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesOperations { // (undocumented) cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => Promise; @@ -533,7 +532,7 @@ export interface FineTunesOperations { retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FineTunesRetrieveOptionalParams extends OperationOptions { } @@ -575,31 +574,30 @@ export interface FineTuningJobEvent { object: string; } -// @public (undocumented) +// @public export interface FineTuningJobsCancelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJobsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJobsListEventsOptionalParams extends OperationOptions { after?: string; limit?: number; } -// @public (undocumented) +// @public export interface FineTuningJobsListOptionalParams extends OperationOptions { after?: string; limit?: number; } -// @public (undocumented) +// @public export interface FineTuningJobsOperations { // (undocumented) cancel: (fineTuningJobId: string, options?: FineTuningJobsCancelOptionalParams) => Promise; - // (undocumented) create: (job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams) => Promise; // (undocumented) list: (options?: FineTuningJobsListOptionalParams) => Promise; @@ -609,11 +607,11 @@ export interface FineTuningJobsOperations { retrieve: (fineTuningJobId: string, options?: FineTuningJobsRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FineTuningJobsRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningOperations { // (undocumented) jobs: FineTuningJobsOperations; @@ -625,23 +623,23 @@ export interface Image { url?: string; } -// @public (undocumented) +// @public export interface ImagesCreateEditOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface ImagesCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ImagesCreateVariationOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface ImagesOperations { // (undocumented) create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => Promise; @@ -717,17 +715,16 @@ export interface Model { ownedBy: string; } -// @public (undocumented) +// @public export interface ModelsDeleteOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModelsListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModelsOperations { - // (undocumented) delete: (model: string, options?: ModelsDeleteOptionalParams) => Promise; // (undocumented) list: (options?: ModelsListOptionalParams) => Promise; @@ -735,15 +732,15 @@ export interface ModelsOperations { retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ModelsRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModerationsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModerationsOperations { // (undocumented) create: (content: CreateModerationRequest, options?: ModerationsCreateOptionalParams) => Promise; @@ -766,7 +763,7 @@ export class OpenAIClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface OpenAIClientOptions extends ClientOptions { } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts index db3c80e77e..dbf74354b9 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts @@ -2,6 +2,8 @@ // Licensed under the MIT license. import { + chatCompletionRequestMessageSerializer, + chatCompletionFunctionsSerializer, CreateChatCompletionRequest, CreateChatCompletionResponse, } from "../../../models/models.js"; @@ -16,6 +18,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../../../helpers/serializerHelpers.js"; import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( @@ -31,25 +34,11 @@ export function _createSend( ...operationOptionsToRequestParameters(options), body: { model: body["model"], - messages: body["messages"].map((p) => ({ - role: p["role"], - content: p["content"], - name: p["name"], - function_call: !p.functionCall - ? undefined - : { - name: p.functionCall?.["name"], - arguments: p.functionCall?.["arguments"], - }, - })), + messages: body["messages"].map(chatCompletionRequestMessageSerializer), functions: body["functions"] === undefined ? body["functions"] - : body["functions"].map((p) => ({ - name: p["name"], - description: p["description"], - parameters: p["parameters"], - })), + : body["functions"].map(chatCompletionFunctionsSerializer), function_call: body["functionCall"], temperature: body["temperature"], top_p: body["topP"], @@ -58,7 +47,9 @@ export function _createSend( stop: body["stop"], presence_penalty: body["presencePenalty"], frequency_penalty: body["frequencyPenalty"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], stream: body["stream"], }, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts index 634fff501c..a18fdf954c 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts @@ -16,6 +16,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; +import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { CompletionsCreateOptionalParams } from "../../models/options.js"; export function _createSend( @@ -40,7 +41,9 @@ export function _createSend( stop: body["stop"], presence_penalty: body["presencePenalty"], frequency_penalty: body["frequencyPenalty"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], stream: body["stream"], logprobs: body["logprobs"], diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts index 2c6dbd0f87..c85b781dd1 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { OpenAIContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface OpenAIClientOptions extends ClientOptions {} export { OpenAIContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts index c0a04121a8..387f20c869 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts @@ -11,6 +11,7 @@ import { getAudioTranslationsOperations, } from "./translations/index.js"; +/** Interface representing a Audio operations. */ export interface AudioOperations { transcriptions: AudioTranscriptionsOperations; translations: AudioTranslationsOperations; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts index db43a341dd..9ef66e5342 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/transcriptions/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../../api/audio/transcriptions/index.js"; import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a AudioTranscriptions operations. */ export interface AudioTranscriptionsOperations { create: ( audio: CreateTranscriptionRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts index 63f7dc1409..57b177af32 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/translations/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../../api/audio/translations/index.js"; import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a AudioTranslations operations. */ export interface AudioTranslationsOperations { create: ( audio: CreateTranslationRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts index 2a77e8911d..71b39275d2 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/completions/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../../api/chat/completions/index.js"; import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a ChatCompletions operations. */ export interface ChatCompletionsOperations { create: ( body: CreateChatCompletionRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/index.ts index 4bb844f0fe..94b124dcd2 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/chat/index.ts @@ -7,6 +7,7 @@ import { getChatCompletionsOperations, } from "./completions/index.js"; +/** Interface representing a Chat operations. */ export interface ChatOperations { completions: ChatCompletionsOperations; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts index 8ed5b2f942..4e7ee7f63d 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/completions/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../api/completions/index.js"; import { CompletionsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Completions operations. */ export interface CompletionsOperations { create: ( body: CreateCompletionRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts index cb5243dd3c..3e012a3fd3 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/edits/index.ts @@ -6,6 +6,7 @@ import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; import { create } from "../../api/edits/index.js"; import { EditsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Edits operations. */ export interface EditsOperations { create: ( edit: CreateEditRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts index bfaaad7c87..7c4a3df561 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/embeddings/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../api/embeddings/index.js"; import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Embeddings operations. */ export interface EmbeddingsOperations { create: ( embedding: CreateEmbeddingRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts index d455636df8..298ffb428e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts @@ -23,6 +23,7 @@ import { FilesDownloadOptionalParams, } from "../../models/options.js"; +/** Interface representing a Files operations. */ export interface FilesOperations { list: (options?: FilesListOptionalParams) => Promise; create: ( @@ -33,6 +34,11 @@ export interface FilesOperations { fileId: string, options?: FilesRetrieveOptionalParams, ) => Promise; + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( fileId: string, options?: FilesDeleteOptionalParams, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts index f199327d75..bf437586b1 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -23,6 +23,7 @@ import { FineTunesCancelOptionalParams, } from "../../models/options.js"; +/** Interface representing a FineTunes operations. */ export interface FineTunesOperations { create: ( fineTune: CreateFineTuneRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/index.ts index 03f25e1129..ac33945ea4 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/index.ts @@ -7,6 +7,7 @@ import { getFineTuningJobsOperations, } from "./jobs/index.js"; +/** Interface representing a FineTuning operations. */ export interface FineTuningOperations { jobs: FineTuningJobsOperations; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index c083412f8f..b4d7cd951b 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -23,7 +23,16 @@ import { FineTuningJobsCancelOptionalParams, } from "../../../models/options.js"; +/** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ create: ( job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts index 7558487b9b..ce09835e76 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts @@ -15,6 +15,7 @@ import { ImagesCreateVariationOptionalParams, } from "../../models/options.js"; +/** Interface representing a Images operations. */ export interface ImagesOperations { create: ( image: CreateImageRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts index 5e1a082e71..df4bd144dd 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts @@ -14,12 +14,18 @@ import { ModelsDeleteOptionalParams, } from "../../models/options.js"; +/** Interface representing a Models operations. */ export interface ModelsOperations { list: (options?: ModelsListOptionalParams) => Promise; retrieve: ( model: string, options?: ModelsRetrieveOptionalParams, ) => Promise; + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( model: string, options?: ModelsDeleteOptionalParams, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts index 05763c6bd1..cbe1b5cf79 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/moderations/index.ts @@ -9,6 +9,7 @@ import { import { create } from "../../api/moderations/index.js"; import { ModerationsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Moderations operations. */ export interface ModerationsOperations { create: ( content: CreateModerationRequest, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts index 5373dea72e..88dd94d8b9 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + CreateModerationRequest as CreateModerationRequestRest, + CreateImageRequest as CreateImageRequestRest, + CreateImageEditRequest as CreateImageEditRequestRest, + CreateImageVariationRequest as CreateImageVariationRequestRest, + CreateFineTuneRequest as CreateFineTuneRequestRest, + CreateFileRequest as CreateFileRequestRest, + CreateEmbeddingRequest as CreateEmbeddingRequestRest, + CreateEditRequest as CreateEditRequestRest, + CreateCompletionRequest as CreateCompletionRequestRest, + CreateFineTuningJobRequest as CreateFineTuningJobRequestRest, + ChatCompletionRequestMessage as ChatCompletionRequestMessageRest, + ChatCompletionFunctions as ChatCompletionFunctionsRest, + ChatCompletionFunctionParameters as ChatCompletionFunctionParametersRest, + ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOptionRest, + CreateChatCompletionRequest as CreateChatCompletionRequestRest, + CreateTranslationRequest as CreateTranslationRequestRest, + CreateTranscriptionRequest as CreateTranscriptionRequestRest, +} from "../rest/index.js"; + export interface CreateModerationRequest { /** The input text to classify */ input: string | string[]; @@ -14,6 +36,15 @@ export interface CreateModerationRequest { model?: string | "text-moderation-latest" | "text-moderation-stable"; } +export function createModerationRequestSerializer( + item: CreateModerationRequest, +): CreateModerationRequestRest { + return { + input: item["input"], + model: item["model"], + }; +} + export interface CreateModerationResponse { /** The unique identifier for the moderation request. */ id: string; @@ -74,6 +105,18 @@ export interface CreateImageRequest { user?: string; } +export function createImageRequestSerializer( + item: CreateImageRequest, +): CreateImageRequestRest { + return { + prompt: item["prompt"], + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface ImagesResponse { created: Date; data: Image[]; @@ -110,6 +153,23 @@ export interface CreateImageEditRequest { user?: string; } +export function createImageEditRequestSerializer( + item: CreateImageEditRequest, +): CreateImageEditRequestRest { + return { + prompt: item["prompt"], + image: uint8ArrayToString(item["image"], "base64"), + mask: + item["mask"] !== undefined + ? uint8ArrayToString(item["mask"], "base64") + : undefined, + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface CreateImageVariationRequest { /** * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, @@ -125,6 +185,18 @@ export interface CreateImageVariationRequest { user?: string; } +export function createImageVariationRequestSerializer( + item: CreateImageVariationRequest, +): CreateImageVariationRequestRest { + return { + image: uint8ArrayToString(item["image"], "base64"), + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface ListModelsResponse { object: string; data: Model[]; @@ -258,6 +330,25 @@ export interface CreateFineTuneRequest { suffix?: string | null; } +export function createFineTuneRequestSerializer( + item: CreateFineTuneRequest, +): CreateFineTuneRequestRest { + return { + training_file: item["trainingFile"], + validation_file: item["validationFile"], + model: item["model"], + n_epochs: item["nEpochs"], + batch_size: item["batchSize"], + learning_rate_multiplier: item["learningRateMultiplier"], + prompt_loss_rate: item["promptLossRate"], + compute_classification_metrics: item["computeClassificationMetrics"], + classification_n_classes: item["classificationNClasses"], + classification_positive_class: item["classificationPositiveClass"], + classification_betas: item["classificationBetas"], + suffix: item["suffix"], + }; +} + /** The `FineTune` object represents a legacy fine-tune job that has been created through the API. */ export interface FineTune { /** The object identifier, which can be referenced in the API endpoints. */ @@ -371,6 +462,15 @@ export interface CreateFileRequest { purpose: string; } +export function createFileRequestSerializer( + item: CreateFileRequest, +): CreateFileRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + purpose: item["purpose"], + }; +} + export interface DeleteFileResponse { id: string; object: string; @@ -391,6 +491,16 @@ export interface CreateEmbeddingRequest { user?: string; } +export function createEmbeddingRequestSerializer( + item: CreateEmbeddingRequest, +): CreateEmbeddingRequestRest { + return { + model: item["model"], + input: item["input"], + user: item["user"], + }; +} + export interface CreateEmbeddingResponse { /** The object type, which is always "embedding". */ object: "embedding"; @@ -410,7 +520,7 @@ export interface Embedding { object: "embedding"; /** * The embedding vector, which is a list of floats. The length of vector depends on the model as\ - * listed in the [embedding guide](/docs/guides/embeddings). + * * listed in the [embedding guide](/docs/guides/embeddings). */ embedding: number[]; } @@ -444,6 +554,19 @@ export interface CreateEditRequest { topP?: number | null; } +export function createEditRequestSerializer( + item: CreateEditRequest, +): CreateEditRequestRest { + return { + model: item["model"], + input: item["input"], + instruction: item["instruction"], + n: item["n"], + temperature: item["temperature"], + top_p: item["topP"], + }; +} + export interface CreateEditResponse { /** The object type, which is always `edit`. */ object: "edit"; @@ -545,7 +668,7 @@ export interface CreateCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record; + logitBias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -582,6 +705,31 @@ export interface CreateCompletionRequest { bestOf?: number | null; } +export function createCompletionRequestSerializer( + item: CreateCompletionRequest, +): CreateCompletionRequestRest { + return { + model: item["model"], + prompt: item["prompt"], + suffix: item["suffix"], + temperature: item["temperature"], + top_p: item["topP"], + n: item["n"], + max_tokens: item["maxTokens"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + stream: item["stream"], + logprobs: item["logprobs"], + echo: item["echo"], + best_of: item["bestOf"], + }; +} + /** * Represents a completion response from the API. Note: both the streamed and non-streamed response * objects share the same shape (unlike the chat endpoint). @@ -651,6 +799,20 @@ export interface CreateFineTuningJobRequest { suffix?: string | null; } +export function createFineTuningJobRequestSerializer( + item: CreateFineTuningJobRequest, +): CreateFineTuningJobRequestRest { + return { + training_file: item["trainingFile"], + validation_file: item["validationFile"], + model: item["model"], + hyperparameters: !item.hyperparameters + ? undefined + : { n_epochs: item.hyperparameters?.["nEpochs"] }, + suffix: item["suffix"], + }; +} + export interface FineTuningJob { /** The object identifier, which can be referenced in the API endpoints. */ id: string; @@ -752,6 +914,22 @@ export interface ChatCompletionRequestMessage { functionCall?: { name: string; arguments: string }; } +export function chatCompletionRequestMessageSerializer( + item: ChatCompletionRequestMessage, +): ChatCompletionRequestMessageRest { + return { + role: item["role"], + content: item["content"], + name: item["name"], + function_call: !item.functionCall + ? undefined + : { + name: item.functionCall?.["name"], + arguments: item.functionCall?.["arguments"], + }, + }; +} + export interface ChatCompletionFunctions { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and @@ -773,13 +951,39 @@ export interface ChatCompletionFunctions { parameters: ChatCompletionFunctionParameters; } +export function chatCompletionFunctionsSerializer( + item: ChatCompletionFunctions, +): ChatCompletionFunctionsRest { + return { + name: item["name"], + description: item["description"], + parameters: serializeRecord(item.parameters as any) as any, + }; +} + export interface ChatCompletionFunctionParameters extends Record {} +export function chatCompletionFunctionParametersSerializer( + item: ChatCompletionFunctionParameters, +): ChatCompletionFunctionParametersRest { + return { + ...item, + }; +} + export interface ChatCompletionFunctionCallOption { /** The name of the function to call. */ name: string; } +export function chatCompletionFunctionCallOptionSerializer( + item: ChatCompletionFunctionCallOption, +): ChatCompletionFunctionCallOptionRest { + return { + name: item["name"], + }; +} + export interface CreateChatCompletionRequest { /** * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) @@ -867,7 +1071,7 @@ export interface CreateChatCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record; + logitBias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -882,6 +1086,32 @@ export interface CreateChatCompletionRequest { stream?: boolean | null; } +export function createChatCompletionRequestSerializer( + item: CreateChatCompletionRequest, +): CreateChatCompletionRequestRest { + return { + model: item["model"], + messages: item["messages"].map(chatCompletionRequestMessageSerializer), + functions: + item["functions"] === undefined + ? item["functions"] + : item["functions"].map(chatCompletionFunctionsSerializer), + function_call: item["functionCall"], + temperature: item["temperature"], + top_p: item["topP"], + n: item["n"], + max_tokens: item["maxTokens"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + stream: item["stream"], + }; +} + /** Represents a chat completion response returned by model, based on the provided input. */ export interface CreateChatCompletionResponse { /** A unique identifier for the chat completion. */ @@ -937,6 +1167,18 @@ export interface CreateTranslationRequest { temperature?: number; } +export function createTranslationRequestSerializer( + item: CreateTranslationRequest, +): CreateTranslationRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + model: item["model"], + prompt: item["prompt"], + response_format: item["responseFormat"], + temperature: item["temperature"], + }; +} + export interface CreateTranslationResponse { text: string; } @@ -974,6 +1216,19 @@ export interface CreateTranscriptionRequest { language?: string; } +export function createTranscriptionRequestSerializer( + item: CreateTranscriptionRequest, +): CreateTranscriptionRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + model: item["model"], + prompt: item["prompt"], + response_format: item["responseFormat"], + temperature: item["temperature"], + language: item["language"], + }; +} + export interface CreateTranscriptionResponse { text: string; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts index b8ce393d38..81438533fb 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/options.ts @@ -3,20 +3,25 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface AudioTranslationsCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsListOptionalParams extends OperationOptions { /** Identifier for the last job from the previous pagination request. */ after?: string; @@ -24,9 +29,11 @@ export interface FineTuningJobsListOptionalParams extends OperationOptions { limit?: number; } +/** Optional parameters. */ export interface FineTuningJobsRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsListEventsOptionalParams extends OperationOptions { /** Identifier for the last event from the previous pagination request. */ @@ -35,32 +42,45 @@ export interface FineTuningJobsListEventsOptionalParams limit?: number; } +/** Optional parameters. */ export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface CompletionsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface EditsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface EmbeddingsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface FilesRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesDeleteOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesDownloadOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesListEventsOptionalParams extends OperationOptions { /** * Whether to stream events for the fine-tune job. If set to true, events will be sent as @@ -74,22 +94,30 @@ export interface FineTunesListEventsOptionalParams extends OperationOptions { stream?: boolean; } +/** Optional parameters. */ export interface FineTunesCancelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsDeleteOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ImagesCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ImagesCreateEditOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ImagesCreateVariationOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ModerationsCreateOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/models.ts index 91f38eb7c4..a669cfe755 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/models.ts @@ -15,7 +15,7 @@ export interface CreateTranscriptionRequest { | NodeJS.ReadableStream | File; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: string; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -55,7 +55,7 @@ export interface CreateTranslationRequest { | NodeJS.ReadableStream | File; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: string; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -80,19 +80,7 @@ export interface CreateChatCompletionRequest { * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) * table for details on which models work with the Chat API. */ - model: - | string - | "gpt4" - | "gpt-4-0314" - | "gpt-4-0613" - | "gpt-4-32k" - | "gpt-4-32k-0314" - | "gpt-4-32k-0613" - | "gpt-3.5-turbo" - | "gpt-3.5-turbo-16k" - | "gpt-3.5-turbo-0301" - | "gpt-3.5-turbo-0613" - | "gpt-3.5-turbo-16k-0613"; + model: string; /** * A list of messages comprising the conversation so far. * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb). @@ -253,7 +241,7 @@ export interface CreateFineTuningJobRequest { * The name of the model to fine-tune. You can select one of the * [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). */ - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: string; /** The hyperparameters used for the fine-tuning job. */ hyperparameters?: { n_epochs?: "auto" | number }; /** @@ -271,17 +259,7 @@ export interface CreateCompletionRequest { * see all of your available models, or see our [Model overview](/docs/models/overview) for * descriptions of them. */ - model: - | string - | "babbage-002" - | "davinci-002" - | "text-davinci-003" - | "text-davinci-002" - | "text-davinci-001" - | "code-davinci-002" - | "text-curie-001" - | "text-babbage-001" - | "text-ada-001"; + model: string; /** * The prompt(s) to generate completions for, encoded as a string, array of strings, array of * tokens, or array of token arrays. @@ -388,7 +366,7 @@ export interface CreateEditRequest { * ID of the model to use. You can use the `text-davinci-edit-001` or `code-davinci-edit-001` * model with this endpoint. */ - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: string; /** The input text to use as a starting point for the edit. */ input?: string | null; /** The instruction that tells the model how to edit the prompt. */ @@ -414,7 +392,7 @@ export interface CreateEditRequest { export interface CreateEmbeddingRequest { /** ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. */ - model: string | "text-embedding-ada-002"; + model: string; /** * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a * single request, pass an array of strings or array of token arrays. Each input must not exceed @@ -483,7 +461,7 @@ export interface CreateFineTuneRequest { * "davinci", or a fine-tuned model created after 2022-04-21 and before 2023-08-22. To learn more * about these models, see the [Models](/docs/models) documentation. */ - model?: string | "ada" | "babbage" | "curie" | "davinci" | null; + model?: string; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the * training dataset. @@ -639,7 +617,7 @@ export interface CreateModerationRequest { * `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy * of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. */ - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: string; } /** Alias for Stop */ diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/openAIClient.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/openAIClient.ts index 4aac636178..775e475301 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/openAIClient.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/openAIClient.ts @@ -6,6 +6,9 @@ import { logger } from "../logger.js"; import { KeyCredential } from "@azure/core-auth"; import { OpenAIContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface OpenAIContextOptions extends ClientOptions {} + /** * Initialize a new instance of `OpenAIContext` * @param credentials - uniquely identify client credential @@ -13,7 +16,7 @@ import { OpenAIContext } from "./clientDefinitions.js"; */ export default function createClient( credentials: KeyCredential, - options: ClientOptions = {}, + options: OpenAIContextOptions = {}, ): OpenAIContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://api.openai.com/v1`; @@ -31,7 +34,6 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, }; - const client = getClient(endpointUrl, options) as OpenAIContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/outputModels.ts index 6c0b802d8d..c8dc6eb465 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/rest/outputModels.ts @@ -198,7 +198,7 @@ export interface EmbeddingOutput { object: "embedding"; /** * The embedding vector, which is a list of floats. The length of vector depends on the model as\ - * listed in the [embedding guide](/docs/guides/embeddings). + * * listed in the [embedding guide](/docs/guides/embeddings). */ embedding: number[]; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/openai_modular/generated/typespec-ts/package.json index e7cfb64f78..f5381eeeb6 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/package.json @@ -42,7 +42,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -59,7 +59,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md index 009df1e822..680d5bd20d 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md @@ -19,13 +19,13 @@ export interface AudioSpeechOptions { voice: AudioSpeechVoice; } -// @public (undocumented) +// @public export type AudioSpeechOutputFormat = "mp3" | "opus" | "aac" | "flac"; -// @public (undocumented) +// @public export type AudioSpeechVoice = "alloy" | "echo" | "fable" | "onyx" | "nova" | "shimmer"; -// @public (undocumented) +// @public export type AudioTaskLabel = "transcribe" | "translate"; // @public @@ -37,7 +37,7 @@ export interface AudioTranscription { text: string; } -// @public (undocumented) +// @public export type AudioTranscriptionFormat = "json" | "verbose_json" | "text" | "srt" | "vtt"; // @public @@ -74,7 +74,7 @@ export interface AudioTranslation { text: string; } -// @public (undocumented) +// @public export type AudioTranslationFormat = "json" | "verbose_json" | "text" | "srt" | "vtt"; // @public @@ -135,7 +135,7 @@ export interface AzureChatExtensionsMessageContext { intent?: string; } -// @public (undocumented) +// @public export type AzureChatExtensionType = "azure_search" | "azure_ml_index" | "azure_cosmos_db" | "elasticsearch" | "Pinecone"; // @public @@ -255,7 +255,7 @@ export interface AzureSearchIndexFieldMappingOptions { vectorFields?: string[]; } -// @public (undocumented) +// @public export type AzureSearchQueryType = "simple" | "semantic" | "vector" | "vector_simple_hybrid" | "vector_semantic_hybrid"; // @public @@ -275,11 +275,6 @@ export interface ChatChoiceLogProbabilityInfo { content: ChatTokenLogProbabilityResult[] | null; } -// @public -export interface ChatChoiceLogProbabilityInfo { - content: ChatTokenLogProbabilityResult[] | null; -} - // @public export interface ChatCompletions { choices: ChatChoice[]; @@ -382,7 +377,7 @@ export interface ChatCompletionsToolDefinition { // @public export type ChatCompletionsToolDefinitionUnion = ChatCompletionsFunctionToolDefinition | ChatCompletionsToolDefinition; -// @public (undocumented) +// @public export type ChatCompletionsToolSelectionPreset = "auto" | "none"; // @public @@ -407,7 +402,7 @@ export interface ChatMessageImageContentItem extends ChatMessageContentItem { type: "image_url"; } -// @public (undocumented) +// @public export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; // @public @@ -476,7 +471,7 @@ export interface ChatResponseMessage { toolCalls?: ChatCompletionsToolCallUnion[]; } -// @public (undocumented) +// @public export type ChatRole = "system" | "assistant" | "user" | "function" | "tool"; // @public @@ -512,16 +507,8 @@ export interface Completions { usage: CompletionsUsage; } -// @public (undocumented) -export type CompletionsFinishReason = "stop" | "length" | "content_filter" | "function_call" | "tool_calls"; - // @public -export interface CompletionsLogProbabilityModel { - textOffset: number[]; - tokenLogprobs: (number | null)[]; - tokens: string[]; - topLogprobs: Record[]; -} +export type CompletionsFinishReason = "stop" | "length" | "content_filter" | "function_call" | "tool_calls"; // @public export interface CompletionsLogProbabilityModel { @@ -614,7 +601,7 @@ export interface ContentFilterResultsForPrompt { promptIndex: number; } -// @public (undocumented) +// @public export type ContentFilterSeverity = "safe" | "low" | "medium" | "high"; // @public @@ -647,7 +634,7 @@ export interface ElasticsearchIndexFieldMappingOptions { vectorFields?: string[]; } -// @public (undocumented) +// @public export type ElasticsearchQueryType = "simple" | "vector"; // @public @@ -682,7 +669,7 @@ export interface FunctionCall { name: string; } -// @public (undocumented) +// @public export type FunctionCallPreset = "auto" | "none"; // @public @@ -697,43 +684,43 @@ export interface FunctionName { name: string; } -// @public (undocumented) +// @public export interface GetAudioSpeechOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetAudioTranscriptionAsPlainTextOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface GetAudioTranscriptionAsResponseObjectOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface GetAudioTranslationAsPlainTextOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface GetAudioTranslationAsResponseObjectOptionalParams extends OperationOptions { contentType?: string; } -// @public (undocumented) +// @public export interface GetChatCompletionsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetCompletionsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetEmbeddingsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface GetImageGenerationsOptionalParams extends OperationOptions { } @@ -756,10 +743,10 @@ export interface ImageGenerationOptions { user?: string; } -// @public (undocumented) +// @public export type ImageGenerationQuality = "standard" | "hd"; -// @public (undocumented) +// @public export type ImageGenerationResponseFormat = "url" | "b64_json"; // @public @@ -768,10 +755,10 @@ export interface ImageGenerations { data: ImageGenerationData[]; } -// @public (undocumented) +// @public export type ImageGenerationStyle = "natural" | "vivid"; -// @public (undocumented) +// @public export type ImageSize = "256x256" | "512x512" | "1024x1024" | "1792x1024" | "1024x1792"; // @public @@ -799,7 +786,7 @@ export interface OnYourDataAuthenticationOptions { // @public export type OnYourDataAuthenticationOptionsUnion = OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions | OnYourDataEncodedApiKeyAuthenticationOptions | OnYourDataAccessTokenAuthenticationOptions | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions | OnYourDataUserAssignedManagedIdentityAuthenticationOptions | OnYourDataAuthenticationOptions; -// @public (undocumented) +// @public export type OnYourDataAuthenticationType = "api_key" | "connection_string" | "key_and_key_id" | "encoded_api_key" | "access_token" | "system_assigned_managed_identity" | "user_assigned_managed_identity"; // @public @@ -856,7 +843,7 @@ export interface OnYourDataVectorizationSource { type: OnYourDataVectorizationSourceType; } -// @public (undocumented) +// @public export type OnYourDataVectorizationSourceType = "endpoint" | "deployment_name" | "model_id"; // @public @@ -877,7 +864,7 @@ export class OpenAIClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface OpenAIClientOptions extends ClientOptions { apiVersion?: string; } @@ -910,7 +897,7 @@ export interface PineconeFieldMappingOptions { urlField?: string; } -// @public (undocumented) +// @public export type ServiceApiVersions = "2022-12-01" | "2023-05-15" | "2023-06-01-preview" | "2023-07-01-preview" | "2024-02-15-preview"; // @public diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts index 1a906baa11..f85894f385 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { OpenAIContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface OpenAIClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts index c90dc4a31a..be0ec6ccb4 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts @@ -2,6 +2,11 @@ // Licensed under the MIT license. import { + chatRequestMessageUnionSerializer, + functionDefinitionSerializer, + azureChatExtensionConfigurationUnionSerializer, + azureChatEnhancementConfigurationSerializer, + chatCompletionsResponseFormatUnionSerializer, AudioTranscriptionOptions, AudioTranscription, AudioTranslationOptions, @@ -16,10 +21,6 @@ import { EmbeddingsOptions, Embeddings, } from "../models/models.js"; -import { - serializeChatRequestMessageUnion, - serializeAzureChatExtensionConfigurationUnion, -} from "../utils/serializeUtil.js"; import { GetAudioSpeech200Response, GetAudioSpeechDefaultResponse, @@ -48,6 +49,7 @@ import { createRestError, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; +import { serializeRecord } from "../helpers/serializerHelpers.js"; import { GetAudioTranscriptionAsPlainTextOptionalParams, GetAudioTranscriptionAsResponseObjectOptionalParams, @@ -363,7 +365,9 @@ export function _getCompletionsSend( max_tokens: body["maxTokens"], temperature: body["temperature"], top_p: body["topP"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], n: body["n"], logprobs: body["logprobs"], @@ -575,21 +579,19 @@ export function _getChatCompletionsSend( ...operationOptionsToRequestParameters(options), body: { messages: body["messages"].map((p) => - serializeChatRequestMessageUnion(p), + chatRequestMessageUnionSerializer(p), ), functions: body["functions"] === undefined ? body["functions"] - : body["functions"].map((p) => ({ - name: p["name"], - description: p["description"], - parameters: p["parameters"], - })), + : body["functions"].map(functionDefinitionSerializer), function_call: body["functionCall"], max_tokens: body["maxTokens"], temperature: body["temperature"], top_p: body["topP"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], n: body["n"], stop: body["stop"], @@ -601,24 +603,17 @@ export function _getChatCompletionsSend( body["dataSources"] === undefined ? body["dataSources"] : body["dataSources"].map((p) => - serializeAzureChatExtensionConfigurationUnion(p), + azureChatExtensionConfigurationUnionSerializer(p), ), enhancements: !body.enhancements - ? undefined - : { - grounding: !body.enhancements?.grounding - ? undefined - : { enabled: body.enhancements?.grounding?.["enabled"] }, - ocr: !body.enhancements?.ocr - ? undefined - : { enabled: body.enhancements?.ocr?.["enabled"] }, - }, + ? body.enhancements + : azureChatEnhancementConfigurationSerializer(body.enhancements), seed: body["seed"], logprobs: body["logprobs"], top_logprobs: body["topLogprobs"], response_format: !body.responseFormat - ? undefined - : { type: body.responseFormat?.["type"] }, + ? body.responseFormat + : chatCompletionsResponseFormatUnionSerializer(body.responseFormat), tools: body["tools"], tool_choice: body["toolChoice"], }, @@ -989,7 +984,7 @@ export async function _getAudioSpeechDeserialize( throw createRestError(result); } - return result.body; + return result.body as any; } /** Generates text-to-speech audio from the input text. */ diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts index 344fa6e520..049898cc59 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts @@ -1,10 +1,73 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + AudioTranscriptionOptions as AudioTranscriptionOptionsRest, + AudioTranslationOptions as AudioTranslationOptionsRest, + CompletionsOptions as CompletionsOptionsRest, + ChatRequestMessage as ChatRequestMessageRest, + ChatRequestSystemMessage as ChatRequestSystemMessageRest, + ChatRequestUserMessage as ChatRequestUserMessageRest, + ChatMessageContentItem as ChatMessageContentItemRest, + ChatMessageTextContentItem as ChatMessageTextContentItemRest, + ChatMessageImageContentItem as ChatMessageImageContentItemRest, + ChatMessageImageUrl as ChatMessageImageUrlRest, + ChatRequestAssistantMessage as ChatRequestAssistantMessageRest, + ChatCompletionsToolCall as ChatCompletionsToolCallRest, + ChatCompletionsFunctionToolCall as ChatCompletionsFunctionToolCallRest, + FunctionCall as FunctionCallRest, + ChatRequestToolMessage as ChatRequestToolMessageRest, + ChatRequestFunctionMessage as ChatRequestFunctionMessageRest, + FunctionDefinition as FunctionDefinitionRest, + FunctionName as FunctionNameRest, + AzureChatExtensionConfiguration as AzureChatExtensionConfigurationRest, + AzureSearchChatExtensionConfiguration as AzureSearchChatExtensionConfigurationRest, + AzureSearchChatExtensionParameters as AzureSearchChatExtensionParametersRest, + OnYourDataAuthenticationOptions as OnYourDataAuthenticationOptionsRest, + OnYourDataApiKeyAuthenticationOptions as OnYourDataApiKeyAuthenticationOptionsRest, + OnYourDataConnectionStringAuthenticationOptions as OnYourDataConnectionStringAuthenticationOptionsRest, + OnYourDataKeyAndKeyIdAuthenticationOptions as OnYourDataKeyAndKeyIdAuthenticationOptionsRest, + OnYourDataEncodedApiKeyAuthenticationOptions as OnYourDataEncodedApiKeyAuthenticationOptionsRest, + OnYourDataAccessTokenAuthenticationOptions as OnYourDataAccessTokenAuthenticationOptionsRest, + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions as OnYourDataSystemAssignedManagedIdentityAuthenticationOptionsRest, + OnYourDataUserAssignedManagedIdentityAuthenticationOptions as OnYourDataUserAssignedManagedIdentityAuthenticationOptionsRest, + AzureSearchIndexFieldMappingOptions as AzureSearchIndexFieldMappingOptionsRest, + OnYourDataVectorizationSource as OnYourDataVectorizationSourceRest, + OnYourDataEndpointVectorizationSource as OnYourDataEndpointVectorizationSourceRest, + OnYourDataDeploymentNameVectorizationSource as OnYourDataDeploymentNameVectorizationSourceRest, + OnYourDataModelIdVectorizationSource as OnYourDataModelIdVectorizationSourceRest, + AzureMachineLearningIndexChatExtensionConfiguration as AzureMachineLearningIndexChatExtensionConfigurationRest, + AzureMachineLearningIndexChatExtensionParameters as AzureMachineLearningIndexChatExtensionParametersRest, + AzureCosmosDBChatExtensionConfiguration as AzureCosmosDBChatExtensionConfigurationRest, + AzureCosmosDBChatExtensionParameters as AzureCosmosDBChatExtensionParametersRest, + AzureCosmosDBFieldMappingOptions as AzureCosmosDBFieldMappingOptionsRest, + ElasticsearchChatExtensionConfiguration as ElasticsearchChatExtensionConfigurationRest, + ElasticsearchChatExtensionParameters as ElasticsearchChatExtensionParametersRest, + ElasticsearchIndexFieldMappingOptions as ElasticsearchIndexFieldMappingOptionsRest, + PineconeChatExtensionConfiguration as PineconeChatExtensionConfigurationRest, + PineconeChatExtensionParameters as PineconeChatExtensionParametersRest, + PineconeFieldMappingOptions as PineconeFieldMappingOptionsRest, + AzureChatEnhancementConfiguration as AzureChatEnhancementConfigurationRest, + AzureChatGroundingEnhancementConfiguration as AzureChatGroundingEnhancementConfigurationRest, + AzureChatOCREnhancementConfiguration as AzureChatOCREnhancementConfigurationRest, + ChatCompletionsResponseFormat as ChatCompletionsResponseFormatRest, + ChatCompletionsTextResponseFormat as ChatCompletionsTextResponseFormatRest, + ChatCompletionsJsonResponseFormat as ChatCompletionsJsonResponseFormatRest, + ChatCompletionsToolDefinition as ChatCompletionsToolDefinitionRest, + ChatCompletionsFunctionToolDefinition as ChatCompletionsFunctionToolDefinitionRest, + ChatCompletionsNamedToolSelection as ChatCompletionsNamedToolSelectionRest, + ChatCompletionsNamedFunctionToolSelection as ChatCompletionsNamedFunctionToolSelectionRest, + ChatCompletionsFunctionToolSelection as ChatCompletionsFunctionToolSelectionRest, + ChatCompletionsOptions as ChatCompletionsOptionsRest, + ImageGenerationOptions as ImageGenerationOptionsRest, + AudioSpeechOptions as AudioSpeechOptionsRest, + EmbeddingsOptions as EmbeddingsOptionsRest, +} from "../rest/index.js"; import { ErrorModel } from "@azure-rest/core-client"; /** Defines available options for the underlying response format of output transcription information. */ -/** */ export type AudioTranscriptionFormat = | "json" | "verbose_json" @@ -44,6 +107,20 @@ export interface AudioTranscriptionOptions { model?: string; } +export function audioTranscriptionOptionsSerializer( + item: AudioTranscriptionOptions, +): AudioTranscriptionOptionsRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + filename: item["filename"], + response_format: item["responseFormat"], + language: item["language"], + prompt: item["prompt"], + temperature: item["temperature"], + model: item["model"], + }; +} + /** Result information for an operation that transcribed spoken audio into written text. */ export interface AudioTranscription { /** The transcribed text for the provided audio data. */ @@ -62,7 +139,6 @@ export interface AudioTranscription { } /** Defines the possible descriptors for available audio operation responses. */ -/** */ export type AudioTaskLabel = "transcribe" | "translate"; /** @@ -100,7 +176,6 @@ export interface AudioTranscriptionSegment { } /** Defines available options for the underlying response format of output translation information. */ -/** */ export type AudioTranslationFormat = | "json" | "verbose_json" @@ -134,6 +209,19 @@ export interface AudioTranslationOptions { model?: string; } +export function audioTranslationOptionsSerializer( + item: AudioTranslationOptions, +): AudioTranslationOptionsRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + filename: item["filename"], + response_format: item["responseFormat"], + prompt: item["prompt"], + temperature: item["temperature"], + model: item["model"], + }; +} + /** Result information for an operation that translated spoken audio into written text. */ export interface AudioTranslation { /** The translated text for the provided audio data. */ @@ -277,6 +365,30 @@ export interface CompletionsOptions { model?: string; } +export function completionsOptionsSerializer( + item: CompletionsOptions, +): CompletionsOptionsRest { + return { + prompt: item["prompt"], + max_tokens: item["maxTokens"], + temperature: item["temperature"], + top_p: item["topP"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + n: item["n"], + logprobs: item["logprobs"], + echo: item["echo"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + best_of: item["bestOf"], + stream: item["stream"], + model: item["model"], + }; +} + /** * Representation of the response data from a completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -362,7 +474,6 @@ export interface ContentFilterResult { } /** Ratings for the intensity and risk level of harmful content. */ -/** */ export type ContentFilterSeverity = "safe" | "low" | "medium" | "high"; /** Represents the outcome of a detection operation performed by content filtering. */ @@ -469,20 +580,7 @@ export interface CompletionsLogProbabilityModel { textOffset: number[]; } -/** Representation of a log probabilities model for a completions generation. */ -export interface CompletionsLogProbabilityModel { - /** The textual forms of tokens evaluated in this probability model. */ - tokens: string[]; - /** A collection of log probability values for the tokens in this completions data. */ - tokenLogprobs: (number | null)[]; - /** A mapping of tokens to maximum log probability values in this completions data. */ - topLogprobs: Record[]; - /** The text offsets associated with tokens in this completions data. */ - textOffset: number[]; -} - /** Representation of the manner in which a completions response concluded. */ -/** */ export type CompletionsFinishReason = | "stop" | "length" @@ -510,6 +608,44 @@ export interface ChatRequestMessage { role: ChatRole; } +export function chatRequestMessageUnionSerializer( + item: ChatRequestMessageUnion, +) { + switch (item.role) { + case "system": + return chatRequestSystemMessageSerializer( + item as ChatRequestSystemMessage, + ); + + case "user": + return chatRequestUserMessageSerializer(item as ChatRequestUserMessage); + + case "assistant": + return chatRequestAssistantMessageSerializer( + item as ChatRequestAssistantMessage, + ); + + case "tool": + return chatRequestToolMessageSerializer(item as ChatRequestToolMessage); + + case "function": + return chatRequestFunctionMessageSerializer( + item as ChatRequestFunctionMessage, + ); + + default: + return chatRequestMessageSerializer(item); + } +} + +export function chatRequestMessageSerializer( + item: ChatRequestMessageUnion, +): ChatRequestMessageRest { + return { + ...chatRequestMessageUnionSerializer(item), + }; +} + /** * A request chat message containing system instructions that influence how the model will generate a chat completions * response. @@ -523,6 +659,16 @@ export interface ChatRequestSystemMessage extends ChatRequestMessage { name?: string; } +export function chatRequestSystemMessageSerializer( + item: ChatRequestSystemMessage, +): ChatRequestSystemMessageRest { + return { + role: item["role"], + content: item["content"], + name: item["name"], + }; +} + /** A request chat message representing user input to the assistant. */ export interface ChatRequestUserMessage extends ChatRequestMessage { /** The chat role associated with this message, which is always 'user' for user messages. */ @@ -533,12 +679,49 @@ export interface ChatRequestUserMessage extends ChatRequestMessage { name?: string; } +export function chatRequestUserMessageSerializer( + item: ChatRequestUserMessage, +): ChatRequestUserMessageRest { + return { + role: item["role"], + content: item["content"] as any, + name: item["name"], + }; +} + /** An abstract representation of a structured content item within a chat message. */ export interface ChatMessageContentItem { /** the discriminator possible values: text, image_url */ type: string; } +export function chatMessageContentItemUnionSerializer( + item: ChatMessageContentItemUnion, +) { + switch (item.type) { + case "text": + return chatMessageTextContentItemSerializer( + item as ChatMessageTextContentItem, + ); + + case "image_url": + return chatMessageImageContentItemSerializer( + item as ChatMessageImageContentItem, + ); + + default: + return chatMessageContentItemSerializer(item); + } +} + +export function chatMessageContentItemSerializer( + item: ChatMessageContentItemUnion, +): ChatMessageContentItemRest { + return { + ...chatMessageContentItemUnionSerializer(item), + }; +} + /** A structured chat content item containing plain text. */ export interface ChatMessageTextContentItem extends ChatMessageContentItem { /** The discriminated object type: always 'text' for this type. */ @@ -547,6 +730,15 @@ export interface ChatMessageTextContentItem extends ChatMessageContentItem { text: string; } +export function chatMessageTextContentItemSerializer( + item: ChatMessageTextContentItem, +): ChatMessageTextContentItemRest { + return { + type: item["type"], + text: item["text"], + }; +} + /** A structured chat content item containing an image reference. */ export interface ChatMessageImageContentItem extends ChatMessageContentItem { /** The discriminated object type: always 'image_url' for this type. */ @@ -555,6 +747,15 @@ export interface ChatMessageImageContentItem extends ChatMessageContentItem { imageUrl: ChatMessageImageUrl; } +export function chatMessageImageContentItemSerializer( + item: ChatMessageImageContentItem, +): ChatMessageImageContentItemRest { + return { + type: item["type"], + image_url: chatMessageImageUrlSerializer(item.imageUrl), + }; +} + /** An internet location from which the model may retrieve an image. */ export interface ChatMessageImageUrl { /** The URL of the image. */ @@ -566,8 +767,16 @@ export interface ChatMessageImageUrl { detail?: ChatMessageImageDetailLevel; } +export function chatMessageImageUrlSerializer( + item: ChatMessageImageUrl, +): ChatMessageImageUrlRest { + return { + url: item["url"], + detail: item["detail"], + }; +} + /** A representation of the possible image detail levels for image-based chat completions message content. */ -/** */ export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; /** A request chat message representing response or action from the assistant. */ @@ -590,6 +799,20 @@ export interface ChatRequestAssistantMessage extends ChatRequestMessage { functionCall?: FunctionCall; } +export function chatRequestAssistantMessageSerializer( + item: ChatRequestAssistantMessage, +): ChatRequestAssistantMessageRest { + return { + role: item["role"], + content: item["content"], + name: item["name"], + tool_calls: item["toolCalls"], + function_call: !item.functionCall + ? item.functionCall + : functionCallSerializer(item.functionCall), + }; +} + /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. @@ -601,6 +824,29 @@ export interface ChatCompletionsToolCall { id: string; } +export function chatCompletionsToolCallUnionSerializer( + item: ChatCompletionsToolCallUnion, +) { + switch (item.type) { + case "function": + return chatCompletionsFunctionToolCallSerializer( + item as ChatCompletionsFunctionToolCall, + ); + + default: + return chatCompletionsToolCallSerializer(item); + } +} + +export function chatCompletionsToolCallSerializer( + item: ChatCompletionsToolCallUnion, +): ChatCompletionsToolCallRest { + return { + type: item["type"], + id: item["id"], + }; +} + /** * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents * a function invocation needed for a subsequent chat completions request to resolve. @@ -613,6 +859,16 @@ export interface ChatCompletionsFunctionToolCall function: FunctionCall; } +export function chatCompletionsFunctionToolCallSerializer( + item: ChatCompletionsFunctionToolCall, +): ChatCompletionsFunctionToolCallRest { + return { + type: item["type"], + id: item["id"], + function: functionCallSerializer(item.function), + }; +} + /** The name and arguments of a function that should be called, as generated by the model. */ export interface FunctionCall { /** The name of the function to call. */ @@ -626,6 +882,13 @@ export interface FunctionCall { arguments: string; } +export function functionCallSerializer(item: FunctionCall): FunctionCallRest { + return { + name: item["name"], + arguments: item["arguments"], + }; +} + /** A request chat message representing requested output from a configured tool. */ export interface ChatRequestToolMessage extends ChatRequestMessage { /** The chat role associated with this message, which is always 'tool' for tool messages. */ @@ -636,6 +899,16 @@ export interface ChatRequestToolMessage extends ChatRequestMessage { toolCallId: string; } +export function chatRequestToolMessageSerializer( + item: ChatRequestToolMessage, +): ChatRequestToolMessageRest { + return { + role: item["role"], + content: item["content"], + tool_call_id: item["toolCallId"], + }; +} + /** A request chat message representing requested output from a configured function. */ export interface ChatRequestFunctionMessage extends ChatRequestMessage { /** The chat role associated with this message, which is always 'function' for function messages. */ @@ -646,8 +919,17 @@ export interface ChatRequestFunctionMessage extends ChatRequestMessage { content: string | null; } +export function chatRequestFunctionMessageSerializer( + item: ChatRequestFunctionMessage, +): ChatRequestFunctionMessageRest { + return { + role: item["role"], + name: item["name"], + content: item["content"], + }; +} + /** A description of the intended purpose of a message within a chat completions interaction. */ -/** */ export type ChatRole = "system" | "assistant" | "user" | "function" | "tool"; /** The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ @@ -663,11 +945,20 @@ export interface FunctionDefinition { parameters?: any; } +export function functionDefinitionSerializer( + item: FunctionDefinition, +): FunctionDefinitionRest { + return { + name: item["name"], + description: item["description"], + parameters: item["parameters"], + }; +} + /** * The collection of predefined behaviors for handling request-provided function information in a chat completions * operation. */ -/** */ export type FunctionCallPreset = "auto" | "none"; /** @@ -679,6 +970,12 @@ export interface FunctionName { name: string; } +export function functionNameSerializer(item: FunctionName): FunctionNameRest { + return { + name: item["name"], + }; +} + /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. @@ -689,6 +986,48 @@ export interface AzureChatExtensionConfiguration { type: AzureChatExtensionType; } +export function azureChatExtensionConfigurationUnionSerializer( + item: AzureChatExtensionConfigurationUnion, +) { + switch (item.type) { + case "azure_search": + return azureSearchChatExtensionConfigurationSerializer( + item as AzureSearchChatExtensionConfiguration, + ); + + case "azure_ml_index": + return azureMachineLearningIndexChatExtensionConfigurationSerializer( + item as AzureMachineLearningIndexChatExtensionConfiguration, + ); + + case "azure_cosmos_db": + return azureCosmosDBChatExtensionConfigurationSerializer( + item as AzureCosmosDBChatExtensionConfiguration, + ); + + case "elasticsearch": + return elasticsearchChatExtensionConfigurationSerializer( + item as ElasticsearchChatExtensionConfiguration, + ); + + case "Pinecone": + return pineconeChatExtensionConfigurationSerializer( + item as PineconeChatExtensionConfiguration, + ); + + default: + return azureChatExtensionConfigurationSerializer(item); + } +} + +export function azureChatExtensionConfigurationSerializer( + item: AzureChatExtensionConfigurationUnion, +): AzureChatExtensionConfigurationRest { + return { + ...azureChatExtensionConfigurationUnionSerializer(item), + }; +} + /** * A specific representation of configurable options for Azure Search when using it as an Azure OpenAI chat * extension. @@ -704,6 +1043,15 @@ export interface AzureSearchChatExtensionConfiguration parameters: AzureSearchChatExtensionParameters; } +export function azureSearchChatExtensionConfigurationSerializer( + item: AzureSearchChatExtensionConfiguration, +): AzureSearchChatExtensionConfigurationRest { + return { + type: item["type"], + parameters: azureSearchChatExtensionParametersSerializer(item.parameters), + }; +} + /** Parameters for Azure Cognitive Search when used as an Azure OpenAI chat extension. The supported authentication types are APIKey, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. */ export interface AzureSearchChatExtensionParameters { /** @@ -738,12 +1086,89 @@ export interface AzureSearchChatExtensionParameters { embeddingDependency?: OnYourDataVectorizationSourceUnion; } +export function azureSearchChatExtensionParametersSerializer( + item: AzureSearchChatExtensionParameters, +): AzureSearchChatExtensionParametersRest { + return { + authentication: !item.authentication + ? item.authentication + : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + top_n_documents: item["topNDocuments"], + in_scope: item["inScope"], + strictness: item["strictness"], + role_information: item["roleInformation"], + endpoint: item["endpoint"], + index_name: item["indexName"], + fields_mapping: !item.fieldsMapping + ? item.fieldsMapping + : azureSearchIndexFieldMappingOptionsSerializer(item.fieldsMapping), + query_type: item["queryType"], + semantic_configuration: item["semanticConfiguration"], + filter: item["filter"], + embedding_dependency: !item.embeddingDependency + ? item.embeddingDependency + : onYourDataVectorizationSourceUnionSerializer(item.embeddingDependency), + }; +} + /** The authentication options for Azure OpenAI On Your Data. */ export interface OnYourDataAuthenticationOptions { /** the discriminator possible values: api_key, connection_string, key_and_key_id, encoded_api_key, access_token, system_assigned_managed_identity, user_assigned_managed_identity */ type: OnYourDataAuthenticationType; } +export function onYourDataAuthenticationOptionsUnionSerializer( + item: OnYourDataAuthenticationOptionsUnion, +) { + switch (item.type) { + case "api_key": + return onYourDataApiKeyAuthenticationOptionsSerializer( + item as OnYourDataApiKeyAuthenticationOptions, + ); + + case "connection_string": + return onYourDataConnectionStringAuthenticationOptionsSerializer( + item as OnYourDataConnectionStringAuthenticationOptions, + ); + + case "key_and_key_id": + return onYourDataKeyAndKeyIdAuthenticationOptionsSerializer( + item as OnYourDataKeyAndKeyIdAuthenticationOptions, + ); + + case "encoded_api_key": + return onYourDataEncodedApiKeyAuthenticationOptionsSerializer( + item as OnYourDataEncodedApiKeyAuthenticationOptions, + ); + + case "access_token": + return onYourDataAccessTokenAuthenticationOptionsSerializer( + item as OnYourDataAccessTokenAuthenticationOptions, + ); + + case "system_assigned_managed_identity": + return onYourDataSystemAssignedManagedIdentityAuthenticationOptionsSerializer( + item as OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, + ); + + case "user_assigned_managed_identity": + return onYourDataUserAssignedManagedIdentityAuthenticationOptionsSerializer( + item as OnYourDataUserAssignedManagedIdentityAuthenticationOptions, + ); + + default: + return onYourDataAuthenticationOptionsSerializer(item); + } +} + +export function onYourDataAuthenticationOptionsSerializer( + item: OnYourDataAuthenticationOptionsUnion, +): OnYourDataAuthenticationOptionsRest { + return { + ...onYourDataAuthenticationOptionsUnionSerializer(item), + }; +} + /** The authentication options for Azure OpenAI On Your Data when using an API key. */ export interface OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -753,6 +1178,15 @@ export interface OnYourDataApiKeyAuthenticationOptions key: string; } +export function onYourDataApiKeyAuthenticationOptionsSerializer( + item: OnYourDataApiKeyAuthenticationOptions, +): OnYourDataApiKeyAuthenticationOptionsRest { + return { + type: item["type"], + key: item["key"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using a connection string. */ export interface OnYourDataConnectionStringAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -762,6 +1196,15 @@ export interface OnYourDataConnectionStringAuthenticationOptions connectionString: string; } +export function onYourDataConnectionStringAuthenticationOptionsSerializer( + item: OnYourDataConnectionStringAuthenticationOptions, +): OnYourDataConnectionStringAuthenticationOptionsRest { + return { + type: item["type"], + connection_string: item["connectionString"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ export interface OnYourDataKeyAndKeyIdAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -773,6 +1216,16 @@ export interface OnYourDataKeyAndKeyIdAuthenticationOptions keyId: string; } +export function onYourDataKeyAndKeyIdAuthenticationOptionsSerializer( + item: OnYourDataKeyAndKeyIdAuthenticationOptions, +): OnYourDataKeyAndKeyIdAuthenticationOptionsRest { + return { + type: item["type"], + key: item["key"], + key_id: item["keyId"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch encoded API key. */ export interface OnYourDataEncodedApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -782,6 +1235,15 @@ export interface OnYourDataEncodedApiKeyAuthenticationOptions encodedApiKey: string; } +export function onYourDataEncodedApiKeyAuthenticationOptionsSerializer( + item: OnYourDataEncodedApiKeyAuthenticationOptions, +): OnYourDataEncodedApiKeyAuthenticationOptionsRest { + return { + type: item["type"], + encoded_api_key: item["encodedApiKey"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using access token. */ export interface OnYourDataAccessTokenAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -791,6 +1253,15 @@ export interface OnYourDataAccessTokenAuthenticationOptions accessToken: string; } +export function onYourDataAccessTokenAuthenticationOptionsSerializer( + item: OnYourDataAccessTokenAuthenticationOptions, +): OnYourDataAccessTokenAuthenticationOptionsRest { + return { + type: item["type"], + access_token: item["accessToken"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -798,6 +1269,14 @@ export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions type: "system_assigned_managed_identity"; } +export function onYourDataSystemAssignedManagedIdentityAuthenticationOptionsSerializer( + item: OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, +): OnYourDataSystemAssignedManagedIdentityAuthenticationOptionsRest { + return { + type: item["type"], + }; +} + /** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { @@ -807,8 +1286,16 @@ export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions managedIdentityResourceId: string; } +export function onYourDataUserAssignedManagedIdentityAuthenticationOptionsSerializer( + item: OnYourDataUserAssignedManagedIdentityAuthenticationOptions, +): OnYourDataUserAssignedManagedIdentityAuthenticationOptionsRest { + return { + type: item["type"], + managed_identity_resource_id: item["managedIdentityResourceId"], + }; +} + /** The authentication types supported with Azure OpenAI On Your Data. */ -/** */ export type OnYourDataAuthenticationType = | "api_key" | "connection_string" @@ -836,8 +1323,21 @@ export interface AzureSearchIndexFieldMappingOptions { imageVectorFields?: string[]; } +export function azureSearchIndexFieldMappingOptionsSerializer( + item: AzureSearchIndexFieldMappingOptions, +): AzureSearchIndexFieldMappingOptionsRest { + return { + title_field: item["titleField"], + url_field: item["urlField"], + filepath_field: item["filepathField"], + content_fields: item["contentFields"], + content_fields_separator: item["contentFieldsSeparator"], + vector_fields: item["vectorFields"], + image_vector_fields: item["imageVectorFields"], + }; +} + /** The type of Azure Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** */ export type AzureSearchQueryType = | "simple" | "semantic" @@ -851,6 +1351,38 @@ export interface OnYourDataVectorizationSource { type: OnYourDataVectorizationSourceType; } +export function onYourDataVectorizationSourceUnionSerializer( + item: OnYourDataVectorizationSourceUnion, +) { + switch (item.type) { + case "endpoint": + return onYourDataEndpointVectorizationSourceSerializer( + item as OnYourDataEndpointVectorizationSource, + ); + + case "deployment_name": + return onYourDataDeploymentNameVectorizationSourceSerializer( + item as OnYourDataDeploymentNameVectorizationSource, + ); + + case "model_id": + return onYourDataModelIdVectorizationSourceSerializer( + item as OnYourDataModelIdVectorizationSource, + ); + + default: + return onYourDataVectorizationSourceSerializer(item); + } +} + +export function onYourDataVectorizationSourceSerializer( + item: OnYourDataVectorizationSourceUnion, +): OnYourDataVectorizationSourceRest { + return { + ...onYourDataVectorizationSourceUnionSerializer(item), + }; +} + /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a public Azure OpenAI endpoint call for embeddings. @@ -865,6 +1397,18 @@ export interface OnYourDataEndpointVectorizationSource authentication: OnYourDataAuthenticationOptionsUnion; } +export function onYourDataEndpointVectorizationSourceSerializer( + item: OnYourDataEndpointVectorizationSource, +): OnYourDataEndpointVectorizationSourceRest { + return { + type: item["type"], + endpoint: item["endpoint"], + authentication: onYourDataAuthenticationOptionsUnionSerializer( + item.authentication, + ), + }; +} + /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on an internal embeddings model deployment name in the same Azure OpenAI resource. @@ -877,6 +1421,15 @@ export interface OnYourDataDeploymentNameVectorizationSource deploymentName: string; } +export function onYourDataDeploymentNameVectorizationSourceSerializer( + item: OnYourDataDeploymentNameVectorizationSource, +): OnYourDataDeploymentNameVectorizationSourceRest { + return { + type: item["type"], + deployment_name: item["deploymentName"], + }; +} + /** * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a search service model ID. Currently only supported by Elasticsearch®. @@ -889,11 +1442,19 @@ export interface OnYourDataModelIdVectorizationSource modelId: string; } +export function onYourDataModelIdVectorizationSourceSerializer( + item: OnYourDataModelIdVectorizationSource, +): OnYourDataModelIdVectorizationSourceRest { + return { + type: item["type"], + model_id: item["modelId"], + }; +} + /** * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with * vector search. */ -/** */ export type OnYourDataVectorizationSourceType = | "endpoint" | "deployment_name" @@ -914,6 +1475,17 @@ export interface AzureMachineLearningIndexChatExtensionConfiguration parameters: AzureMachineLearningIndexChatExtensionParameters; } +export function azureMachineLearningIndexChatExtensionConfigurationSerializer( + item: AzureMachineLearningIndexChatExtensionConfiguration, +): AzureMachineLearningIndexChatExtensionConfigurationRest { + return { + type: item["type"], + parameters: azureMachineLearningIndexChatExtensionParametersSerializer( + item.parameters, + ), + }; +} + /** Parameters for the Azure Machine Learning vector index chat extension. The supported authentication types are AccessToken, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. */ export interface AzureMachineLearningIndexChatExtensionParameters { /** @@ -942,6 +1514,24 @@ export interface AzureMachineLearningIndexChatExtensionParameters { filter?: string; } +export function azureMachineLearningIndexChatExtensionParametersSerializer( + item: AzureMachineLearningIndexChatExtensionParameters, +): AzureMachineLearningIndexChatExtensionParametersRest { + return { + authentication: !item.authentication + ? item.authentication + : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + top_n_documents: item["topNDocuments"], + in_scope: item["inScope"], + strictness: item["strictness"], + role_information: item["roleInformation"], + project_resource_id: item["projectResourceId"], + name: item["name"], + version: item["version"], + filter: item["filter"], + }; +} + /** * A specific representation of configurable options for Azure Cosmos DB when using it as an Azure OpenAI chat * extension. @@ -957,6 +1547,15 @@ export interface AzureCosmosDBChatExtensionConfiguration parameters: AzureCosmosDBChatExtensionParameters; } +export function azureCosmosDBChatExtensionConfigurationSerializer( + item: AzureCosmosDBChatExtensionConfiguration, +): AzureCosmosDBChatExtensionConfigurationRest { + return { + type: item["type"], + parameters: azureCosmosDBChatExtensionParametersSerializer(item.parameters), + }; +} + /** * Parameters to use when configuring Azure OpenAI On Your Data chat extensions when using Azure Cosmos DB for * MongoDB vCore. The supported authentication type is ConnectionString. @@ -990,6 +1589,29 @@ export interface AzureCosmosDBChatExtensionParameters { embeddingDependency: OnYourDataVectorizationSourceUnion; } +export function azureCosmosDBChatExtensionParametersSerializer( + item: AzureCosmosDBChatExtensionParameters, +): AzureCosmosDBChatExtensionParametersRest { + return { + authentication: !item.authentication + ? item.authentication + : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + top_n_documents: item["topNDocuments"], + in_scope: item["inScope"], + strictness: item["strictness"], + role_information: item["roleInformation"], + database_name: item["databaseName"], + container_name: item["containerName"], + index_name: item["indexName"], + fields_mapping: azureCosmosDBFieldMappingOptionsSerializer( + item.fieldsMapping, + ), + embedding_dependency: onYourDataVectorizationSourceUnionSerializer( + item.embeddingDependency, + ), + }; +} + /** Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. */ export interface AzureCosmosDBFieldMappingOptions { /** The name of the index field to use as a title. */ @@ -1006,6 +1628,19 @@ export interface AzureCosmosDBFieldMappingOptions { vectorFields: string[]; } +export function azureCosmosDBFieldMappingOptionsSerializer( + item: AzureCosmosDBFieldMappingOptions, +): AzureCosmosDBFieldMappingOptionsRest { + return { + title_field: item["titleField"], + url_field: item["urlField"], + filepath_field: item["filepathField"], + content_fields: item["contentFields"], + content_fields_separator: item["contentFieldsSeparator"], + vector_fields: item["vectorFields"], + }; +} + /** * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat * extension. @@ -1021,6 +1656,15 @@ export interface ElasticsearchChatExtensionConfiguration parameters: ElasticsearchChatExtensionParameters; } +export function elasticsearchChatExtensionConfigurationSerializer( + item: ElasticsearchChatExtensionConfiguration, +): ElasticsearchChatExtensionConfigurationRest { + return { + type: item["type"], + parameters: elasticsearchChatExtensionParametersSerializer(item.parameters), + }; +} + /** Parameters to use when configuring Elasticsearch® as an Azure OpenAI chat extension. The supported authentication types are KeyAndKeyId and EncodedAPIKey. */ export interface ElasticsearchChatExtensionParameters { /** @@ -1051,6 +1695,29 @@ export interface ElasticsearchChatExtensionParameters { embeddingDependency?: OnYourDataVectorizationSourceUnion; } +export function elasticsearchChatExtensionParametersSerializer( + item: ElasticsearchChatExtensionParameters, +): ElasticsearchChatExtensionParametersRest { + return { + authentication: !item.authentication + ? item.authentication + : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + top_n_documents: item["topNDocuments"], + in_scope: item["inScope"], + strictness: item["strictness"], + role_information: item["roleInformation"], + endpoint: item["endpoint"], + index_name: item["indexName"], + fields_mapping: !item.fieldsMapping + ? item.fieldsMapping + : elasticsearchIndexFieldMappingOptionsSerializer(item.fieldsMapping), + query_type: item["queryType"], + embedding_dependency: !item.embeddingDependency + ? item.embeddingDependency + : onYourDataVectorizationSourceUnionSerializer(item.embeddingDependency), + }; +} + /** Optional settings to control how fields are processed when using a configured Elasticsearch® resource. */ export interface ElasticsearchIndexFieldMappingOptions { /** The name of the index field to use as a title. */ @@ -1067,8 +1734,20 @@ export interface ElasticsearchIndexFieldMappingOptions { vectorFields?: string[]; } +export function elasticsearchIndexFieldMappingOptionsSerializer( + item: ElasticsearchIndexFieldMappingOptions, +): ElasticsearchIndexFieldMappingOptionsRest { + return { + title_field: item["titleField"], + url_field: item["urlField"], + filepath_field: item["filepathField"], + content_fields: item["contentFields"], + content_fields_separator: item["contentFieldsSeparator"], + vector_fields: item["vectorFields"], + }; +} + /** The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** */ export type ElasticsearchQueryType = "simple" | "vector"; /** @@ -1086,6 +1765,15 @@ export interface PineconeChatExtensionConfiguration parameters: PineconeChatExtensionParameters; } +export function pineconeChatExtensionConfigurationSerializer( + item: PineconeChatExtensionConfiguration, +): PineconeChatExtensionConfigurationRest { + return { + type: item["type"], + parameters: pineconeChatExtensionParametersSerializer(item.parameters), + }; +} + /** Parameters for configuring Azure OpenAI Pinecone chat extensions. The supported authentication type is APIKey. */ export interface PineconeChatExtensionParameters { /** @@ -1114,6 +1802,26 @@ export interface PineconeChatExtensionParameters { embeddingDependency: OnYourDataVectorizationSourceUnion; } +export function pineconeChatExtensionParametersSerializer( + item: PineconeChatExtensionParameters, +): PineconeChatExtensionParametersRest { + return { + authentication: !item.authentication + ? item.authentication + : onYourDataAuthenticationOptionsUnionSerializer(item.authentication), + top_n_documents: item["topNDocuments"], + in_scope: item["inScope"], + strictness: item["strictness"], + role_information: item["roleInformation"], + environment: item["environment"], + index_name: item["indexName"], + fields_mapping: pineconeFieldMappingOptionsSerializer(item.fieldsMapping), + embedding_dependency: onYourDataVectorizationSourceUnionSerializer( + item.embeddingDependency, + ), + }; +} + /** Optional settings to control how fields are processed when using a configured Pinecone resource. */ export interface PineconeFieldMappingOptions { /** The name of the index field to use as a title. */ @@ -1128,12 +1836,23 @@ export interface PineconeFieldMappingOptions { contentFieldsSeparator?: string; } +export function pineconeFieldMappingOptionsSerializer( + item: PineconeFieldMappingOptions, +): PineconeFieldMappingOptionsRest { + return { + title_field: item["titleField"], + url_field: item["urlField"], + filepath_field: item["filepathField"], + content_fields: item["contentFields"], + content_fields_separator: item["contentFieldsSeparator"], + }; +} + /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. * The use of this configuration is compatible only with Azure OpenAI. */ -/** */ export type AzureChatExtensionType = | "azure_search" | "azure_ml_index" @@ -1149,18 +1868,47 @@ export interface AzureChatEnhancementConfiguration { ocr?: AzureChatOCREnhancementConfiguration; } +export function azureChatEnhancementConfigurationSerializer( + item: AzureChatEnhancementConfiguration, +): AzureChatEnhancementConfigurationRest { + return { + grounding: !item.grounding + ? item.grounding + : azureChatGroundingEnhancementConfigurationSerializer(item.grounding), + ocr: !item.ocr + ? item.ocr + : azureChatOCREnhancementConfigurationSerializer(item.ocr), + }; +} + /** A representation of the available options for the Azure OpenAI grounding enhancement. */ export interface AzureChatGroundingEnhancementConfiguration { /** Specifies whether the enhancement is enabled. */ enabled: boolean; } +export function azureChatGroundingEnhancementConfigurationSerializer( + item: AzureChatGroundingEnhancementConfiguration, +): AzureChatGroundingEnhancementConfigurationRest { + return { + enabled: item["enabled"], + }; +} + /** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ export interface AzureChatOCREnhancementConfiguration { /** Specifies whether the enhancement is enabled. */ enabled: boolean; } +export function azureChatOCREnhancementConfigurationSerializer( + item: AzureChatOCREnhancementConfiguration, +): AzureChatOCREnhancementConfigurationRest { + return { + enabled: item["enabled"], + }; +} + /** * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON * mode. @@ -1170,6 +1918,33 @@ export interface ChatCompletionsResponseFormat { type: string; } +export function chatCompletionsResponseFormatUnionSerializer( + item: ChatCompletionsResponseFormatUnion, +) { + switch (item.type) { + case "text": + return chatCompletionsTextResponseFormatSerializer( + item as ChatCompletionsTextResponseFormat, + ); + + case "json_object": + return chatCompletionsJsonResponseFormatSerializer( + item as ChatCompletionsJsonResponseFormat, + ); + + default: + return chatCompletionsResponseFormatSerializer(item); + } +} + +export function chatCompletionsResponseFormatSerializer( + item: ChatCompletionsResponseFormatUnion, +): ChatCompletionsResponseFormatRest { + return { + type: item["type"], + }; +} + /** * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response * content that adheres to a specific schema. @@ -1180,6 +1955,14 @@ export interface ChatCompletionsTextResponseFormat type: "text"; } +export function chatCompletionsTextResponseFormatSerializer( + item: ChatCompletionsTextResponseFormat, +): ChatCompletionsTextResponseFormatRest { + return { + type: item["type"], + }; +} + /** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormat { @@ -1187,12 +1970,42 @@ export interface ChatCompletionsJsonResponseFormat type: "json_object"; } +export function chatCompletionsJsonResponseFormatSerializer( + item: ChatCompletionsJsonResponseFormat, +): ChatCompletionsJsonResponseFormatRest { + return { + type: item["type"], + }; +} + /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export interface ChatCompletionsToolDefinition { /** the discriminator possible values: function */ type: string; } +export function chatCompletionsToolDefinitionUnionSerializer( + item: ChatCompletionsToolDefinitionUnion, +) { + switch (item.type) { + case "function": + return chatCompletionsFunctionToolDefinitionSerializer( + item as ChatCompletionsFunctionToolDefinition, + ); + + default: + return chatCompletionsToolDefinitionSerializer(item); + } +} + +export function chatCompletionsToolDefinitionSerializer( + item: ChatCompletionsToolDefinitionUnion, +): ChatCompletionsToolDefinitionRest { + return { + type: item["type"], + }; +} + /** The definition information for a chat completions function tool that can call a function in response to a tool call. */ export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { @@ -1202,8 +2015,16 @@ export interface ChatCompletionsFunctionToolDefinition function: FunctionDefinition; } +export function chatCompletionsFunctionToolDefinitionSerializer( + item: ChatCompletionsFunctionToolDefinition, +): ChatCompletionsFunctionToolDefinitionRest { + return { + type: item["type"], + function: functionDefinitionSerializer(item.function), + }; +} + /** Represents a generic policy for how a chat completions tool may be selected. */ -/** */ export type ChatCompletionsToolSelectionPreset = "auto" | "none"; /** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ @@ -1212,6 +2033,28 @@ export interface ChatCompletionsNamedToolSelection { type: string; } +export function chatCompletionsNamedToolSelectionUnionSerializer( + item: ChatCompletionsNamedToolSelectionUnion, +) { + switch (item.type) { + case "function": + return chatCompletionsNamedFunctionToolSelectionSerializer( + item as ChatCompletionsNamedFunctionToolSelection, + ); + + default: + return chatCompletionsNamedToolSelectionSerializer(item); + } +} + +export function chatCompletionsNamedToolSelectionSerializer( + item: ChatCompletionsNamedToolSelectionUnion, +): ChatCompletionsNamedToolSelectionRest { + return { + type: item["type"], + }; +} + /** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ export interface ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelection { @@ -1221,12 +2064,29 @@ export interface ChatCompletionsNamedFunctionToolSelection function: ChatCompletionsFunctionToolSelection; } +export function chatCompletionsNamedFunctionToolSelectionSerializer( + item: ChatCompletionsNamedFunctionToolSelection, +): ChatCompletionsNamedFunctionToolSelectionRest { + return { + type: item["type"], + function: chatCompletionsFunctionToolSelectionSerializer(item.function), + }; +} + /** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ export interface ChatCompletionsFunctionToolSelection { /** The name of the function that should be called. */ name: string; } +export function chatCompletionsFunctionToolSelectionSerializer( + item: ChatCompletionsFunctionToolSelection, +): ChatCompletionsFunctionToolSelectionRest { + return { + name: item["name"], + }; +} + /** * The configuration information for a chat completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -1339,6 +2199,49 @@ export interface ChatCompletionsOptions { | ChatCompletionsNamedToolSelectionUnion; } +export function chatCompletionsOptionsSerializer( + item: ChatCompletionsOptions, +): ChatCompletionsOptionsRest { + return { + messages: item["messages"].map((p) => chatRequestMessageUnionSerializer(p)), + functions: + item["functions"] === undefined + ? item["functions"] + : item["functions"].map(functionDefinitionSerializer), + function_call: item["functionCall"], + max_tokens: item["maxTokens"], + temperature: item["temperature"], + top_p: item["topP"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + n: item["n"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + stream: item["stream"], + model: item["model"], + data_sources: + item["dataSources"] === undefined + ? item["dataSources"] + : item["dataSources"].map((p) => + azureChatExtensionConfigurationUnionSerializer(p), + ), + enhancements: !item.enhancements + ? item.enhancements + : azureChatEnhancementConfigurationSerializer(item.enhancements), + seed: item["seed"], + logprobs: item["logprobs"], + top_logprobs: item["topLogprobs"], + response_format: !item.responseFormat + ? item.responseFormat + : chatCompletionsResponseFormatUnionSerializer(item.responseFormat), + tools: item["tools"], + tool_choice: item["toolChoice"], + }; +} + /** * Representation of the response data from a chat completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -1471,12 +2374,6 @@ export interface ChatChoiceLogProbabilityInfo { content: ChatTokenLogProbabilityResult[] | null; } -/** Log probability information for a choice, as requested via 'logprobs' and 'top_logprobs'. */ -export interface ChatChoiceLogProbabilityInfo { - /** The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. */ - content: ChatTokenLogProbabilityResult[] | null; -} - /** A representation of the log probability information for a single content token, including a list of most likely tokens if 'top_logprobs' were requested. */ export interface ChatTokenLogProbabilityResult { /** The message content token. */ @@ -1569,7 +2466,6 @@ export interface AzureGroundingEnhancementCoordinatePoint { } /** The desired size of generated images. */ -/** */ export type ImageSize = | "256x256" | "512x512" @@ -1577,19 +2473,16 @@ export type ImageSize = | "1792x1024" | "1024x1792"; /** The format in which the generated images are returned. */ -/** */ export type ImageGenerationResponseFormat = "url" | "b64_json"; /** * An image generation configuration that specifies how the model should prioritize quality, cost, and speed. * Only configurable with dall-e-3 models. */ -/** */ export type ImageGenerationQuality = "standard" | "hd"; /** * An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. * Only configurable with dall-e-3 models. */ -/** */ export type ImageGenerationStyle = "natural" | "vivid"; /** Represents the request data used to generate images. */ @@ -1629,6 +2522,21 @@ export interface ImageGenerationOptions { user?: string; } +export function imageGenerationOptionsSerializer( + item: ImageGenerationOptions, +): ImageGenerationOptionsRest { + return { + model: item["model"], + prompt: item["prompt"], + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + quality: item["quality"], + style: item["style"], + user: item["user"], + }; +} + /** The result of a successful image generation operation. */ export interface ImageGenerations { /** @@ -1640,6 +2548,13 @@ export interface ImageGenerations { data: ImageGenerationData[]; } +export function imageGenerationsSerializer(item: ImageGenerations) { + return { + created: item["created"].getTime(), + data: item["data"].map(imageGenerationDataSerializer), + }; +} + /** * A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image * may be retrieved. @@ -1656,8 +2571,15 @@ export interface ImageGenerationData { revisedPrompt?: string; } +export function imageGenerationDataSerializer(item: ImageGenerationData) { + return { + url: item["url"], + b64_json: item["base64Data"], + revised_prompt: item["revisedPrompt"], + }; +} + /** The available voices for text-to-speech. */ -/** */ export type AudioSpeechVoice = | "alloy" | "echo" @@ -1666,7 +2588,6 @@ export type AudioSpeechVoice = | "nova" | "shimmer"; /** The supported audio output formats for text-to-speech. */ -/** */ export type AudioSpeechOutputFormat = "mp3" | "opus" | "aac" | "flac"; /** A representation of the request options that control the behavior of a text-to-speech operation. */ @@ -1681,6 +2602,17 @@ export interface AudioSpeechOptions { speed?: number; } +export function audioSpeechOptionsSerializer( + item: AudioSpeechOptions, +): AudioSpeechOptionsRest { + return { + input: item["input"], + voice: item["voice"], + response_format: item["responseFormat"], + speed: item["speed"], + }; +} + /** * The configuration information for an embeddings request. * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, @@ -1710,6 +2642,17 @@ export interface EmbeddingsOptions { inputType?: string; } +export function embeddingsOptionsSerializer( + item: EmbeddingsOptions, +): EmbeddingsOptionsRest { + return { + user: item["user"], + model: item["model"], + input: item["input"], + input_type: item["inputType"], + }; +} + /** * Representation of the response data from an embeddings request. * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, @@ -1741,7 +2684,7 @@ export interface EmbeddingsUsage { totalTokens: number; } -/** */ +/** Type of ServiceApiVersions */ export type ServiceApiVersions = | "2022-12-01" | "2023-05-15" diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts index 159debeebb..72b4c03543 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/options.ts @@ -3,36 +3,45 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface GetAudioTranscriptionAsPlainTextOptionalParams extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } +/** Optional parameters. */ export interface GetAudioTranscriptionAsResponseObjectOptionalParams extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } +/** Optional parameters. */ export interface GetAudioTranslationAsPlainTextOptionalParams extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } +/** Optional parameters. */ export interface GetAudioTranslationAsResponseObjectOptionalParams extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } +/** Optional parameters. */ export interface GetCompletionsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetChatCompletionsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetImageGenerationsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetAudioSpeechOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface GetEmbeddingsOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/openAIClient.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/openAIClient.ts index e553197b40..ad00233515 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/openAIClient.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/openAIClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { OpenAIContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface OpenAIContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `OpenAIContext` * @param endpointParam - Supported Cognitive Services endpoints (protocol and hostname, for example: @@ -16,11 +22,10 @@ import { OpenAIContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {}, + { apiVersion = "2024-02-15-preview", ...options }: OpenAIContextOptions = {}, ): OpenAIContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/openai`; - options.apiVersion = options.apiVersion ?? "2024-02-15-preview"; const userAgentInfo = `azsdk-js-openai_modular-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -41,8 +46,24 @@ export default function createClient( apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "api-key", }, }; - const client = getClient(endpointUrl, credentials, options) as OpenAIContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/responses.ts index 09b82e50bc..dd28894766 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/rest/responses.ts @@ -12,11 +12,17 @@ import { EmbeddingsOutput, } from "./outputModels.js"; +export interface GetAudioTranscriptionAsPlainText200Headers { + /** The content type 'text/plain' for the audio text response. */ + "content-type": "text/plain"; +} + /** The request has succeeded. */ export interface GetAudioTranscriptionAsPlainText200Response extends HttpResponse { status: "200"; body: string; + headers: RawHttpHeaders & GetAudioTranscriptionAsPlainText200Headers; } export interface GetAudioTranscriptionAsPlainTextDefaultHeaders { @@ -50,11 +56,17 @@ export interface GetAudioTranscriptionAsResponseObjectDefaultResponse headers: RawHttpHeaders & GetAudioTranscriptionAsResponseObjectDefaultHeaders; } +export interface GetAudioTranslationAsPlainText200Headers { + /** The content type 'text/plain' for the audio text response. */ + "content-type": "text/plain"; +} + /** The request has succeeded. */ export interface GetAudioTranslationAsPlainText200Response extends HttpResponse { status: "200"; body: string; + headers: RawHttpHeaders & GetAudioTranslationAsPlainText200Headers; } export interface GetAudioTranslationAsPlainTextDefaultHeaders { @@ -139,11 +151,17 @@ export interface GetImageGenerationsDefaultResponse extends HttpResponse { headers: RawHttpHeaders & GetImageGenerationsDefaultHeaders; } +export interface GetAudioSpeech200Headers { + /** The content type of the response. Always application/octet-stream for audio/speech responses. */ + "content-type": "application/octet-stream"; +} + /** The request has succeeded. */ export interface GetAudioSpeech200Response extends HttpResponse { status: "200"; /** Value may contain any sequence of octets */ body: Uint8Array; + headers: RawHttpHeaders & GetAudioSpeech200Headers; } export interface GetAudioSpeechDefaultHeaders { diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/openai_modular/spec/client/custom_visibility.tsp b/packages/typespec-test/test/openai_modular/spec/client/custom_visibility.tsp index 6865e7dc07..22e02606eb 100644 --- a/packages/typespec-test/test/openai_modular/spec/client/custom_visibility.tsp +++ b/packages/typespec-test/test/openai_modular/spec/client/custom_visibility.tsp @@ -12,6 +12,7 @@ using Azure.ClientGenerator.Core; @@usage(Azure.OpenAI.ImageGenerationOptions, Usage.input | Usage.output); @@access(Azure.OpenAI.ImageSize, Access.public); @@usage(Azure.OpenAI.ImageGenerations, Usage.input | Usage.output); +@@usage(Azure.OpenAI.ImageGenerationData, Usage.output | Usage.input); // The purpose of this enum is to identify the type of a given result. In C#, this is redundant because we have // strongly-typed classes for each possible result. diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md index 526daf448c..1c1ecc49b8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md @@ -9,7 +9,7 @@ import { KeyCredential } from '@typespec/ts-http-runtime'; import { OperationOptions } from '@typespec/ts-http-runtime'; import { Pipeline } from '@typespec/ts-http-runtime'; -// @public (undocumented) +// @public export interface AudioOperations { // (undocumented) transcriptions: AudioTranscriptionsOperations; @@ -17,25 +17,25 @@ export interface AudioOperations { translations: AudioTranslationsOperations; } -// @public (undocumented) +// @public export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface AudioTranscriptionsOperations { // (undocumented) create: (audio: CreateTranscriptionRequest, options?: AudioTranscriptionsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface AudioTranslationsCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface AudioTranslationsOperations { // (undocumented) create: (audio: CreateTranslationRequest, options?: AudioTranslationsCreateOptionalParams) => Promise; @@ -78,27 +78,27 @@ export interface ChatCompletionResponseMessage { role: "system" | "user" | "assistant" | "function"; } -// @public (undocumented) +// @public export interface ChatCompletionsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ChatCompletionsOperations { // (undocumented) create: (body: CreateChatCompletionRequest, options?: ChatCompletionsCreateOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ChatOperations { // (undocumented) completions: ChatCompletionsOperations; } -// @public (undocumented) +// @public export interface CompletionsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface CompletionsOperations { // (undocumented) create: (body: CreateCompletionRequest, options?: CompletionsCreateOptionalParams) => Promise; @@ -116,7 +116,7 @@ export interface CreateChatCompletionRequest { frequencyPenalty?: number | null; functionCall?: "none" | "auto" | ChatCompletionFunctionCallOption; functions?: ChatCompletionFunctions[]; - logitBias?: Record; + logitBias?: Record | null; maxTokens?: number | null; messages: ChatCompletionRequestMessage[]; model: string | "gpt4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-16k-0613"; @@ -149,7 +149,7 @@ export interface CreateCompletionRequest { bestOf?: number | null; echo?: boolean | null; frequencyPenalty?: number | null; - logitBias?: Record; + logitBias?: Record | null; logprobs?: number | null; maxTokens?: number | null; model: string | "babbage-002" | "davinci-002" | "text-davinci-003" | "text-davinci-002" | "text-davinci-001" | "code-davinci-002" | "text-curie-001" | "text-babbage-001" | "text-ada-001"; @@ -384,11 +384,11 @@ export interface DeleteModelResponse { object: string; } -// @public (undocumented) +// @public export interface EditsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface EditsOperations { // (undocumented) create: (edit: CreateEditRequest, options?: EditsCreateOptionalParams) => Promise; @@ -401,11 +401,11 @@ export interface Embedding { object: "embedding"; } -// @public (undocumented) +// @public export interface EmbeddingsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface EmbeddingsOperations { // (undocumented) create: (embedding: CreateEmbeddingRequest, options?: EmbeddingsCreateOptionalParams) => Promise; @@ -429,29 +429,28 @@ export interface ErrorResponse { error: ErrorModel; } -// @public (undocumented) +// @public export interface FilesCreateOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface FilesDeleteOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesDownloadOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FilesOperations { // (undocumented) create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => Promise; - // (undocumented) delete: (fileId: string, options?: FilesDeleteOptionalParams) => Promise; // (undocumented) download: (fileId: string, options?: FilesDownloadOptionalParams) => Promise; @@ -461,7 +460,7 @@ export interface FilesOperations { retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FilesRetrieveOptionalParams extends OperationOptions { } @@ -502,24 +501,24 @@ export interface FineTuneEvent { object: string; } -// @public (undocumented) +// @public export interface FineTunesCancelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesListEventsOptionalParams extends OperationOptions { stream?: boolean; } -// @public (undocumented) +// @public export interface FineTunesListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTunesOperations { // (undocumented) cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => Promise; @@ -533,7 +532,7 @@ export interface FineTunesOperations { retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FineTunesRetrieveOptionalParams extends OperationOptions { } @@ -575,31 +574,30 @@ export interface FineTuningJobEvent { object: string; } -// @public (undocumented) +// @public export interface FineTuningJobsCancelOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJobsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningJobsListEventsOptionalParams extends OperationOptions { after?: string; limit?: number; } -// @public (undocumented) +// @public export interface FineTuningJobsListOptionalParams extends OperationOptions { after?: string; limit?: number; } -// @public (undocumented) +// @public export interface FineTuningJobsOperations { // (undocumented) cancel: (fineTuningJobId: string, options?: FineTuningJobsCancelOptionalParams) => Promise; - // (undocumented) create: (job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams) => Promise; // (undocumented) list: (options?: FineTuningJobsListOptionalParams) => Promise; @@ -609,11 +607,11 @@ export interface FineTuningJobsOperations { retrieve: (fineTuningJobId: string, options?: FineTuningJobsRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface FineTuningJobsRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface FineTuningOperations { // (undocumented) jobs: FineTuningJobsOperations; @@ -625,23 +623,23 @@ export interface Image { url?: string; } -// @public (undocumented) +// @public export interface ImagesCreateEditOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface ImagesCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ImagesCreateVariationOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface ImagesOperations { // (undocumented) create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => Promise; @@ -717,17 +715,16 @@ export interface Model { ownedBy: string; } -// @public (undocumented) +// @public export interface ModelsDeleteOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModelsListOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModelsOperations { - // (undocumented) delete: (model: string, options?: ModelsDeleteOptionalParams) => Promise; // (undocumented) list: (options?: ModelsListOptionalParams) => Promise; @@ -735,15 +732,15 @@ export interface ModelsOperations { retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface ModelsRetrieveOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModerationsCreateOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ModerationsOperations { // (undocumented) create: (content: CreateModerationRequest, options?: ModerationsCreateOptionalParams) => Promise; @@ -766,7 +763,7 @@ export class OpenAIClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface OpenAIClientOptions extends ClientOptions { } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts index b2badb0a3f..d1a5d73b69 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts @@ -1,6 +1,8 @@ // Licensed under the MIT license. import { + chatCompletionRequestMessageSerializer, + chatCompletionFunctionsSerializer, CreateChatCompletionRequest, CreateChatCompletionResponse, } from "../../../models/models.js"; @@ -15,6 +17,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@typespec/ts-http-runtime"; +import { serializeRecord } from "../../../helpers/serializerHelpers.js"; import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; export function _createSend( @@ -30,25 +33,11 @@ export function _createSend( ...operationOptionsToRequestParameters(options), body: { model: body["model"], - messages: body["messages"].map((p) => ({ - role: p["role"], - content: p["content"], - name: p["name"], - function_call: !p.functionCall - ? undefined - : { - name: p.functionCall?.["name"], - arguments: p.functionCall?.["arguments"], - }, - })), + messages: body["messages"].map(chatCompletionRequestMessageSerializer), functions: body["functions"] === undefined ? body["functions"] - : body["functions"].map((p) => ({ - name: p["name"], - description: p["description"], - parameters: p["parameters"], - })), + : body["functions"].map(chatCompletionFunctionsSerializer), function_call: body["functionCall"], temperature: body["temperature"], top_p: body["topP"], @@ -57,7 +46,9 @@ export function _createSend( stop: body["stop"], presence_penalty: body["presencePenalty"], frequency_penalty: body["frequencyPenalty"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], stream: body["stream"], }, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts index cf5ddcb6af..7479bef2f4 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts @@ -15,6 +15,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@typespec/ts-http-runtime"; +import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { CompletionsCreateOptionalParams } from "../../models/options.js"; export function _createSend( @@ -39,7 +40,9 @@ export function _createSend( stop: body["stop"], presence_penalty: body["presencePenalty"], frequency_penalty: body["frequencyPenalty"], - logit_bias: body["logitBias"], + logit_bias: !body.logitBias + ? body.logitBias + : (serializeRecord(body.logitBias as any) as any), user: body["user"], stream: body["stream"], logprobs: body["logprobs"], diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts index 48b43aa4ff..3edfc00149 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts @@ -5,6 +5,7 @@ import { ClientOptions } from "@typespec/ts-http-runtime"; import { OpenAIContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface OpenAIClientOptions extends ClientOptions {} export { OpenAIContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts index 26612f2539..1806effe85 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts @@ -10,6 +10,7 @@ import { getAudioTranslationsOperations, } from "./translations/index.js"; +/** Interface representing a Audio operations. */ export interface AudioOperations { transcriptions: AudioTranscriptionsOperations; translations: AudioTranslationsOperations; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts index 6dfe00bdfa..16b50560b9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/transcriptions/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../../api/audio/transcriptions/index.js"; import { AudioTranscriptionsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a AudioTranscriptions operations. */ export interface AudioTranscriptionsOperations { create: ( audio: CreateTranscriptionRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts index a36f24b95c..84985a19ce 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/translations/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../../api/audio/translations/index.js"; import { AudioTranslationsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a AudioTranslations operations. */ export interface AudioTranslationsOperations { create: ( audio: CreateTranslationRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts index 778b440e6e..72243bc3c6 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/completions/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../../api/chat/completions/index.js"; import { ChatCompletionsCreateOptionalParams } from "../../../models/options.js"; +/** Interface representing a ChatCompletions operations. */ export interface ChatCompletionsOperations { create: ( body: CreateChatCompletionRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/index.ts index 7659d96eeb..99a2972f50 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/chat/index.ts @@ -6,6 +6,7 @@ import { getChatCompletionsOperations, } from "./completions/index.js"; +/** Interface representing a Chat operations. */ export interface ChatOperations { completions: ChatCompletionsOperations; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts index d7bd15b3a5..b1dc4c1683 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/completions/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../api/completions/index.js"; import { CompletionsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Completions operations. */ export interface CompletionsOperations { create: ( body: CreateCompletionRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts index 14e1b19270..fd6f4720f6 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/edits/index.ts @@ -5,6 +5,7 @@ import { CreateEditRequest, CreateEditResponse } from "../../models/models.js"; import { create } from "../../api/edits/index.js"; import { EditsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Edits operations. */ export interface EditsOperations { create: ( edit: CreateEditRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts index bd886d5e74..8c50e9af6a 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/embeddings/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../api/embeddings/index.js"; import { EmbeddingsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Embeddings operations. */ export interface EmbeddingsOperations { create: ( embedding: CreateEmbeddingRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts index 5321e2ebfd..fb0e70e92d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts @@ -22,6 +22,7 @@ import { FilesDownloadOptionalParams, } from "../../models/options.js"; +/** Interface representing a Files operations. */ export interface FilesOperations { list: (options?: FilesListOptionalParams) => Promise; create: ( @@ -32,6 +33,11 @@ export interface FilesOperations { fileId: string, options?: FilesRetrieveOptionalParams, ) => Promise; + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( fileId: string, options?: FilesDeleteOptionalParams, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts index 4455356413..a07826b0d8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -22,6 +22,7 @@ import { FineTunesCancelOptionalParams, } from "../../models/options.js"; +/** Interface representing a FineTunes operations. */ export interface FineTunesOperations { create: ( fineTune: CreateFineTuneRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/index.ts index 536038cdf1..a2bcd4e19f 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/index.ts @@ -6,6 +6,7 @@ import { getFineTuningJobsOperations, } from "./jobs/index.js"; +/** Interface representing a FineTuning operations. */ export interface FineTuningOperations { jobs: FineTuningJobsOperations; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index 35b7e19ee1..d3166e82f7 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -22,7 +22,16 @@ import { FineTuningJobsCancelOptionalParams, } from "../../../models/options.js"; +/** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ create: ( job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts index 13dc794f5b..fc1867fe7f 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts @@ -14,6 +14,7 @@ import { ImagesCreateVariationOptionalParams, } from "../../models/options.js"; +/** Interface representing a Images operations. */ export interface ImagesOperations { create: ( image: CreateImageRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts index a872034d5a..dc91822eee 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts @@ -13,12 +13,18 @@ import { ModelsDeleteOptionalParams, } from "../../models/options.js"; +/** Interface representing a Models operations. */ export interface ModelsOperations { list: (options?: ModelsListOptionalParams) => Promise; retrieve: ( model: string, options?: ModelsRetrieveOptionalParams, ) => Promise; + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ delete: ( model: string, options?: ModelsDeleteOptionalParams, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts index 6a3d49725e..626ad5ff52 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/moderations/index.ts @@ -8,6 +8,7 @@ import { import { create } from "../../api/moderations/index.js"; import { ModerationsCreateOptionalParams } from "../../models/options.js"; +/** Interface representing a Moderations operations. */ export interface ModerationsOperations { create: ( content: CreateModerationRequest, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..9c73b7fc55 --- /dev/null +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,39 @@ +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts index fb6cce2da7..6826122ed8 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts @@ -1,5 +1,27 @@ // Licensed under the MIT license. +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { + CreateModerationRequest as CreateModerationRequestRest, + CreateImageRequest as CreateImageRequestRest, + CreateImageEditRequest as CreateImageEditRequestRest, + CreateImageVariationRequest as CreateImageVariationRequestRest, + CreateFineTuneRequest as CreateFineTuneRequestRest, + CreateFileRequest as CreateFileRequestRest, + CreateEmbeddingRequest as CreateEmbeddingRequestRest, + CreateEditRequest as CreateEditRequestRest, + CreateCompletionRequest as CreateCompletionRequestRest, + CreateFineTuningJobRequest as CreateFineTuningJobRequestRest, + ChatCompletionRequestMessage as ChatCompletionRequestMessageRest, + ChatCompletionFunctions as ChatCompletionFunctionsRest, + ChatCompletionFunctionParameters as ChatCompletionFunctionParametersRest, + ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOptionRest, + CreateChatCompletionRequest as CreateChatCompletionRequestRest, + CreateTranslationRequest as CreateTranslationRequestRest, + CreateTranscriptionRequest as CreateTranscriptionRequestRest, +} from "../rest/index.js"; +import { uint8ArrayToString } from "@typespec/ts-http-runtime"; + export interface CreateModerationRequest { /** The input text to classify */ input: string | string[]; @@ -13,6 +35,15 @@ export interface CreateModerationRequest { model?: string | "text-moderation-latest" | "text-moderation-stable"; } +export function createModerationRequestSerializer( + item: CreateModerationRequest, +): CreateModerationRequestRest { + return { + input: item["input"], + model: item["model"], + }; +} + export interface CreateModerationResponse { /** The unique identifier for the moderation request. */ id: string; @@ -73,6 +104,18 @@ export interface CreateImageRequest { user?: string; } +export function createImageRequestSerializer( + item: CreateImageRequest, +): CreateImageRequestRest { + return { + prompt: item["prompt"], + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface ImagesResponse { created: Date; data: Image[]; @@ -109,6 +152,23 @@ export interface CreateImageEditRequest { user?: string; } +export function createImageEditRequestSerializer( + item: CreateImageEditRequest, +): CreateImageEditRequestRest { + return { + prompt: item["prompt"], + image: uint8ArrayToString(item["image"], "base64"), + mask: + item["mask"] !== undefined + ? uint8ArrayToString(item["mask"], "base64") + : undefined, + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface CreateImageVariationRequest { /** * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, @@ -124,6 +184,18 @@ export interface CreateImageVariationRequest { user?: string; } +export function createImageVariationRequestSerializer( + item: CreateImageVariationRequest, +): CreateImageVariationRequestRest { + return { + image: uint8ArrayToString(item["image"], "base64"), + n: item["n"], + size: item["size"], + response_format: item["responseFormat"], + user: item["user"], + }; +} + export interface ListModelsResponse { object: string; data: Model[]; @@ -257,6 +329,25 @@ export interface CreateFineTuneRequest { suffix?: string | null; } +export function createFineTuneRequestSerializer( + item: CreateFineTuneRequest, +): CreateFineTuneRequestRest { + return { + training_file: item["trainingFile"], + validation_file: item["validationFile"], + model: item["model"], + n_epochs: item["nEpochs"], + batch_size: item["batchSize"], + learning_rate_multiplier: item["learningRateMultiplier"], + prompt_loss_rate: item["promptLossRate"], + compute_classification_metrics: item["computeClassificationMetrics"], + classification_n_classes: item["classificationNClasses"], + classification_positive_class: item["classificationPositiveClass"], + classification_betas: item["classificationBetas"], + suffix: item["suffix"], + }; +} + /** The `FineTune` object represents a legacy fine-tune job that has been created through the API. */ export interface FineTune { /** The object identifier, which can be referenced in the API endpoints. */ @@ -370,6 +461,15 @@ export interface CreateFileRequest { purpose: string; } +export function createFileRequestSerializer( + item: CreateFileRequest, +): CreateFileRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + purpose: item["purpose"], + }; +} + export interface DeleteFileResponse { id: string; object: string; @@ -390,6 +490,16 @@ export interface CreateEmbeddingRequest { user?: string; } +export function createEmbeddingRequestSerializer( + item: CreateEmbeddingRequest, +): CreateEmbeddingRequestRest { + return { + model: item["model"], + input: item["input"], + user: item["user"], + }; +} + export interface CreateEmbeddingResponse { /** The object type, which is always "embedding". */ object: "embedding"; @@ -409,7 +519,7 @@ export interface Embedding { object: "embedding"; /** * The embedding vector, which is a list of floats. The length of vector depends on the model as\ - * listed in the [embedding guide](/docs/guides/embeddings). + * * listed in the [embedding guide](/docs/guides/embeddings). */ embedding: number[]; } @@ -443,6 +553,19 @@ export interface CreateEditRequest { topP?: number | null; } +export function createEditRequestSerializer( + item: CreateEditRequest, +): CreateEditRequestRest { + return { + model: item["model"], + input: item["input"], + instruction: item["instruction"], + n: item["n"], + temperature: item["temperature"], + top_p: item["topP"], + }; +} + export interface CreateEditResponse { /** The object type, which is always `edit`. */ object: "edit"; @@ -544,7 +667,7 @@ export interface CreateCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record; + logitBias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -581,6 +704,31 @@ export interface CreateCompletionRequest { bestOf?: number | null; } +export function createCompletionRequestSerializer( + item: CreateCompletionRequest, +): CreateCompletionRequestRest { + return { + model: item["model"], + prompt: item["prompt"], + suffix: item["suffix"], + temperature: item["temperature"], + top_p: item["topP"], + n: item["n"], + max_tokens: item["maxTokens"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + stream: item["stream"], + logprobs: item["logprobs"], + echo: item["echo"], + best_of: item["bestOf"], + }; +} + /** * Represents a completion response from the API. Note: both the streamed and non-streamed response * objects share the same shape (unlike the chat endpoint). @@ -650,6 +798,20 @@ export interface CreateFineTuningJobRequest { suffix?: string | null; } +export function createFineTuningJobRequestSerializer( + item: CreateFineTuningJobRequest, +): CreateFineTuningJobRequestRest { + return { + training_file: item["trainingFile"], + validation_file: item["validationFile"], + model: item["model"], + hyperparameters: !item.hyperparameters + ? undefined + : { n_epochs: item.hyperparameters?.["nEpochs"] }, + suffix: item["suffix"], + }; +} + export interface FineTuningJob { /** The object identifier, which can be referenced in the API endpoints. */ id: string; @@ -751,6 +913,22 @@ export interface ChatCompletionRequestMessage { functionCall?: { name: string; arguments: string }; } +export function chatCompletionRequestMessageSerializer( + item: ChatCompletionRequestMessage, +): ChatCompletionRequestMessageRest { + return { + role: item["role"], + content: item["content"], + name: item["name"], + function_call: !item.functionCall + ? undefined + : { + name: item.functionCall?.["name"], + arguments: item.functionCall?.["arguments"], + }, + }; +} + export interface ChatCompletionFunctions { /** * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and @@ -772,13 +950,39 @@ export interface ChatCompletionFunctions { parameters: ChatCompletionFunctionParameters; } +export function chatCompletionFunctionsSerializer( + item: ChatCompletionFunctions, +): ChatCompletionFunctionsRest { + return { + name: item["name"], + description: item["description"], + parameters: serializeRecord(item.parameters as any) as any, + }; +} + export interface ChatCompletionFunctionParameters extends Record {} +export function chatCompletionFunctionParametersSerializer( + item: ChatCompletionFunctionParameters, +): ChatCompletionFunctionParametersRest { + return { + ...item, + }; +} + export interface ChatCompletionFunctionCallOption { /** The name of the function to call. */ name: string; } +export function chatCompletionFunctionCallOptionSerializer( + item: ChatCompletionFunctionCallOption, +): ChatCompletionFunctionCallOptionRest { + return { + name: item["name"], + }; +} + export interface CreateChatCompletionRequest { /** * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) @@ -866,7 +1070,7 @@ export interface CreateChatCompletionRequest { * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 * should result in a ban or exclusive selection of the relevant token. */ - logitBias?: Record; + logitBias?: Record | null; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect * abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). @@ -881,6 +1085,32 @@ export interface CreateChatCompletionRequest { stream?: boolean | null; } +export function createChatCompletionRequestSerializer( + item: CreateChatCompletionRequest, +): CreateChatCompletionRequestRest { + return { + model: item["model"], + messages: item["messages"].map(chatCompletionRequestMessageSerializer), + functions: + item["functions"] === undefined + ? item["functions"] + : item["functions"].map(chatCompletionFunctionsSerializer), + function_call: item["functionCall"], + temperature: item["temperature"], + top_p: item["topP"], + n: item["n"], + max_tokens: item["maxTokens"], + stop: item["stop"], + presence_penalty: item["presencePenalty"], + frequency_penalty: item["frequencyPenalty"], + logit_bias: !item.logitBias + ? item.logitBias + : (serializeRecord(item.logitBias as any) as any), + user: item["user"], + stream: item["stream"], + }; +} + /** Represents a chat completion response returned by model, based on the provided input. */ export interface CreateChatCompletionResponse { /** A unique identifier for the chat completion. */ @@ -936,6 +1166,18 @@ export interface CreateTranslationRequest { temperature?: number; } +export function createTranslationRequestSerializer( + item: CreateTranslationRequest, +): CreateTranslationRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + model: item["model"], + prompt: item["prompt"], + response_format: item["responseFormat"], + temperature: item["temperature"], + }; +} + export interface CreateTranslationResponse { text: string; } @@ -973,6 +1215,19 @@ export interface CreateTranscriptionRequest { language?: string; } +export function createTranscriptionRequestSerializer( + item: CreateTranscriptionRequest, +): CreateTranscriptionRequestRest { + return { + file: uint8ArrayToString(item["file"], "base64"), + model: item["model"], + prompt: item["prompt"], + response_format: item["responseFormat"], + temperature: item["temperature"], + language: item["language"], + }; +} + export interface CreateTranscriptionResponse { text: string; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts index 8185ee1cf7..333cc26fb6 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/options.ts @@ -2,20 +2,25 @@ import { OperationOptions } from "@typespec/ts-http-runtime"; +/** Optional parameters. */ export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface AudioTranslationsCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsListOptionalParams extends OperationOptions { /** Identifier for the last job from the previous pagination request. */ after?: string; @@ -23,9 +28,11 @@ export interface FineTuningJobsListOptionalParams extends OperationOptions { limit?: number; } +/** Optional parameters. */ export interface FineTuningJobsRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTuningJobsListEventsOptionalParams extends OperationOptions { /** Identifier for the last event from the previous pagination request. */ @@ -34,32 +41,45 @@ export interface FineTuningJobsListEventsOptionalParams limit?: number; } +/** Optional parameters. */ export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface CompletionsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface EditsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface EmbeddingsCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesCreateOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface FilesRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesDeleteOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FilesDownloadOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface FineTunesListEventsOptionalParams extends OperationOptions { /** * Whether to stream events for the fine-tune job. If set to true, events will be sent as @@ -73,22 +93,30 @@ export interface FineTunesListEventsOptionalParams extends OperationOptions { stream?: boolean; } +/** Optional parameters. */ export interface FineTunesCancelOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsListOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsRetrieveOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ModelsDeleteOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ImagesCreateOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface ImagesCreateEditOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ImagesCreateVariationOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface ModerationsCreateOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/models.ts index 2ae874260e..30f20a2daf 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/models.ts @@ -14,7 +14,7 @@ export interface CreateTranscriptionRequest { | NodeJS.ReadableStream | File; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: string; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -54,7 +54,7 @@ export interface CreateTranslationRequest { | NodeJS.ReadableStream | File; /** ID of the model to use. Only `whisper-1` is currently available. */ - model: string | "whisper-1"; + model: string; /** * An optional text to guide the model's style or continue a previous audio segment. The * [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. @@ -79,19 +79,7 @@ export interface CreateChatCompletionRequest { * ID of the model to use. See the [model endpoint compatibility](/docs/models/model-endpoint-compatibility) * table for details on which models work with the Chat API. */ - model: - | string - | "gpt4" - | "gpt-4-0314" - | "gpt-4-0613" - | "gpt-4-32k" - | "gpt-4-32k-0314" - | "gpt-4-32k-0613" - | "gpt-3.5-turbo" - | "gpt-3.5-turbo-16k" - | "gpt-3.5-turbo-0301" - | "gpt-3.5-turbo-0613" - | "gpt-3.5-turbo-16k-0613"; + model: string; /** * A list of messages comprising the conversation so far. * [Example Python code](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb). @@ -252,7 +240,7 @@ export interface CreateFineTuningJobRequest { * The name of the model to fine-tune. You can select one of the * [supported models](/docs/guides/fine-tuning/what-models-can-be-fine-tuned). */ - model: string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo"; + model: string; /** The hyperparameters used for the fine-tuning job. */ hyperparameters?: { n_epochs?: "auto" | number }; /** @@ -270,17 +258,7 @@ export interface CreateCompletionRequest { * see all of your available models, or see our [Model overview](/docs/models/overview) for * descriptions of them. */ - model: - | string - | "babbage-002" - | "davinci-002" - | "text-davinci-003" - | "text-davinci-002" - | "text-davinci-001" - | "code-davinci-002" - | "text-curie-001" - | "text-babbage-001" - | "text-ada-001"; + model: string; /** * The prompt(s) to generate completions for, encoded as a string, array of strings, array of * tokens, or array of token arrays. @@ -387,7 +365,7 @@ export interface CreateEditRequest { * ID of the model to use. You can use the `text-davinci-edit-001` or `code-davinci-edit-001` * model with this endpoint. */ - model: string | "text-davinci-edit-001" | "code-davinci-edit-001"; + model: string; /** The input text to use as a starting point for the edit. */ input?: string | null; /** The instruction that tells the model how to edit the prompt. */ @@ -413,7 +391,7 @@ export interface CreateEditRequest { export interface CreateEmbeddingRequest { /** ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models/overview) for descriptions of them. */ - model: string | "text-embedding-ada-002"; + model: string; /** * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a * single request, pass an array of strings or array of token arrays. Each input must not exceed @@ -482,7 +460,7 @@ export interface CreateFineTuneRequest { * "davinci", or a fine-tuned model created after 2022-04-21 and before 2023-08-22. To learn more * about these models, see the [Models](/docs/models) documentation. */ - model?: string | "ada" | "babbage" | "curie" | "davinci" | null; + model?: string; /** * The number of epochs to train the model for. An epoch refers to one full cycle through the * training dataset. @@ -638,7 +616,7 @@ export interface CreateModerationRequest { * `text-moderation-stable`, we will provide advanced notice before updating the model. Accuracy * of `text-moderation-stable` may be slightly lower than for `text-moderation-latest`. */ - model?: string | "text-moderation-latest" | "text-moderation-stable"; + model?: string; } /** Alias for Stop */ diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/openAIClient.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/openAIClient.ts index 15ab0d850e..604f21cbdf 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/openAIClient.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/openAIClient.ts @@ -4,6 +4,9 @@ import { getClient, ClientOptions } from "@typespec/ts-http-runtime"; import { KeyCredential } from "@typespec/ts-http-runtime"; import { OpenAIContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface OpenAIContextOptions extends ClientOptions {} + /** * Initialize a new instance of `OpenAIContext` * @param credentials - uniquely identify client credential @@ -11,7 +14,7 @@ import { OpenAIContext } from "./clientDefinitions.js"; */ export default function createClient( credentials: KeyCredential, - options: ClientOptions = {}, + options: OpenAIContextOptions = {}, ): OpenAIContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://api.openai.com/v1`; @@ -26,7 +29,6 @@ export default function createClient( userAgentPrefix, }, }; - const client = getClient(endpointUrl, options) as OpenAIContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/outputModels.ts index 7c37da0b82..e4ed9656dc 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/rest/outputModels.ts @@ -197,7 +197,7 @@ export interface EmbeddingOutput { object: "embedding"; /** * The embedding vector, which is a list of floats. The length of vector depends on the model as\ - * listed in the [embedding guide](/docs/guides/embeddings). + * * listed in the [embedding guide](/docs/guides/embeddings). */ embedding: number[]; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/package.json index c2b84b1c05..a17f99bbe1 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/package.json @@ -43,7 +43,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -60,7 +60,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md index c87e48635f..e24fcbe6d6 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md @@ -10,27 +10,25 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public (undocumented) +// @public export interface FooOperationsGetAvatarAsJpegOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface FooOperationsGetAvatarAsPngOptionalParams extends OperationOptions { // (undocumented) contentType?: string; } -// @public (undocumented) +// @public export interface FooOperationsOperations { - // (undocumented) getAvatarAsJpeg: (image: Uint8Array, options?: FooOperationsGetAvatarAsJpegOptionalParams) => Promise; - // (undocumented) getAvatarAsPng: (image: Uint8Array, options?: FooOperationsGetAvatarAsPngOptionalParams) => Promise; } -// @public (undocumented) +// @public export type Versions = "2022-08-30"; // @public (undocumented) @@ -40,7 +38,7 @@ export class WidgetManagerClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface WidgetManagerClientOptions extends ClientOptions { apiVersion?: string; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts index 53916935e3..4008cdd70f 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { WidgetManagerContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface WidgetManagerClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts index 324c8a1bf0..5ba82e4dcc 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts @@ -11,11 +11,14 @@ import { FooOperationsGetAvatarAsJpegOptionalParams, } from "../../models/options.js"; +/** Interface representing a FooOperations operations. */ export interface FooOperationsOperations { + /** A remote procedure call (RPC) operation. */ getAvatarAsPng: ( image: Uint8Array, options?: FooOperationsGetAvatarAsPngOptionalParams, ) => Promise; + /** A remote procedure call (RPC) operation. */ getAvatarAsJpeg: ( image: Uint8Array, options?: FooOperationsGetAvatarAsJpegOptionalParams, diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts index f6a8c2c70b..81e99759bd 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/models.ts @@ -2,5 +2,4 @@ // Licensed under the MIT license. /** The Contoso Widget Manager service version. */ -/** */ export type Versions = "2022-08-30"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts index 2c77f1bd22..175df565d1 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/models/options.ts @@ -3,11 +3,13 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface FooOperationsGetAvatarAsPngOptionalParams extends OperationOptions { contentType?: string; } +/** Optional parameters. */ export interface FooOperationsGetAvatarAsJpegOptionalParams extends OperationOptions { contentType?: string; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/rest/widgetManagerClient.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/rest/widgetManagerClient.ts index c07467b524..f85c3d1cd6 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/rest/widgetManagerClient.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/rest/widgetManagerClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { WidgetManagerContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface WidgetManagerContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `WidgetManagerContext` * @param endpointParam - Supported Widget Services endpoints (protocol and hostname, for example: @@ -16,11 +22,10 @@ import { WidgetManagerContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {}, + { apiVersion = "2022-08-30", ...options }: WidgetManagerContextOptions = {}, ): WidgetManagerContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/widget`; - options.apiVersion = options.apiVersion ?? "2022-08-30"; const userAgentInfo = `azsdk-js-overload_modular-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -41,12 +46,28 @@ export default function createClient( apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "api-key", }, }; - const client = getClient( endpointUrl, credentials, options, ) as WidgetManagerContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/package.json b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/package.json index 8d58cf310e..e2726d5575 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/package.json @@ -43,7 +43,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md index b1e8b86b8b..eb7bb1afbe 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/review/parametrized-host.api.md @@ -15,13 +15,12 @@ export interface Collection { readonly collectionId: string; } -// @public (undocumented) +// @public export interface ConfidentialLedgerListCollectionsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface ConfidentialLedgerOperations { - // (undocumented) listCollections: (apiVersion: string, options?: ConfidentialLedgerListCollectionsOptionalParams) => Promise; } @@ -32,7 +31,7 @@ export class ParametrizedHostClient { readonly pipeline: Pipeline; } -// @public (undocumented) +// @public export interface ParametrizedHostClientOptions extends ClientOptions { // (undocumented) apiVersion?: string; diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts index 3a9761d74c..dd05448aca 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { ParametrizedHostContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface ParametrizedHostClientOptions extends ClientOptions { host?: string; subdomain?: string; diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts index 6e80a926da..351cec44b3 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/classic/confidentialLedger/index.ts @@ -6,7 +6,9 @@ import { Collection } from "../../models/models.js"; import { listCollections } from "../../api/confidentialLedger/index.js"; import { ConfidentialLedgerListCollectionsOptionalParams } from "../../models/options.js"; +/** Interface representing a ConfidentialLedger operations. */ export interface ConfidentialLedgerOperations { + /** Collection ids are user-created collections of ledger entries */ listCollections: ( apiVersion: string, options?: ConfidentialLedgerListCollectionsOptionalParams, diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts index 46323eb0b3..7140d59b9e 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/models/options.ts @@ -3,5 +3,6 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface ConfidentialLedgerListCollectionsOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/rest/parametrizedHostClient.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/rest/parametrizedHostClient.ts index c903781a4a..a0eef34f33 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/rest/parametrizedHostClient.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/rest/parametrizedHostClient.ts @@ -6,10 +6,15 @@ import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; import { ParametrizedHostContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ export interface ParametrizedHostContextOptions extends ClientOptions { + /** A sequence of textual characters. */ host?: string; + /** A sequence of textual characters. */ subdomain?: string; + /** A sequence of textual characters. */ sufix?: string; + /** A sequence of textual characters. */ apiVersion?: string; } @@ -20,17 +25,15 @@ export interface ParametrizedHostContextOptions extends ClientOptions { */ export default function createClient( credentials: TokenCredential, - options: ParametrizedHostContextOptions = {}, + { apiVersion = "v1", ...options }: ParametrizedHostContextOptions = {}, ): ParametrizedHostContext { const host = options.host ?? "one"; const subdomain = options.subdomain ?? "two"; const sufix = options.sufix ?? "three"; - const apiVersion = options.apiVersion ?? "v1"; const endpointUrl = options.endpoint ?? options.baseUrl ?? `${host}.${subdomain}.${sufix}.com/${apiVersion}`; - const userAgentInfo = `azsdk-js-parametrized-host-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -50,7 +53,6 @@ export default function createClient( ], }, }; - const client = getClient( endpointUrl, credentials, @@ -58,11 +60,6 @@ export default function createClient( ) as ParametrizedHostContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - if (options.apiVersion) { - logger.warning( - "This client does not support client api-version, please change it at the operation level", - ); - } return client; } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/package.json b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/package.json index b42ddf710e..657d4bfb93 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/package.json @@ -43,7 +43,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md index 26ee3986d4..a77813c4f4 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md @@ -9,7 +9,7 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; -// @public (undocumented) +// @public export type ContentTypeEnum = "application/octet-stream" | "application/json; serialization=Avro" | "application/json; serialization=json" | "text/vnd.ms.protobuf"; // @public @@ -24,18 +24,6 @@ export interface PagedAsyncIterableIterator>; } -// @public -export interface PagedSchemaGroup { - nextLink?: string; - value: SchemaGroup[]; -} - -// @public -export interface PagedVersion { - nextLink?: string; - value: SchemaVersion[]; -} - // @public export interface PageSettings { continuationToken?: string; @@ -47,10 +35,10 @@ export interface Schema { properties: SchemaProperties; } -// @public (undocumented) +// @public export type SchemaContentTypeValues = "application/json; serialization=Avro" | "application/json; serialization=json" | "text/plain; charset=utf-8" | "text/vnd.ms.protobuf"; -// @public (undocumented) +// @public export type SchemaFormat = "Avro" | "Json" | "Custom" | "Protobuf"; // @public @@ -58,43 +46,37 @@ export interface SchemaGroup { readonly groupName: string; } -// @public (undocumented) +// @public export interface SchemaOperationsGetSchemaByIdOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface SchemaOperationsGetSchemaByVersionOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface SchemaOperationsGetSchemaIdByContentOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface SchemaOperationsListSchemaGroupsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface SchemaOperationsListSchemaVersionsOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface SchemaOperationsOperations { - // (undocumented) getSchemaById: (id: string, options?: SchemaOperationsGetSchemaByIdOptionalParams) => Promise; - // (undocumented) getSchemaByVersion: (groupName: string, name: string, schemaVersion: number, options?: SchemaOperationsGetSchemaByVersionOptionalParams) => Promise; - // (undocumented) getSchemaIdByContent: (groupName: string, name: string, contentType: SchemaContentTypeValues, schemaContent: Uint8Array, options?: SchemaOperationsGetSchemaIdByContentOptionalParams) => Promise; - // (undocumented) listSchemaGroups: (options?: SchemaOperationsListSchemaGroupsOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) listSchemaVersions: (groupName: string, name: string, options?: SchemaOperationsListSchemaVersionsOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) registerSchema: (groupName: string, name: string, contentType: SchemaContentTypeValues, content: Uint8Array, options?: SchemaOperationsRegisterSchemaOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface SchemaOperationsRegisterSchemaOptionalParams extends OperationOptions { } @@ -114,7 +96,7 @@ export class SchemaRegistryClient { readonly schemaOperations: SchemaOperationsOperations; } -// @public (undocumented) +// @public export interface SchemaRegistryClientOptions extends ClientOptions { apiVersion?: string; } @@ -124,7 +106,7 @@ export interface SchemaVersion { readonly schemaVersion: number; } -// @public (undocumented) +// @public export type ServiceApiVersions = "2021-10" | "2022-10" | "2023-07-01"; // (No @packageDocumentation comment for this package) diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts index 7988212116..307f96abf5 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts @@ -5,8 +5,8 @@ import { SchemaGroup, SchemaVersion, SchemaContentTypeValues, - PagedSchemaGroup, - PagedVersion, + _PagedSchemaGroup, + _PagedVersion, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -60,7 +60,7 @@ export function _listSchemaGroupsSend( export async function _listSchemaGroupsDeserialize( result: ListSchemaGroups200Response | ListSchemaGroupsDefaultResponse, -): Promise { +): Promise<_PagedSchemaGroup> { if (isUnexpected(result)) { throw createRestError(result); } @@ -135,7 +135,7 @@ export function _listSchemaVersionsSend( export async function _listSchemaVersionsDeserialize( result: ListSchemaVersions200Response | ListSchemaVersionsDefaultResponse, -): Promise { +): Promise<_PagedVersion> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts index eb65bf77f7..1dbf2a564b 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts @@ -6,6 +6,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { SchemaRegistryContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface SchemaRegistryClientOptions extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts index 04fa3780e4..cf1da6b763 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts @@ -25,25 +25,31 @@ import { SchemaOperationsRegisterSchemaOptionalParams, } from "../../models/options.js"; +/** Interface representing a SchemaOperations operations. */ export interface SchemaOperationsOperations { + /** Gets the list of schema groups user is authorized to access. */ listSchemaGroups: ( options?: SchemaOperationsListSchemaGroupsOptionalParams, ) => PagedAsyncIterableIterator; + /** Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. Operation response type is based on serialization of schema requested. */ getSchemaById: ( id: string, options?: SchemaOperationsGetSchemaByIdOptionalParams, ) => Promise; + /** Gets the list of all versions of one schema. */ listSchemaVersions: ( groupName: string, name: string, options?: SchemaOperationsListSchemaVersionsOptionalParams, ) => PagedAsyncIterableIterator; + /** Gets one specific version of one schema. */ getSchemaByVersion: ( groupName: string, name: string, schemaVersion: number, options?: SchemaOperationsGetSchemaByVersionOptionalParams, ) => Promise; + /** Gets the ID referencing an existing schema within the specified schema group, as matched by schema content comparison. */ getSchemaIdByContent: ( groupName: string, name: string, @@ -51,6 +57,7 @@ export interface SchemaOperationsOperations { schemaContent: Uint8Array, options?: SchemaOperationsGetSchemaIdByContentOptionalParams, ) => Promise; + /** Register new schema. If schema of specified name does not exist in specified group, schema is created at version 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. */ registerSchema: ( groupName: string, name: string, diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts index 3229f174b8..852dbc0d50 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts @@ -14,8 +14,6 @@ export { Schema, ContentTypeEnum, ServiceApiVersions, - PagedSchemaGroup, - PagedVersion, SchemaOperationsListSchemaGroupsOptionalParams, SchemaOperationsGetSchemaByIdOptionalParams, SchemaOperationsListSchemaVersionsOptionalParams, diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts index b7e1cdc997..7c62de7c33 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/index.ts @@ -10,8 +10,6 @@ export { Schema, ContentTypeEnum, ServiceApiVersions, - PagedSchemaGroup, - PagedVersion, } from "./models.js"; export { SchemaOperationsListSchemaGroupsOptionalParams, diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts index c23644e09e..58bb7fd7ed 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/models.ts @@ -14,7 +14,6 @@ export interface SchemaVersion { } /** Type of SchemaContentTypeValues */ -/** */ export type SchemaContentTypeValues = | "application/json; serialization=Avro" | "application/json; serialization=json" @@ -35,8 +34,17 @@ export interface SchemaProperties { version: number; } +export function schemaPropertiesSerializer(item: SchemaProperties) { + return { + id: item["id"], + format: item["format"], + groupName: item["groupName"], + name: item["name"], + version: item["version"], + }; +} + /** Represents the format of the schema to be stored by the Schema Registry service. */ -/** */ export type SchemaFormat = "Avro" | "Json" | "Custom" | "Protobuf"; /** The schema content of a schema, along with id and meta properties. */ @@ -47,19 +55,24 @@ export interface Schema { properties: SchemaProperties; } +export function schemaSerializer(item: Schema) { + return { + definition: item["definition"], + properties: schemaPropertiesSerializer(item.properties), + }; +} + /** The content type for the schema. */ -/** */ export type ContentTypeEnum = | "application/octet-stream" | "application/json; serialization=Avro" | "application/json; serialization=json" | "text/vnd.ms.protobuf"; /** Represents the Schema Registry API version to use for requests. */ -/** */ export type ServiceApiVersions = "2021-10" | "2022-10" | "2023-07-01"; /** Paged collection of SchemaGroup items */ -export interface PagedSchemaGroup { +export interface _PagedSchemaGroup { /** The SchemaGroup items on this page */ value: SchemaGroup[]; /** The link to the next page of items */ @@ -67,7 +80,7 @@ export interface PagedSchemaGroup { } /** Paged collection of Version items */ -export interface PagedVersion { +export interface _PagedVersion { /** The Version items on this page */ value: SchemaVersion[]; /** The link to the next page of items */ diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts index c314c5cca1..4965d64938 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/models/options.ts @@ -3,20 +3,26 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface SchemaOperationsListSchemaGroupsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface SchemaOperationsGetSchemaByIdOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface SchemaOperationsListSchemaVersionsOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface SchemaOperationsGetSchemaByVersionOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface SchemaOperationsGetSchemaIdByContentOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface SchemaOperationsRegisterSchemaOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/rest/schemaRegistryClient.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/rest/schemaRegistryClient.ts index f75b877da4..6132cd7be7 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/rest/schemaRegistryClient.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/rest/schemaRegistryClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; import { SchemaRegistryContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface SchemaRegistryContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `SchemaRegistryContext` * @param fullyQualifiedNamespace - The Schema Registry service endpoint, for example 'my-namespace.servicebus.windows.net'. @@ -15,11 +21,10 @@ import { SchemaRegistryContext } from "./clientDefinitions.js"; export default function createClient( fullyQualifiedNamespace: string, credentials: TokenCredential, - options: ClientOptions = {}, + { apiVersion = "2023-07-01", ...options }: SchemaRegistryContextOptions = {}, ): SchemaRegistryContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${fullyQualifiedNamespace}`; - options.apiVersion = options.apiVersion ?? "2023-07-01"; const userAgentInfo = `azsdk-js-schema-registry-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -39,12 +44,28 @@ export default function createClient( ], }, }; - const client = getClient( endpointUrl, credentials, options, ) as SchemaRegistryContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md index 0e7d87b088..bad1f09509 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md @@ -14,7 +14,7 @@ import { RequestParameters } from '@typespec/ts-http-runtime'; import { StreamableMethod } from '@typespec/ts-http-runtime'; // @public -function createClient(endpointParam: string, credentials: KeyCredential, options?: ClientOptions): TodoClient; +function createClient(endpointParam: string, credentials: KeyCredential, options?: TodoClientOptions): TodoClient; export default createClient; // @public (undocumented) @@ -52,6 +52,10 @@ export type TodoClient = Client & { path: Routes; }; +// @public +export interface TodoClientOptions extends ClientOptions { +} + // @public (undocumented) export interface TodoFileAttachmentOutput { filename: string; diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts index b78e158915..500d24474f 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts @@ -4,6 +4,9 @@ import { getClient, ClientOptions } from "@typespec/ts-http-runtime"; import { KeyCredential } from "@typespec/ts-http-runtime"; import { TodoClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface TodoClientOptions extends ClientOptions {} + /** * Initialize a new instance of `TodoClient` * @param endpointParam - The parameter endpointParam @@ -13,10 +16,9 @@ import { TodoClient } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: KeyCredential, - options: ClientOptions = {}, + options: TodoClientOptions = {}, ): TodoClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-todo-non-branded-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -28,7 +30,6 @@ export default function createClient( userAgentPrefix, }, }; - const client = getClient(endpointUrl, options) as TodoClient; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/package.json b/packages/typespec-test/test/translator/generated/typespec-ts/package.json index 0f19126dbf..52c2240b3a 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/translator/generated/typespec-ts/package.json @@ -40,7 +40,7 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", @@ -57,7 +57,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/review/cognitiveservices-translator.api.md b/packages/typespec-test/test/translator/generated/typespec-ts/review/cognitiveservices-translator.api.md index 32b0493e0b..8fbcf87aab 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/review/cognitiveservices-translator.api.md +++ b/packages/typespec-test/test/translator/generated/typespec-ts/review/cognitiveservices-translator.api.md @@ -109,7 +109,7 @@ export interface CommonScriptModelOutput { } // @public -function createClient(endpointParam: string, options?: ClientOptions): TranslatorClient; +function createClient(endpointParam: string, { apiVersion, ...options }?: TranslatorClientOptions): TranslatorClient; export default createClient; // @public (undocumented) @@ -616,6 +616,11 @@ export type TranslatorClient = Client & { path: Routes; }; +// @public +export interface TranslatorClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export interface TransliterableScriptOutput extends CommonScriptModelOutput { toScripts: Array; diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/src/translatorClient.ts b/packages/typespec-test/test/translator/generated/typespec-ts/src/translatorClient.ts index 6b7ef367d6..2072e6f398 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/src/translatorClient.ts +++ b/packages/typespec-test/test/translator/generated/typespec-ts/src/translatorClient.ts @@ -5,6 +5,12 @@ import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "./logger.js"; import { TranslatorClient } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface TranslatorClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `TranslatorClient` * @param endpointParam - Supported Text Translation endpoints (protocol and hostname, for example: @@ -13,10 +19,9 @@ import { TranslatorClient } from "./clientDefinitions.js"; */ export default function createClient( endpointParam: string, - options: ClientOptions = {}, + { apiVersion = "3.0", ...options }: TranslatorClientOptions = {}, ): TranslatorClient { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - options.apiVersion = options.apiVersion ?? "3.0"; const userAgentInfo = `azsdk-js-cognitiveservices-translator-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -31,8 +36,24 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, }; - const client = getClient(endpointUrl, options) as TranslatorClient; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; } diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/translator/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/translator/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/translator/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/translator/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/translator/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/translator/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/translator/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/translator/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json index 7e12294e27..e6df4b23ea 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json @@ -44,13 +44,13 @@ "review/*" ], "dependencies": { - "@azure-rest/core-client": "^2.0.0", + "@azure-rest/core-client": "^2.1.0", "@azure/core-auth": "^1.6.0", "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0-beta.2", - "@azure/abort-controller": "^2.0.0", + "@azure/core-lro": "3.0.0", + "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -64,7 +64,7 @@ "typescript": "~5.4.5", "tshy": "1.11.1", "@azure/core-util": "^1.0.0", - "@azure/identity": "^4.0.1", + "@azure/identity": "^4.2.1", "@vitest/browser": "^1.3.1", "@vitest/coverage-istanbul": "^1.3.1", "playwright": "^1.41.2", diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md index 3e8ce67dd6..e3d223a430 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md @@ -5,19 +5,12 @@ ```ts import { AbortSignalLike } from '@azure/abort-controller'; -import { Client } from '@azure-rest/core-client'; import { ClientOptions } from '@azure-rest/core-client'; -import { ErrorResponse } from '@azure-rest/core-client'; -import { HttpResponse } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; import { OperationState } from '@azure/core-lro'; import { PathUncheckedResponse } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; import { PollerLike } from '@azure/core-lro'; -import { RawHttpHeaders } from '@azure/core-rest-pipeline'; -import { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; -import { RequestParameters } from '@azure-rest/core-client'; -import { StreamableMethod } from '@azure-rest/core-client'; // @public (undocumented) export interface AnalyzeResult { @@ -25,16 +18,23 @@ export interface AnalyzeResult { summary: string; } -// @public (undocumented) +// @public export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { apiVersion?: string; updateIntervalInMs?: number; } -// @public (undocumented) +// @public +export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { + apiVersion?: string; + contentType?: string; + updateIntervalInMs?: number; +} + +// @public export interface BudgetsOperations { - // (undocumented) createOrReplace: (name: string, resource: User, options?: BudgetsCreateOrReplaceOptionalParams) => PollerLike, User>; + createOrUpdate: (name: string, resource: User, options?: BudgetsCreateOrUpdateOptionalParams) => PollerLike, User>; } // @public @@ -48,12 +48,6 @@ export interface CreateWidget { weight: number; } -// @public (undocumented) -export interface ListWidgetsPagesResults { - "odata.nextLink"?: string; - results: Widget[]; -} - // @public (undocumented) export interface NonReferencedModel { prop1: number; @@ -72,10 +66,8 @@ export interface PageSettings { continuationToken?: string; } -// Warning: (ae-forgotten-export) The symbol "WidgetServiceContext" needs to be exported by the entry point index.d.ts -// // @public -export function restorePoller(client: WidgetServiceContext | WidgetServiceClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; +export function restorePoller(client: WidgetServiceClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; // @public (undocumented) export interface RestorePollerOptions extends OperationOptions { @@ -97,7 +89,7 @@ export interface User { role: string; } -// @public (undocumented) +// @public export type Versions = "1.0.0"; // @public (undocumented) @@ -113,21 +105,21 @@ export interface WidgetError { message: string; } -// @public (undocumented) +// @public export interface WidgetsAnalyzeWidgetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface WidgetsCreateOrReplaceOptionalParams extends OperationOptions { apiVersion?: string; updateIntervalInMs?: number; } -// @public (undocumented) +// @public export interface WidgetsCreateWidgetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface WidgetsDeleteWidgetOptionalParams extends OperationOptions { } @@ -139,15 +131,15 @@ export class WidgetServiceClient { readonly widgets: WidgetsOperations; } -// @public (undocumented) +// @public export interface WidgetServiceClientOptions extends ClientOptions { } -// @public (undocumented) +// @public export interface WidgetsGetWidgetOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface WidgetsListWidgetsOptionalParams extends OperationOptions { // (undocumented) nullableDateHeader?: Date | null; @@ -159,37 +151,30 @@ export interface WidgetsListWidgetsOptionalParams extends OperationOptions { optionalHeader?: string; } -// @public (undocumented) +// @public export interface WidgetsListWidgetsPagesOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface WidgetsOperations { - // (undocumented) analyzeWidget: (id: string, options?: WidgetsAnalyzeWidgetOptionalParams) => Promise; - // (undocumented) createOrReplace: (name: string, resource: User, options?: WidgetsCreateOrReplaceOptionalParams) => PollerLike, User>; - // (undocumented) createWidget: (body: CreateWidget, options?: WidgetsCreateWidgetOptionalParams) => Promise; - // (undocumented) deleteWidget: (id: string, options?: WidgetsDeleteWidgetOptionalParams) => Promise; - // (undocumented) getWidget: (id: string, options?: WidgetsGetWidgetOptionalParams) => Promise; - // (undocumented) listWidgets: (requiredHeader: string, bytesHeader: Uint8Array, value: Uint8Array, csvArrayHeader: Uint8Array[], utcDateHeader: Date, options?: WidgetsListWidgetsOptionalParams) => Promise; // (undocumented) listWidgetsPages: (page: number, pageSize: number, options?: WidgetsListWidgetsPagesOptionalParams) => PagedAsyncIterableIterator; // (undocumented) queryWidgetsPages: (page: number, pageSize: number, options?: WidgetsQueryWidgetsPagesOptionalParams) => PagedAsyncIterableIterator; - // (undocumented) updateWidget: (id: string, body: UpdateWidget, options?: WidgetsUpdateWidgetOptionalParams) => Promise; } -// @public (undocumented) +// @public export interface WidgetsQueryWidgetsPagesOptionalParams extends OperationOptions { } -// @public (undocumented) +// @public export interface WidgetsUpdateWidgetOptionalParams extends OperationOptions { } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts index a5bdc3a025..cb9ddda7eb 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts @@ -9,6 +9,10 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, + BudgetsCreateOrUpdate200Response, + BudgetsCreateOrUpdate201Response, + BudgetsCreateOrUpdateDefaultResponse, + BudgetsCreateOrUpdateLogicalResponse, isUnexpected, WidgetServiceContext as Client, } from "../../rest/index.js"; @@ -17,7 +21,10 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; -import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; +import { + BudgetsCreateOrReplaceOptionalParams, + BudgetsCreateOrUpdateOptionalParams, +} from "../../models/options.js"; export function _createOrReplaceSend( context: Client, @@ -72,3 +79,59 @@ export function createOrReplace( _createOrReplaceSend(context, name, resource, options), }) as PollerLike, User>; } + +export function _createOrUpdateSend( + context: Client, + name: string, + resource: User, + options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateDefaultResponse + | BudgetsCreateOrUpdateLogicalResponse +> { + return context + .path("/budgets/widgets/createOrUpdate/users/{name}", name) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/merge-patch+json", + queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, + body: { role: resource["role"], id: resource["id"] }, + }); +} + +export async function _createOrUpdateDeserialize( + result: + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateDefaultResponse + | BudgetsCreateOrUpdateLogicalResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + result = result as BudgetsCreateOrUpdateLogicalResponse; + return { + name: result.body["name"], + role: result.body["role"], + id: result.body["id"], + }; +} + +/** Long-running resource create or update operation template. */ +export function createOrUpdate( + context: Client, + name: string, + resource: User, + options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): PollerLike, User> { + return getLongRunningPoller(context, _createOrUpdateDeserialize, { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _createOrUpdateSend(context, name, resource, options), + }) as PollerLike, User>; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts index 0388bec217..b9aabf09c4 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts @@ -5,6 +5,7 @@ import { ClientOptions } from "@azure-rest/core-client"; import { WidgetServiceContext } from "../rest/index.js"; import getClient from "../rest/index.js"; +/** Optional parameters for the client. */ export interface WidgetServiceClientOptions extends ClientOptions {} export { WidgetServiceContext } from "../rest/index.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts index 5872a4ad97..b35575c24d 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts @@ -6,10 +6,10 @@ import { PollerLike, OperationState } from "@azure/core-lro"; import { User, Widget, - ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, + _ListWidgetsPagesResults, } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "../pagingHelpers.js"; @@ -165,7 +165,7 @@ export async function _listWidgetsPagesDeserialize( result: | WidgetsListWidgetsPages200Response | WidgetsListWidgetsPagesDefaultResponse, -): Promise { +): Promise<_ListWidgetsPagesResults> { if (isUnexpected(result)) { throw createRestError(result); } @@ -214,7 +214,7 @@ export async function _queryWidgetsPagesDeserialize( result: | WidgetsQueryWidgetsPages200Response | WidgetsQueryWidgetsPagesDefaultResponse, -): Promise { +): Promise<_ListWidgetsPagesResults> { if (isUnexpected(result)) { throw createRestError(result); } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts index 304428e7fb..d891c3b353 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts @@ -3,16 +3,27 @@ import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; import { User } from "../../models/models.js"; -import { createOrReplace } from "../../api/budgets/index.js"; +import { createOrReplace, createOrUpdate } from "../../api/budgets/index.js"; import { PollerLike, OperationState } from "@azure/core-lro"; -import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; +import { + BudgetsCreateOrReplaceOptionalParams, + BudgetsCreateOrUpdateOptionalParams, +} from "../../models/options.js"; +/** Interface representing a Budgets operations. */ export interface BudgetsOperations { + /** Long-running resource create or replace operation template. */ createOrReplace: ( name: string, resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => PollerLike, User>; + /** Long-running resource create or update operation template. */ + createOrUpdate: ( + name: string, + resource: User, + options?: BudgetsCreateOrUpdateOptionalParams, + ) => PollerLike, User>; } export function getBudgets(context: WidgetServiceContext) { @@ -22,6 +33,11 @@ export function getBudgets(context: WidgetServiceContext) { resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => createOrReplace(context, name, resource, options), + createOrUpdate: ( + name: string, + resource: User, + options?: BudgetsCreateOrUpdateOptionalParams, + ) => createOrUpdate(context, name, resource, options), }; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts index 9d408f19d6..8145486b93 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts @@ -34,7 +34,13 @@ import { WidgetsAnalyzeWidgetOptionalParams, } from "../../models/options.js"; +/** Interface representing a Widgets operations. */ export interface WidgetsOperations { + /** + * List all widgets in the system. This operation is not paginated, and returns a simple array of widgets. + * + * It does not accept any options or parameters. + */ listWidgets: ( requiredHeader: string, bytesHeader: Uint8Array, @@ -53,28 +59,42 @@ export interface WidgetsOperations { pageSize: number, options?: WidgetsQueryWidgetsPagesOptionalParams, ) => PagedAsyncIterableIterator; + /** Get a widget by ID. */ getWidget: ( id: string, options?: WidgetsGetWidgetOptionalParams, ) => Promise; + /** + * Create a new widget. + * + * The widget ID is not required during creation, as it is automatically set by the server. Providing an ID will + * result in an error. + */ createWidget: ( body: CreateWidget, options?: WidgetsCreateWidgetOptionalParams, ) => Promise; + /** Long-running resource create or replace operation template. */ createOrReplace: ( name: string, resource: User, options?: WidgetsCreateOrReplaceOptionalParams, ) => PollerLike, User>; + /** + * Update the contents of the widget. The widget ID is required in the input, but cannot be changed. All other fields + * are optional and will be updated within the widget if provided. + */ updateWidget: ( id: string, body: UpdateWidget, options?: WidgetsUpdateWidgetOptionalParams, ) => Promise; + /** Delete a widget by ID. */ deleteWidget: ( id: string, options?: WidgetsDeleteWidgetOptionalParams, ) => Promise; + /** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ analyzeWidget: ( id: string, options?: WidgetsAnalyzeWidgetOptionalParams, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/helpers/serializerHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts index d589c7727e..b749c17f1e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts @@ -10,7 +10,6 @@ export { User, Widget, WidgetError, - ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, @@ -26,6 +25,7 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, + BudgetsCreateOrUpdateOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index 9c53707361..9ba49f01b0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -5,7 +5,6 @@ export { User, Widget, WidgetError, - ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, @@ -23,6 +22,7 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, + BudgetsCreateOrUpdateOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts index 5722c21fab..b42c15b623 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts @@ -1,6 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { + User as UserRest, + CreateWidget as CreateWidgetRest, +} from "../rest/index.js"; + /** Details about a user. */ export interface User { /** The name of user. */ @@ -11,6 +16,13 @@ export interface User { id: string; } +export function userSerializer(item: User): UserRest { + return { + role: item["role"], + id: item["id"], + }; +} + export interface Widget { /** The UUID of this widget. This is generated automatically by the service. */ id: string; @@ -27,7 +39,7 @@ export interface WidgetError { message: string; } -export interface ListWidgetsPagesResults { +export interface _ListWidgetsPagesResults { /** The current page of results. */ results: Widget[]; /** The URL to get the next set of results. */ @@ -41,6 +53,13 @@ export interface CreateWidget { color: "red" | "blue"; } +export function createWidgetSerializer(item: CreateWidget): CreateWidgetRest { + return { + weight: item["weight"], + color: item["color"], + }; +} + export interface UpdateWidget { /** The weight of the widget. This is an int32, but must be greater than zero. */ weight?: number; @@ -48,6 +67,13 @@ export interface UpdateWidget { color?: "red" | "blue"; } +export function updateWidgetSerializer(item: UpdateWidget) { + return { + weight: item["weight"], + color: item["color"], + }; +} + export interface AnalyzeResult { summary: string; } @@ -59,6 +85,12 @@ export interface NonReferencedModel { prop2: string; } +export function nonReferencedModelSerializer(item: NonReferencedModel) { + return { + prop1: item["prop1"], + prop2: item["prop2"], + }; +} + /** The Contoso Widget Manager service version. */ -/** */ export type Versions = "1.0.0"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts index 76d2655dd1..2ba48a5b1e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts @@ -3,6 +3,7 @@ import { OperationOptions } from "@azure-rest/core-client"; +/** Optional parameters. */ export interface WidgetsListWidgetsOptionalParams extends OperationOptions { optionalHeader?: string; nullableOptionalHeader?: string | null; @@ -10,16 +11,21 @@ export interface WidgetsListWidgetsOptionalParams extends OperationOptions { nullableDateHeader?: Date | null; } +/** Optional parameters. */ export interface WidgetsListWidgetsPagesOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsQueryWidgetsPagesOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsGetWidgetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsCreateWidgetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsCreateOrReplaceOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; @@ -27,15 +33,29 @@ export interface WidgetsCreateOrReplaceOptionalParams extends OperationOptions { apiVersion?: string; } +/** Optional parameters. */ export interface WidgetsUpdateWidgetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsDeleteWidgetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface WidgetsAnalyzeWidgetOptionalParams extends OperationOptions {} +/** Optional parameters. */ export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** The API version to use for this operation. */ apiVersion?: string; } + +/** Optional parameters. */ +export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** The API version to use for this operation. */ + apiVersion?: string; + /** This request has a JSON Merge Patch body. */ + contentType?: string; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts index 246c23ed06..14643f2b13 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -12,6 +12,7 @@ import { WidgetsCreateOrReplaceParameters, WidgetsAnalyzeWidgetParameters, BudgetsCreateOrReplaceParameters, + BudgetsCreateOrUpdateParameters, } from "./parameters.js"; import { WidgetsListWidgets200Response, @@ -36,6 +37,9 @@ import { BudgetsCreateOrReplace200Response, BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, + BudgetsCreateOrUpdate200Response, + BudgetsCreateOrUpdate201Response, + BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; @@ -132,6 +136,17 @@ export interface BudgetsCreateOrReplace { >; } +export interface BudgetsCreateOrUpdate { + /** Long-running resource create or update operation template. */ + patch( + options: BudgetsCreateOrUpdateParameters, + ): StreamableMethod< + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateDefaultResponse + >; +} + export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): WidgetsListWidgets; @@ -151,6 +166,11 @@ export interface Routes { path: "/budgets/widgets/createOrReplace/users/{name}", name: string, ): BudgetsCreateOrReplace; + /** Resource for '/budgets/widgets/createOrUpdate/users/\{name\}' has methods for the following verbs: patch */ + ( + path: "/budgets/widgets/createOrUpdate/users/{name}", + name: string, + ): BudgetsCreateOrUpdate; } export type WidgetServiceContext = Client & { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts index 2ee6febfd6..f6205b939e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts @@ -26,6 +26,10 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceLogicalResponse, BudgetsCreateOrReplaceDefaultResponse, + BudgetsCreateOrUpdate200Response, + BudgetsCreateOrUpdate201Response, + BudgetsCreateOrUpdateLogicalResponse, + BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -41,6 +45,8 @@ const responseMap: Record = { "POST /widgets/{id}/analyze": ["200"], "GET /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], "PUT /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], + "GET /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], + "PATCH /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], }; export function isUnexpected( @@ -87,6 +93,13 @@ export function isUnexpected( | BudgetsCreateOrReplaceLogicalResponse | BudgetsCreateOrReplaceDefaultResponse, ): response is BudgetsCreateOrReplaceDefaultResponse; +export function isUnexpected( + response: + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateLogicalResponse + | BudgetsCreateOrUpdateDefaultResponse, +): response is BudgetsCreateOrUpdateDefaultResponse; export function isUnexpected( response: | WidgetsListWidgets200Response @@ -112,7 +125,11 @@ export function isUnexpected( | BudgetsCreateOrReplace200Response | BudgetsCreateOrReplace201Response | BudgetsCreateOrReplaceLogicalResponse - | BudgetsCreateOrReplaceDefaultResponse, + | BudgetsCreateOrReplaceDefaultResponse + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateLogicalResponse + | BudgetsCreateOrUpdateDefaultResponse, ): response is | WidgetsListWidgetsDefaultResponse | WidgetsCreateWidgetDefaultResponse @@ -123,7 +140,8 @@ export function isUnexpected( | WidgetsDeleteWidgetDefaultResponse | WidgetsCreateOrReplaceDefaultResponse | WidgetsAnalyzeWidgetDefaultResponse - | BudgetsCreateOrReplaceDefaultResponse { + | BudgetsCreateOrReplaceDefaultResponse + | BudgetsCreateOrUpdateDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts index 8c547f10c0..24abbd70ba 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts @@ -103,3 +103,29 @@ export type BudgetsCreateOrReplaceParameters = BudgetsCreateOrReplaceQueryParam & BudgetsCreateOrReplaceBodyParam & RequestParameters; +/** The resource instance. */ +export type UserResourceMergeAndPatch = Partial; + +export interface BudgetsCreateOrUpdateBodyParam { + /** The resource instance. */ + body: UserResourceMergeAndPatch; +} + +export interface BudgetsCreateOrUpdateQueryParamProperties { + /** The API version to use for this operation. */ + "api-version": string; +} + +export interface BudgetsCreateOrUpdateQueryParam { + queryParameters: BudgetsCreateOrUpdateQueryParamProperties; +} + +export interface BudgetsCreateOrUpdateMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type BudgetsCreateOrUpdateParameters = BudgetsCreateOrUpdateQueryParam & + BudgetsCreateOrUpdateMediaTypesParam & + BudgetsCreateOrUpdateBodyParam & + RequestParameters; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts index 3426531d4a..0884bc7b40 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts @@ -20,6 +20,10 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, + BudgetsCreateOrUpdate200Response, + BudgetsCreateOrUpdate201Response, + BudgetsCreateOrUpdateDefaultResponse, + BudgetsCreateOrUpdateLogicalResponse, } from "./responses.js"; /** @@ -100,6 +104,18 @@ export interface SimplePollerLike< * @param options - Options to set a resume state or custom polling interval. * @returns - A poller object to poll for operation state updates and eventually get the final response. */ +export async function getLongRunningPoller< + TResult extends + | BudgetsCreateOrUpdateLogicalResponse + | BudgetsCreateOrUpdateDefaultResponse, +>( + client: Client, + initialResponse: + | BudgetsCreateOrUpdate200Response + | BudgetsCreateOrUpdate201Response + | BudgetsCreateOrUpdateDefaultResponse, + options?: CreateHttpPollerOptions>, +): Promise, TResult>>; export async function getLongRunningPoller< TResult extends | WidgetsCreateOrReplaceLogicalResponse @@ -139,7 +155,7 @@ export async function getLongRunningPoller( }, sendPollRequest: async ( path: string, - options?: { abortSignal?: AbortSignalLike }, + pollOptions?: { abortSignal?: AbortSignalLike }, ) => { // This is the callback that is going to be called to poll the service // to get the latest status. We use the client provided and the polling path @@ -148,7 +164,7 @@ export async function getLongRunningPoller( function abortListener(): void { abortController.abort(); } - const inputAbortSignal = options?.abortSignal; + const inputAbortSignal = pollOptions?.abortSignal; const abortSignal = abortController.signal; if (inputAbortSignal?.aborted) { abortController.abort(); diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts index 4b63997112..c573254135 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts @@ -179,3 +179,44 @@ export interface BudgetsCreateOrReplaceLogicalResponse extends HttpResponse { status: "200"; body: UserOutput; } + +export interface BudgetsCreateOrUpdate200Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has succeeded. */ +export interface BudgetsCreateOrUpdate200Response extends HttpResponse { + status: "200"; + body: UserOutput; + headers: RawHttpHeaders & BudgetsCreateOrUpdate200Headers; +} + +export interface BudgetsCreateOrUpdate201Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface BudgetsCreateOrUpdate201Response extends HttpResponse { + status: "201"; + body: UserOutput; + headers: RawHttpHeaders & BudgetsCreateOrUpdate201Headers; +} + +export interface BudgetsCreateOrUpdateDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface BudgetsCreateOrUpdateDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & BudgetsCreateOrUpdateDefaultHeaders; +} + +/** The final response for long-running createOrUpdate operation */ +export interface BudgetsCreateOrUpdateLogicalResponse extends HttpResponse { + status: "200"; + body: UserOutput; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/widgetServiceClient.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/widgetServiceClient.ts index e037192643..1a44e090fe 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/widgetServiceClient.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/widgetServiceClient.ts @@ -5,6 +5,9 @@ import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "../logger.js"; import { WidgetServiceContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface WidgetServiceContextOptions extends ClientOptions {} + /** * Initialize a new instance of `WidgetServiceContext` * @param endpointParam - The parameter endpointParam @@ -12,10 +15,9 @@ import { WidgetServiceContext } from "./clientDefinitions.js"; */ export default function createClient( endpointParam: string, - options: ClientOptions = {}, + options: WidgetServiceContextOptions = {}, ): WidgetServiceContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; - const userAgentInfo = `azsdk-js-widget_dpg-rest/1.0.0-beta.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -30,7 +32,6 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, }; - const client = getClient(endpointUrl, options) as WidgetServiceContext; client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts index 2181a3515e..5716b3eb7f 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts @@ -7,11 +7,13 @@ import { deserializeState, ResourceLocationConfig, } from "@azure/core-lro"; -import { WidgetServiceContext } from "./api/widgetServiceContext.js"; import { WidgetServiceClient } from "./widgetServiceClient.js"; import { getLongRunningPoller } from "./api/pollingHelpers.js"; import { _createOrReplaceDeserialize } from "./api/widgets/index.js"; -import { _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets } from "./api/budgets/index.js"; +import { + _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets, + _createOrUpdateDeserialize, +} from "./api/budgets/index.js"; import { PathUncheckedResponse, OperationOptions, @@ -38,7 +40,7 @@ export interface RestorePollerOptions< * needs to be constructed after the original one is not in scope. */ export function restorePoller( - client: WidgetServiceContext | WidgetServiceClient, + client: WidgetServiceClient, serializedState: string, sourceOperation: ( ...args: any[] @@ -81,6 +83,8 @@ const deserializeMap: Record = { _createOrReplaceDeserialize, "PUT /budgets/widgets/createOrReplace/users/{name}": _createOrReplaceDeserializeBudgets, + "PATCH /budgets/widgets/createOrUpdate/users/{name}": + _createOrUpdateDeserialize, }; function getDeserializationHelper( diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.browser.config.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.browser.config.ts index 4965b26ce5..dc8e7cb68e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.browser.config.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.browser.config.ts @@ -32,5 +32,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage-browser", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.config.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.config.ts index 367c90fa4e..7928f980b0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.config.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/vitest.config.ts @@ -28,5 +28,6 @@ export default defineConfig({ reporter: ["text", "json", "html"], reportsDirectory: "coverage", }, + testTimeout: 1200000, }, }); diff --git a/packages/typespec-test/test/widget_dpg/spec/main.tsp b/packages/typespec-test/test/widget_dpg/spec/main.tsp index 7423dc7513..a75784a198 100644 --- a/packages/typespec-test/test/widget_dpg/spec/main.tsp +++ b/packages/typespec-test/test/widget_dpg/spec/main.tsp @@ -178,7 +178,6 @@ interface Budgets { op createOrReplace is ResourceOperations.LongRunningResourceCreateOrReplace; // the patch case for lro - // DPG patch LRO has issue but no real case met yet - // @route("/widgets/createOrUpdate") - // op createOrUpdate is ResourceOperations.LongRunningResourceCreateOrUpdate; + @route("/widgets/createOrUpdate") + op createOrUpdate is ResourceOperations.LongRunningResourceCreateOrUpdate; } From e1bdd37b574b02b331000ec02ce3e8c0882d65a9 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 3 Jul 2024 22:28:31 +0800 Subject: [PATCH 06/18] Update the loadtesting spec to the latest --- .../administrationOperationsClient.ts | 38 +- .../api/administrationOperationsContext.ts | 6 +- .../src/administrationOperations/api/index.ts | 2 +- .../api/operations.ts | 649 ++++++-- .../src/administrationOperations/index.ts | 22 +- .../administrationOperations/models/index.ts | 22 +- .../administrationOperations/models/models.ts | 638 ++++++-- .../models/options.ts | 18 +- .../generated/typespec-ts/src/index.ts | 207 ++- .../src/rest/azureLoadTestingClient.ts | 73 - .../typespec-ts/src/rest/clientDefinitions.ts | 243 ++- .../generated/typespec-ts/src/rest/index.ts | 7 +- .../typespec-ts/src/rest/isUnexpected.ts | 194 ++- .../src/rest/loadTestServiceClient.ts | 29 +- .../generated/typespec-ts/src/rest/models.ts | 287 ++-- .../typespec-ts/src/rest/outputModels.ts | 458 ++++-- .../typespec-ts/src/rest/parameters.ts | 174 +- .../typespec-ts/src/rest/pollingHelper.ts | 223 --- .../typespec-ts/src/rest/responses.ts | 312 +++- .../api/index.ts | 14 + .../api/operations.ts | 278 ++++ .../api/pagingHelpers.ts | 191 +++ ...tProfileAdministrationOperationsContext.ts | 25 + .../index.ts | 80 + .../models/index.ts | 80 + .../models/models.ts | 1244 ++++++++++++++ .../models/options.ts | 31 + .../models/pagingTypes.ts | 89 + ...stProfileAdministrationOperationsClient.ts | 80 + .../src/testProfileRunOperations/api/index.ts | 15 + .../api/operations.ts | 433 +++++ .../api/pagingHelpers.ts | 191 +++ .../api/testProfileRunOperationsContext.ts | 24 + .../src/testProfileRunOperations/index.ts | 81 + .../testProfileRunOperations/models/index.ts | 81 + .../testProfileRunOperations/models/models.ts | 1244 ++++++++++++++ .../models/options.ts | 44 + .../models/pagingTypes.ts | 89 + .../testProfileRunOperationsClient.ts | 92 ++ .../src/testRunOperations/api/index.ts | 6 +- .../src/testRunOperations/api/operations.ts | 1458 ++++++++++++----- .../testRunOperations/api/pollingHelpers.ts | 139 -- .../api/testRunOperationsContext.ts | 6 +- .../src/testRunOperations/index.ts | 27 +- .../src/testRunOperations/models/index.ts | 26 +- .../src/testRunOperations/models/models.ts | 638 ++++++-- .../src/testRunOperations/models/options.ts | 43 +- .../testRunOperations/restorePollerHelpers.ts | 156 -- .../testRunOperationsClient.ts | 83 +- .../test/loadtesting_modular/spec/client.tsp | 104 +- .../test/loadtesting_modular/spec/main.tsp | 30 +- .../spec/models.testprofile.tsp | 324 ++++ .../test/loadtesting_modular/spec/models.tsp | 1101 ++++++++----- .../test/loadtesting_modular/spec/routes.tsp | 673 ++++---- 54 files changed, 10021 insertions(+), 2801 deletions(-) delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/pagingHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/options.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/pagingTypes.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/pagingHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/pagingTypes.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index b83a0d4a29..aba71240a2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -5,7 +5,9 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, - FileInfo, + TestFileInfo, + FileType, + FileStatus, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -27,7 +29,7 @@ import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createAdministrationOperations, AdministrationOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, createOrUpdateTest, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, @@ -45,7 +47,7 @@ import { export { AdministrationOperationsClientOptions } from "./api/administrationOperationsContext.js"; export class AdministrationOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -62,7 +64,7 @@ export class AdministrationOperationsClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ createOrUpdateTest( testId: string, body: Test, @@ -71,7 +73,7 @@ export class AdministrationOperationsClient { return createOrUpdateTest(this._client, testId, body, options); } - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ createOrUpdateAppComponents( testId: string, body: TestAppComponents, @@ -112,7 +114,7 @@ export class AdministrationOperationsClient { return getServerMetricsConfig(this._client, testId, options); } - /** Get load test details by test name */ + /** Get load test details by test Id */ getTest( testId: string, options: GetTestOptionalParams = { requestOptions: {} }, @@ -120,12 +122,18 @@ export class AdministrationOperationsClient { return getTest(this._client, testId, options); } - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return getTestFile(this._client, testId, fileName, options); } @@ -133,7 +141,7 @@ export class AdministrationOperationsClient { listTestFiles( testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -148,7 +156,7 @@ export class AdministrationOperationsClient { } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -157,7 +165,13 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return uploadTestFile(this._client, testId, fileName, body, options); } @@ -170,7 +184,7 @@ export class AdministrationOperationsClient { return deleteTestFile(this._client, testId, fileName, options); } - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ deleteTest( testId: string, options: DeleteTestOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 41e5e742a6..54a0bdef28 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ @@ -12,13 +12,13 @@ export interface AdministrationOperationsClientOptions extends ClientOptions { apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createAdministrationOperations( endpointParam: string, credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts index f7564cbffd..342aa50e7a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts @@ -4,7 +4,7 @@ export { createAdministrationOperations, AdministrationOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./administrationOperationsContext.js"; export { createOrUpdateTest, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index 6c568e6bf2..8143e00653 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -3,23 +3,27 @@ import { passFailCriteriaSerializer, + autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, Test, - FileInfo, + CertificateType, + TestFileInfo, + FileType, + FileStatus, + TestKind, TestAppComponents, TestServerMetricConfig, - _PagedFileInfo, _PagedTest, + _PagedTestFileInfo, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestAdministrationCreateOrUpdateAppComponents200Response, LoadTestAdministrationCreateOrUpdateAppComponents201Response, LoadTestAdministrationCreateOrUpdateAppComponentsDefaultResponse, @@ -47,6 +51,7 @@ import { LoadTestAdministrationListTestsDefaultResponse, LoadTestAdministrationUploadTestFile201Response, LoadTestAdministrationUploadTestFileDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -89,6 +94,9 @@ export function _createOrUpdateTestSend( passFailCriteria: !body.passFailCriteria ? body.passFailCriteria : passFailCriteriaSerializer(body.passFailCriteria), + autoStopCriteria: !body.autoStopCriteria + ? body.autoStopCriteria + : autoStopCriteriaSerializer(body.autoStopCriteria), secrets: !body.secrets ? body.secrets : (serializeRecord(body.secrets as any, secretSerializer) as any), @@ -101,9 +109,12 @@ export function _createOrUpdateTestSend( loadTestConfiguration: !body.loadTestConfiguration ? body.loadTestConfiguration : loadTestConfigurationSerializer(body.loadTestConfiguration), + baselineTestRunId: body["baselineTestRunId"], description: body["description"], displayName: body["displayName"], subnetId: body["subnetId"], + kind: body["kind"], + publicIPDisabled: body["publicIPDisabled"], keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], }, @@ -124,12 +135,20 @@ export async function _createOrUpdateTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], + type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, environmentVariables: result.body["environmentVariables"], @@ -148,6 +167,14 @@ export async function _createOrUpdateTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -161,26 +188,43 @@ export async function _createOrUpdateTestDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + })), }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.configFileInfo?.["fileType"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], + fileType: result.body.inputArtifacts?.configFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -189,19 +233,24 @@ export async function _createOrUpdateTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], + fileType: result.body.inputArtifacts?.testScriptFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -210,19 +259,24 @@ export async function _createOrUpdateTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.userPropFileInfo?.["fileType"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], + fileType: result.body.inputArtifacts?.userPropFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.userPropFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -232,27 +286,60 @@ export async function _createOrUpdateTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - fileType: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], + fileType: result.body.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], - validationStatus: + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" + "validationFailureDetails" + ], + }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" ], }, @@ -260,11 +347,14 @@ export async function _createOrUpdateTestDeserialize( result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -272,16 +362,24 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"] as TestKind, + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create a new test or update an existing test. */ +/** Create a new test or update an existing test by providing the test Id. */ export async function createOrUpdateTest( context: Client, testId: string, @@ -330,14 +428,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test */ +/** Add an app component to a test by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testId: string, @@ -372,12 +476,10 @@ export function _createOrUpdateServerMetricsConfigSend( contentType: (options.contentType as any) ?? "application/merge-patch+json", body: { - metrics: !body.metrics - ? body.metrics - : (serializeRecord( - body.metrics as any, - resourceMetricSerializer, - ) as any), + metrics: serializeRecord( + body.metrics as any, + resourceMetricSerializer, + ) as any, }, }); } @@ -395,9 +497,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -445,9 +553,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -487,9 +601,15 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -530,12 +650,20 @@ export async function _getTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], + type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, environmentVariables: result.body["environmentVariables"], @@ -554,6 +682,14 @@ export async function _getTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -567,26 +703,43 @@ export async function _getTestDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + })), }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.configFileInfo?.["fileType"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], + fileType: result.body.inputArtifacts?.configFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -595,19 +748,24 @@ export async function _getTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], + fileType: result.body.inputArtifacts?.testScriptFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -616,19 +774,24 @@ export async function _getTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - fileType: - result.body.inputArtifacts?.userPropFileInfo?.["fileType"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], + fileType: result.body.inputArtifacts?.userPropFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], - validationStatus: - result.body.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.userPropFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: result.body.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -638,27 +801,60 @@ export async function _getTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - fileType: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], + fileType: result.body.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], - validationStatus: + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" + "validationFailureDetails" ], + }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" + ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: result.body.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" ], }, @@ -666,11 +862,14 @@ export async function _getTestDeserialize( result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -678,16 +877,24 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"] as TestKind, + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get load test details by test name */ +/** Get load test details by test Id */ export async function getTest( context: Client, testId: string, @@ -715,28 +922,42 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], - fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], - validationStatus: result.body["validationStatus"], + fileType: result.body["fileType"] as FileType, + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, + validationStatus: result.body["validationStatus"] as FileStatus, validationFailureDetails: result.body["validationFailureDetails"], }; } -/** Get test file by the file name. */ +/** Get all the files that are associated with a test. */ export async function getTestFile( context: Client, testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -758,18 +979,21 @@ export async function _listTestFilesDeserialize( result: | LoadTestAdministrationListTestFiles200Response | LoadTestAdministrationListTestFilesDefaultResponse, -): Promise<_PagedFileInfo> { +): Promise<_PagedTestFileInfo> { if (isUnexpected(result)) { throw createRestError(result); } return { value: result.body["value"].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), nextLink: result.body["nextLink"], @@ -781,7 +1005,7 @@ export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), @@ -804,8 +1028,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime, - lastModifiedEndTime: options?.lastModifiedEndTime, + lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), maxpagesize: options?.maxpagesize, }, }); @@ -825,12 +1049,20 @@ export async function _listTestsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined : { value: p.certificate?.["value"], - type: p.certificate?.["type"], + type: p.certificate?.["type"] as CertificateType, name: p.certificate?.["name"], }, environmentVariables: p["environmentVariables"], @@ -848,6 +1080,14 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -861,20 +1101,38 @@ export async function _listTestsDeserialize( "duration" ], }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + }), + ), }, + baselineTestRunId: p["baselineTestRunId"], inputArtifacts: !p.inputArtifacts ? undefined : { configFileInfo: !p.inputArtifacts?.configFileInfo ? undefined : { - url: p.inputArtifacts?.configFileInfo?.["url"], fileName: p.inputArtifacts?.configFileInfo?.["fileName"], - fileType: p.inputArtifacts?.configFileInfo?.["fileType"], + url: p.inputArtifacts?.configFileInfo?.["url"], + fileType: p.inputArtifacts?.configFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"], - validationStatus: - p.inputArtifacts?.configFileInfo?.["validationStatus"], + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -883,13 +1141,23 @@ export async function _listTestsDeserialize( testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo ? undefined : { - url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], - fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], + url: p.inputArtifacts?.testScriptFileInfo?.["url"], + fileType: p.inputArtifacts?.testScriptFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], - validationStatus: - p.inputArtifacts?.testScriptFileInfo?.["validationStatus"], + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -898,13 +1166,23 @@ export async function _listTestsDeserialize( userPropFileInfo: !p.inputArtifacts?.userPropFileInfo ? undefined : { - url: p.inputArtifacts?.userPropFileInfo?.["url"], fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], - fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], + url: p.inputArtifacts?.userPropFileInfo?.["url"], + fileType: p.inputArtifacts?.userPropFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], - validationStatus: - p.inputArtifacts?.userPropFileInfo?.["validationStatus"], + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -914,21 +1192,55 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], - fileType: - p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], + fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], - validationStatus: + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" + "validationFailureDetails" ], + }, + urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], + url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: p.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + p.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" ], }, @@ -936,11 +1248,14 @@ export async function _listTestsDeserialize( p.inputArtifacts?.["additionalFileInfo"] === undefined ? p.inputArtifacts?.["additionalFileInfo"] : p.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -948,11 +1263,19 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], + kind: p["kind"] as TestKind, + publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], @@ -999,23 +1322,31 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], - fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], - validationStatus: result.body["validationStatus"], + fileType: result.body["fileType"] as FileType, + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, + validationStatus: result.body["validationStatus"] as FileStatus, validationFailureDetails: result.body["validationFailureDetails"], }; } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -1025,7 +1356,13 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _uploadTestFileSend( context, testId, @@ -1098,7 +1435,7 @@ export async function _deleteTestDeserialize( return; } -/** Delete a test by its name. */ +/** Delete a test by its test Id. */ export async function deleteTest( context: Client, testId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index b0c78f4e9d..6cab3ad382 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -13,16 +13,19 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -33,12 +36,15 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -46,7 +52,6 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -54,6 +59,17 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index 8385d30729..e8845351c8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -9,16 +9,19 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -29,12 +32,15 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -42,7 +48,6 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -50,6 +55,17 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, } from "./models.js"; export { CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index 3a7491a214..31dd6af57e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -6,10 +6,12 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -19,12 +21,19 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -33,32 +42,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -68,6 +83,9 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -80,9 +98,12 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -113,7 +134,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -148,29 +169,55 @@ export function passFailMetricSerializer( }; } -/** Type of PFMetrics */ +/** Metrics for pass/fail criteria. */ export type PFMetrics = | "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; -/** Type of PFAgFunc */ +/** Aggregation functions for pass/fail criteria. */ export type PFAgFunc = | "count" | "percentage" | "avg" | "p50" + | "p75" | "p90" | "p95" + | "p96" + | "p97" + | "p98" | "p99" + | "p99.9" + | "p99.99" | "min" | "max"; -/** Type of PFAction */ +/** Action to take on failure of pass/fail criteria. */ export type PFAction = "continue" | "stop"; -/** Type of PFResult */ +/** Pass/fail criteria result. */ export type PFResult = "passed" | "undetermined" | "failed"; +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + /** Secret */ export interface Secret { /** The value of the secret for the respective type */ @@ -186,7 +233,7 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Type of SecretType */ +/** Types of secrets supported. */ export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ @@ -209,15 +256,12 @@ export function certificateMetadataSerializer( }; } -/** Type of CertificateType */ +/** Types of certificates supported. */ export type CertificateType = "AKV_CERT_URI"; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -231,8 +275,10 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -245,21 +291,26 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } @@ -268,53 +319,86 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Type of FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** Type of FileStatus */ +/** Types of file supported. */ +export type FileType = + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG" + | "TEST_SCRIPT"; +/** File status. */ export type FileStatus = | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +/** Test kind */ +export type TestKind = "URL" | "JMX" | "Locust"; -/** Test app component */ +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -324,12 +408,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -345,20 +429,14 @@ export function testAppComponentsSerializer( }; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -387,13 +465,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -402,9 +480,10 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, }; } @@ -446,31 +525,21 @@ export function resourceMetricSerializer( }; } -/** Collection of files. */ -export interface _PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Type of APIVersions */ -export type APIVersions = "2022-11-01"; +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -485,8 +554,18 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -503,24 +582,32 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -530,6 +617,9 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -545,6 +635,8 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -578,6 +670,18 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -597,28 +701,58 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; } -/** Type of PFTestResult */ +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Type of Status */ +/** Test run status. */ export type Status = | "ACCEPTED" | "NOTSTARTED" @@ -636,6 +770,8 @@ export type Status = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +/** Request data collection level for test run */ +export type RequestDataLevel = "NONE" | "ERRORS"; /** Test run app component */ export interface TestRunAppComponents { @@ -647,12 +783,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -678,12 +814,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -698,11 +834,17 @@ export function testRunServerMetricConfigSerializer( }; } -/** Type of Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Time Grain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -742,16 +884,22 @@ export interface NameAndDesc { name?: string; } -/** Type of AggregationType */ +/** Aggregation type. */ export type AggregationType = | "Average" | "Count" | "None" | "Total" + | "Percentile75" | "Percentile90" | "Percentile95" - | "Percentile99"; -/** Type of MetricUnit */ + | "Percentile96" + | "Percentile97" + | "Percentile98" + | "Percentile99" + | "Percentile999" + | "Percentile9999"; +/** Metric unit. */ export type MetricUnit = | "NotSpecified" | "Percent" @@ -771,9 +919,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** Type of TimeGrain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -788,7 +933,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -828,7 +973,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _PagedTimeSeriesElement { +export interface _Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -845,8 +990,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -859,7 +1004,217 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Kind of the resource on which test profile is created. */ +export type ResourceKind = "FunctionsFlexConsumption"; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Test profile run status. */ +export type TestProfileRunStatus = + | "ACCEPTED" + | "NOTSTARTED" + | "EXECUTING" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED"; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Category of Recommendation. */ +export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -867,10 +1222,23 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface _PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; /** The link to the next page of items */ nextLink?: string; } + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts index f6d6da0948..4a2f18723c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts @@ -6,18 +6,21 @@ import { FileType } from "./models.js"; /** Optional parameters. */ export interface CreateOrUpdateTestOptionalParams extends OperationOptions { + /** This request has a JSON Merge Patch body. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -50,22 +53,17 @@ export interface ListTestsOptionalParams extends OperationOptions { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date; /** Number of results in response. */ maxpagesize?: number; } /** Optional parameters. */ export interface UploadTestFileOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; /** File type */ fileType?: FileType; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index d06253bb01..9bfd8e72fc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -13,16 +13,19 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -33,12 +36,15 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -46,7 +52,6 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -54,6 +59,17 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -74,10 +90,6 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperations/testRunOperationsClient.js"; -export { - restorePoller, - RestorePollerOptions, -} from "./testRunOperations/restorePollerHelpers.js"; export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, @@ -86,16 +98,19 @@ export { PFAgFunc as TestRunOperationsClientPFAgFunc, PFAction as TestRunOperationsClientPFAction, PFResult as TestRunOperationsClientPFResult, + AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, CertificateType as TestRunOperationsClientCertificateType, LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestRunOperationsClientRegionalConfiguration, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, - FileInfo as TestRunOperationsClientFileInfo, + TestFileInfo as TestRunOperationsClientTestFileInfo, FileType as TestRunOperationsClientFileType, FileStatus as TestRunOperationsClientFileStatus, + TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, TestServerMetricConfig as TestRunOperationsClientTestServerMetricConfig, @@ -106,12 +121,15 @@ export { TestRunStatistics as TestRunOperationsClientTestRunStatistics, TestRunArtifacts as TestRunOperationsClientTestRunArtifacts, TestRunInputArtifacts as TestRunOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, PFTestResult as TestRunOperationsClientPFTestResult, Status as TestRunOperationsClientStatus, + RequestDataLevel as TestRunOperationsClientRequestDataLevel, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, - Interval as TestRunOperationsClientInterval, + TimeGrain as TestRunOperationsClientTimeGrain, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, @@ -119,7 +137,6 @@ export { AggregationType as TestRunOperationsClientAggregationType, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, - TimeGrain as TestRunOperationsClientTimeGrain, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, MetricNamespace as TestRunOperationsClientMetricNamespace, MetricRequestPayload as TestRunOperationsClientMetricRequestPayload, @@ -127,7 +144,18 @@ export { TimeSeriesElement as TestRunOperationsClientTimeSeriesElement, MetricValue as TestRunOperationsClientMetricValue, DimensionValue as TestRunOperationsClientDimensionValue, - TestRunOptionalParams, + TestProfile as TestRunOperationsClientTestProfile, + TargetResourceConfigurations as TestRunOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + ResourceKind as TestRunOperationsClientResourceKind, + TestProfileRun as TestRunOperationsClientTestProfileRun, + TestProfileRunStatus as TestRunOperationsClientTestProfileRunStatus, + TestRunDetail as TestRunOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestRunOperationsClientTestProfileRunRecommendation, + RecommendationCategory as TestRunOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestRunOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -140,8 +168,163 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings as TestRunOperationsClientPageSettings, ContinuablePage as TestRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestRunOperationsClientPagedAsyncIterableIterator, } from "./testRunOperations/models/index.js"; +export { + TestProfileAdministrationOperationsClient, + TestProfileAdministrationOperationsClientOptions, +} from "./testProfileAdministrationOperations/testProfileAdministrationOperationsClient.js"; +export { + Test as TestProfileAdministrationOperationsClientTest, + PassFailCriteria as TestProfileAdministrationOperationsClientPassFailCriteria, + PassFailMetric as TestProfileAdministrationOperationsClientPassFailMetric, + PFMetrics as TestProfileAdministrationOperationsClientPFMetrics, + PFAgFunc as TestProfileAdministrationOperationsClientPFAgFunc, + PFAction as TestProfileAdministrationOperationsClientPFAction, + PFResult as TestProfileAdministrationOperationsClientPFResult, + AutoStopCriteria as TestProfileAdministrationOperationsClientAutoStopCriteria, + Secret as TestProfileAdministrationOperationsClientSecret, + SecretType as TestProfileAdministrationOperationsClientSecretType, + CertificateMetadata as TestProfileAdministrationOperationsClientCertificateMetadata, + CertificateType as TestProfileAdministrationOperationsClientCertificateType, + LoadTestConfiguration as TestProfileAdministrationOperationsClientLoadTestConfiguration, + OptionalLoadTestConfig as TestProfileAdministrationOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestProfileAdministrationOperationsClientRegionalConfiguration, + TestInputArtifacts as TestProfileAdministrationOperationsClientTestInputArtifacts, + TestFileInfo as TestProfileAdministrationOperationsClientTestFileInfo, + FileType as TestProfileAdministrationOperationsClientFileType, + FileStatus as TestProfileAdministrationOperationsClientFileStatus, + TestKind as TestProfileAdministrationOperationsClientTestKind, + TestAppComponents as TestProfileAdministrationOperationsClientTestAppComponents, + AppComponent as TestProfileAdministrationOperationsClientAppComponent, + TestServerMetricConfig as TestProfileAdministrationOperationsClientTestServerMetricConfig, + ResourceMetric as TestProfileAdministrationOperationsClientResourceMetric, + APIVersions as TestProfileAdministrationOperationsClientAPIVersions, + TestRun as TestProfileAdministrationOperationsClientTestRun, + ErrorDetails as TestProfileAdministrationOperationsClientErrorDetails, + TestRunStatistics as TestProfileAdministrationOperationsClientTestRunStatistics, + TestRunArtifacts as TestProfileAdministrationOperationsClientTestRunArtifacts, + TestRunInputArtifacts as TestProfileAdministrationOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestProfileAdministrationOperationsClientTestRunFileInfo, + TestRunOutputArtifacts as TestProfileAdministrationOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestProfileAdministrationOperationsClientArtifactsContainerInfo, + PFTestResult as TestProfileAdministrationOperationsClientPFTestResult, + Status as TestProfileAdministrationOperationsClientStatus, + RequestDataLevel as TestProfileAdministrationOperationsClientRequestDataLevel, + TestRunAppComponents as TestProfileAdministrationOperationsClientTestRunAppComponents, + TestRunServerMetricConfig as TestProfileAdministrationOperationsClientTestRunServerMetricConfig, + TimeGrain as TestProfileAdministrationOperationsClientTimeGrain, + DimensionValueList as TestProfileAdministrationOperationsClientDimensionValueList, + MetricDefinitionCollection as TestProfileAdministrationOperationsClientMetricDefinitionCollection, + MetricDefinition as TestProfileAdministrationOperationsClientMetricDefinition, + NameAndDesc as TestProfileAdministrationOperationsClientNameAndDesc, + AggregationType as TestProfileAdministrationOperationsClientAggregationType, + MetricUnit as TestProfileAdministrationOperationsClientMetricUnit, + MetricAvailability as TestProfileAdministrationOperationsClientMetricAvailability, + MetricNamespaceCollection as TestProfileAdministrationOperationsClientMetricNamespaceCollection, + MetricNamespace as TestProfileAdministrationOperationsClientMetricNamespace, + MetricRequestPayload as TestProfileAdministrationOperationsClientMetricRequestPayload, + DimensionFilter as TestProfileAdministrationOperationsClientDimensionFilter, + TimeSeriesElement as TestProfileAdministrationOperationsClientTimeSeriesElement, + MetricValue as TestProfileAdministrationOperationsClientMetricValue, + DimensionValue as TestProfileAdministrationOperationsClientDimensionValue, + TestProfile as TestProfileAdministrationOperationsClientTestProfile, + TargetResourceConfigurations as TestProfileAdministrationOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration, + ResourceKind as TestProfileAdministrationOperationsClientResourceKind, + TestProfileRun as TestProfileAdministrationOperationsClientTestProfileRun, + TestProfileRunStatus as TestProfileAdministrationOperationsClientTestProfileRunStatus, + TestRunDetail as TestProfileAdministrationOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestProfileAdministrationOperationsClientTestProfileRunRecommendation, + RecommendationCategory as TestProfileAdministrationOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, + PageSettings as TestProfileAdministrationOperationsClientPageSettings, + ContinuablePage as TestProfileAdministrationOperationsClientContinuablePage, + PagedAsyncIterableIterator as TestProfileAdministrationOperationsClientPagedAsyncIterableIterator, +} from "./testProfileAdministrationOperations/models/index.js"; +export { + TestProfileRunOperationsClient, + TestProfileRunOperationsClientOptions, +} from "./testProfileRunOperations/testProfileRunOperationsClient.js"; +export { + Test as TestProfileRunOperationsClientTest, + PassFailCriteria as TestProfileRunOperationsClientPassFailCriteria, + PassFailMetric as TestProfileRunOperationsClientPassFailMetric, + PFMetrics as TestProfileRunOperationsClientPFMetrics, + PFAgFunc as TestProfileRunOperationsClientPFAgFunc, + PFAction as TestProfileRunOperationsClientPFAction, + PFResult as TestProfileRunOperationsClientPFResult, + AutoStopCriteria as TestProfileRunOperationsClientAutoStopCriteria, + Secret as TestProfileRunOperationsClientSecret, + SecretType as TestProfileRunOperationsClientSecretType, + CertificateMetadata as TestProfileRunOperationsClientCertificateMetadata, + CertificateType as TestProfileRunOperationsClientCertificateType, + LoadTestConfiguration as TestProfileRunOperationsClientLoadTestConfiguration, + OptionalLoadTestConfig as TestProfileRunOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestProfileRunOperationsClientRegionalConfiguration, + TestInputArtifacts as TestProfileRunOperationsClientTestInputArtifacts, + TestFileInfo as TestProfileRunOperationsClientTestFileInfo, + FileType as TestProfileRunOperationsClientFileType, + FileStatus as TestProfileRunOperationsClientFileStatus, + TestKind as TestProfileRunOperationsClientTestKind, + TestAppComponents as TestProfileRunOperationsClientTestAppComponents, + AppComponent as TestProfileRunOperationsClientAppComponent, + TestServerMetricConfig as TestProfileRunOperationsClientTestServerMetricConfig, + ResourceMetric as TestProfileRunOperationsClientResourceMetric, + APIVersions as TestProfileRunOperationsClientAPIVersions, + TestRun as TestProfileRunOperationsClientTestRun, + ErrorDetails as TestProfileRunOperationsClientErrorDetails, + TestRunStatistics as TestProfileRunOperationsClientTestRunStatistics, + TestRunArtifacts as TestProfileRunOperationsClientTestRunArtifacts, + TestRunInputArtifacts as TestProfileRunOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestProfileRunOperationsClientTestRunFileInfo, + TestRunOutputArtifacts as TestProfileRunOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestProfileRunOperationsClientArtifactsContainerInfo, + PFTestResult as TestProfileRunOperationsClientPFTestResult, + Status as TestProfileRunOperationsClientStatus, + RequestDataLevel as TestProfileRunOperationsClientRequestDataLevel, + TestRunAppComponents as TestProfileRunOperationsClientTestRunAppComponents, + TestRunServerMetricConfig as TestProfileRunOperationsClientTestRunServerMetricConfig, + TimeGrain as TestProfileRunOperationsClientTimeGrain, + DimensionValueList as TestProfileRunOperationsClientDimensionValueList, + MetricDefinitionCollection as TestProfileRunOperationsClientMetricDefinitionCollection, + MetricDefinition as TestProfileRunOperationsClientMetricDefinition, + NameAndDesc as TestProfileRunOperationsClientNameAndDesc, + AggregationType as TestProfileRunOperationsClientAggregationType, + MetricUnit as TestProfileRunOperationsClientMetricUnit, + MetricAvailability as TestProfileRunOperationsClientMetricAvailability, + MetricNamespaceCollection as TestProfileRunOperationsClientMetricNamespaceCollection, + MetricNamespace as TestProfileRunOperationsClientMetricNamespace, + MetricRequestPayload as TestProfileRunOperationsClientMetricRequestPayload, + DimensionFilter as TestProfileRunOperationsClientDimensionFilter, + TimeSeriesElement as TestProfileRunOperationsClientTimeSeriesElement, + MetricValue as TestProfileRunOperationsClientMetricValue, + DimensionValue as TestProfileRunOperationsClientDimensionValue, + TestProfile as TestProfileRunOperationsClientTestProfile, + TargetResourceConfigurations as TestProfileRunOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + ResourceKind as TestProfileRunOperationsClientResourceKind, + TestProfileRun as TestProfileRunOperationsClientTestProfileRun, + TestProfileRunStatus as TestProfileRunOperationsClientTestProfileRunStatus, + TestRunDetail as TestProfileRunOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestProfileRunOperationsClientTestProfileRunRecommendation, + RecommendationCategory as TestProfileRunOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestProfileRunOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams as TestProfileRunOperationsClientStopOptionalParams, + PageSettings as TestProfileRunOperationsClientPageSettings, + ContinuablePage as TestProfileRunOperationsClientContinuablePage, + PagedAsyncIterableIterator as TestProfileRunOperationsClientPagedAsyncIterableIterator, +} from "./testProfileRunOperations/models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts deleted file mode 100644 index 01f53c8bc8..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { getClient, ClientOptions } from "@azure-rest/core-client"; -import { logger } from "../logger.js"; -import { TokenCredential } from "@azure/core-auth"; -import { AzureLoadTestingContext } from "./clientDefinitions.js"; - -/** The optional parameters for the client */ -export interface AzureLoadTestingContextOptions extends ClientOptions { - /** The api version option of the client */ - apiVersion?: string; -} - -/** - * Initialize a new instance of `AzureLoadTestingContext` - * @param endpointParam - A sequence of textual characters. - * @param credentials - uniquely identify client credential - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpointParam: string, - credentials: TokenCredential, - { - apiVersion = "2022-11-01", - ...options - }: AzureLoadTestingContextOptions = {}, -): AzureLoadTestingContext { - const endpointUrl = - options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` - : `${userAgentInfo}`; - options = { - ...options, - userAgentOptions: { - userAgentPrefix, - }, - loggingOptions: { - logger: options.loggingOptions?.logger ?? logger.info, - }, - credentials: { - scopes: options.credentials?.scopes ?? [ - "https://cnt-prod.loadtesting.azure.com/.default", - ], - }, - }; - const client = getClient( - endpointUrl, - credentials, - options, - ) as AzureLoadTestingContext; - - client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - client.pipeline.addPolicy({ - name: "ClientApiVersionPolicy", - sendRequest: (req, next) => { - // Use the apiVersion defined in request url directly - // Append one if there is no apiVersion and we have one at client options - const url = new URL(req.url); - if (!url.searchParams.get("api-version") && apiVersion) { - req.url = `${req.url}${ - Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" - }api-version=${apiVersion}`; - } - - return next(req); - }, - }); - return client; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts index 2d1d85129a..fa2d60737c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -14,12 +14,12 @@ import { LoadTestAdministrationGetAppComponentsParameters, LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters, LoadTestAdministrationGetServerMetricsConfigParameters, - LoadTestRunDeleteTestRunParameters, - LoadTestRunCreateOrUpdateTestRunParameters, LoadTestRunGetTestRunParameters, - LoadTestRunGetTestRunFileParameters, + LoadTestRunCreateOrUpdateTestRunParameters, + LoadTestRunDeleteTestRunParameters, LoadTestRunListTestRunsParameters, - LoadTestRunStopTestRunParameters, + LoadTestRunGetTestRunFileParameters, + LoadTestRunStopParameters, LoadTestRunListMetricNamespacesParameters, LoadTestRunListMetricDefinitionsParameters, LoadTestRunListMetricsParameters, @@ -27,7 +27,16 @@ import { LoadTestRunCreateOrUpdateAppComponentsParameters, LoadTestRunGetAppComponentsParameters, LoadTestRunCreateOrUpdateServerMetricsConfigParameters, - LoadTestRunTestRunListServerMetricsConfigParameters, + LoadTestRunGetServerMetricsConfigParameters, + TestProfileAdministrationCreateOrUpdateTestProfileParameters, + TestProfileAdministrationDeleteTestProfileParameters, + TestProfileAdministrationGetTestProfileParameters, + TestProfileAdministrationListTestProfilesParameters, + TestProfileRunAdministrationGetTestProfileRunParameters, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, + TestProfileRunAdministrationDeleteTestProfileRunParameters, + TestProfileRunAdministrationStopParameters, + TestProfileRunAdministrationListTestProfileRunsParameters, } from "./parameters.js"; import { LoadTestAdministrationCreateOrUpdateTest200Response, @@ -57,19 +66,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -86,13 +95,33 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, + TestProfileAdministrationCreateOrUpdateTestProfile200Response, + TestProfileAdministrationCreateOrUpdateTestProfile201Response, + TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, + TestProfileAdministrationDeleteTestProfile204Response, + TestProfileAdministrationDeleteTestProfileDefaultResponse, + TestProfileAdministrationGetTestProfile200Response, + TestProfileAdministrationGetTestProfileDefaultResponse, + TestProfileAdministrationListTestProfiles200Response, + TestProfileAdministrationListTestProfilesDefaultResponse, + TestProfileRunAdministrationGetTestProfileRun200Response, + TestProfileRunAdministrationGetTestProfileRunDefaultResponse, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, + TestProfileRunAdministrationDeleteTestProfileRun204Response, + TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, + TestProfileRunAdministrationStop200Response, + TestProfileRunAdministrationStopDefaultResponse, + TestProfileRunAdministrationListTestProfileRuns200Response, + TestProfileRunAdministrationListTestProfileRunsDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; export interface LoadTestAdministrationCreateOrUpdateTest { - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ patch( options: LoadTestAdministrationCreateOrUpdateTestParameters, ): StreamableMethod< @@ -100,14 +129,14 @@ export interface LoadTestAdministrationCreateOrUpdateTest { | LoadTestAdministrationCreateOrUpdateTest201Response | LoadTestAdministrationCreateOrUpdateTestDefaultResponse >; - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ delete( options?: LoadTestAdministrationDeleteTestParameters, ): StreamableMethod< | LoadTestAdministrationDeleteTest204Response | LoadTestAdministrationDeleteTestDefaultResponse >; - /** Get load test details by test name */ + /** Get load test details by test Id */ get( options?: LoadTestAdministrationGetTestParameters, ): StreamableMethod< @@ -131,7 +160,7 @@ export interface LoadTestAdministrationListTests { export interface LoadTestAdministrationUploadTestFile { /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -141,7 +170,7 @@ export interface LoadTestAdministrationUploadTestFile { | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse >; - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ get( options?: LoadTestAdministrationGetTestFileParameters, ): StreamableMethod< @@ -168,7 +197,7 @@ export interface LoadTestAdministrationListTestFiles { } export interface LoadTestAdministrationCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ patch( options: LoadTestAdministrationCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -203,15 +232,14 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfig { >; } -export interface LoadTestRunDeleteTestRun { - /** Delete a test run by its name. */ - delete( - options?: LoadTestRunDeleteTestRunParameters, +export interface LoadTestRunGetTestRun { + /** Get test run details by test run Id. */ + get( + options?: LoadTestRunGetTestRunParameters, ): StreamableMethod< - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse >; - /** Create and start a new test run with the given name. */ + /** Create and start a new test run with the given test run Id. */ patch( options: LoadTestRunCreateOrUpdateTestRunParameters, ): StreamableMethod< @@ -219,11 +247,21 @@ export interface LoadTestRunDeleteTestRun { | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse >; - /** Get test run details by name. */ + /** Delete an existing load test run by providing the testRunId. */ + delete( + options?: LoadTestRunDeleteTestRunParameters, + ): StreamableMethod< + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse + >; +} + +export interface LoadTestRunListTestRuns { + /** Get all test runs for the given filters. */ get( - options?: LoadTestRunGetTestRunParameters, + options?: LoadTestRunListTestRunsParameters, ): StreamableMethod< - LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse + LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse >; } @@ -237,21 +275,12 @@ export interface LoadTestRunGetTestRunFile { >; } -export interface LoadTestRunListTestRuns { - /** Get all test runs with given filters */ - get( - options?: LoadTestRunListTestRunsParameters, - ): StreamableMethod< - LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - >; -} - -export interface LoadTestRunStopTestRun { - /** Stop test run by name. */ +export interface LoadTestRunStop { + /** Stop test run by test run Id. */ post( - options?: LoadTestRunStopTestRunParameters, + options?: LoadTestRunStopParameters, ): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse + LoadTestRunStop200Response | LoadTestRunStopDefaultResponse >; } @@ -268,7 +297,7 @@ export interface LoadTestRunListMetricNamespaces { export interface LoadTestRunListMetricDefinitions { /** List the metric definitions for a load test run. */ get( - options?: LoadTestRunListMetricDefinitionsParameters, + options: LoadTestRunListMetricDefinitionsParameters, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response | LoadTestRunListMetricDefinitionsDefaultResponse @@ -295,7 +324,7 @@ export interface LoadTestRunListMetricDimensionValues { } export interface LoadTestRunCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ patch( options: LoadTestRunCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -324,12 +353,92 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfig { | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse >; - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ get( - options?: LoadTestRunTestRunListServerMetricsConfigParameters, + options?: LoadTestRunGetServerMetricsConfigParameters, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse + >; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfile { + /** Create a new test profile or update an existing test profile by providing the test profile Id. */ + patch( + options: TestProfileAdministrationCreateOrUpdateTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + >; + /** Delete a test profile by its test profile Id. */ + delete( + options?: TestProfileAdministrationDeleteTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse + >; + /** Get load test profile details by test profile Id. */ + get( + options?: TestProfileAdministrationGetTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse + >; +} + +export interface TestProfileAdministrationListTestProfiles { + /** Get all test profiles for the given filters. */ + get( + options?: TestProfileAdministrationListTestProfilesParameters, + ): StreamableMethod< + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse + >; +} + +export interface TestProfileRunAdministrationGetTestProfileRun { + /** Get test profile run details by test profile run Id. */ + get( + options?: TestProfileRunAdministrationGetTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + >; + /** Create and start a new test profile run with the given test profile run Id. */ + patch( + options: TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + >; + /** Delete an existing load test profile run by providing the test profile run Id. */ + delete( + options?: TestProfileRunAdministrationDeleteTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + >; +} + +export interface TestProfileRunAdministrationStop { + /** Stop test profile run for the given test profile run Id. */ + post( + options?: TestProfileRunAdministrationStopParameters, + ): StreamableMethod< + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse + >; +} + +export interface TestProfileRunAdministrationListTestProfileRuns { + /** Get all test profile runs for the given filters. */ + get( + options?: TestProfileRunAdministrationListTestProfileRunsParameters, + ): StreamableMethod< + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse >; } @@ -362,21 +471,18 @@ export interface Routes { path: "/tests/{testId}/server-metrics-config", testId: string, ): LoadTestAdministrationCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: delete, patch, get */ - (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunDeleteTestRun; + /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: get, patch, delete */ + (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunGetTestRun; + /** Resource for '/test-runs' has methods for the following verbs: get */ + (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}/files/\{fileName\}' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/files/{fileName}", testRunId: string, fileName: string, ): LoadTestRunGetTestRunFile; - /** Resource for '/test-runs' has methods for the following verbs: get */ - (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}:stop' has methods for the following verbs: post */ - ( - path: "/test-runs/{testRunId}:stop", - testRunId: string, - ): LoadTestRunStopTestRun; + (path: "/test-runs/{testRunId}:stop", testRunId: string): LoadTestRunStop; /** Resource for '/test-runs/\{testRunId\}/metric-namespaces' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/metric-namespaces", @@ -408,8 +514,27 @@ export interface Routes { path: "/test-runs/{testRunId}/server-metrics-config", testRunId: string, ): LoadTestRunCreateOrUpdateServerMetricsConfig; + /** Resource for '/test-profiles/\{testProfileId\}' has methods for the following verbs: patch, delete, get */ + ( + path: "/test-profiles/{testProfileId}", + testProfileId: string, + ): TestProfileAdministrationCreateOrUpdateTestProfile; + /** Resource for '/test-profiles' has methods for the following verbs: get */ + (path: "/test-profiles"): TestProfileAdministrationListTestProfiles; + /** Resource for '/test-profile-runs/\{testProfileRunId\}' has methods for the following verbs: get, patch, delete */ + ( + path: "/test-profile-runs/{testProfileRunId}", + testProfileRunId: string, + ): TestProfileRunAdministrationGetTestProfileRun; + /** Resource for '/test-profile-runs/\{testProfileRunId\}:stop' has methods for the following verbs: post */ + ( + path: "/test-profile-runs/{testProfileRunId}:stop", + testProfileRunId: string, + ): TestProfileRunAdministrationStop; + /** Resource for '/test-profile-runs' has methods for the following verbs: get */ + (path: "/test-profile-runs"): TestProfileRunAdministrationListTestProfileRuns; } -export type AzureLoadTestingContext = Client & { +export type LoadTestServiceContext = Client & { path: Routes; }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts index a22d574c4f..b57cb81db2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import AzureLoadTestingClient from "./azureLoadTestingClient.js"; +import LoadTestServiceClient from "./loadTestServiceClient.js"; -export * from "./azureLoadTestingClient.js"; +export * from "./loadTestServiceClient.js"; export * from "./parameters.js"; export * from "./responses.js"; export * from "./clientDefinitions.js"; @@ -11,6 +11,5 @@ export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; export * from "./paginateHelper.js"; -export * from "./pollingHelper.js"; -export default AzureLoadTestingClient; +export default LoadTestServiceClient; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts index e02ac644d2..fdb24b329f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts @@ -29,20 +29,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -59,8 +58,28 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, + TestProfileAdministrationCreateOrUpdateTestProfile200Response, + TestProfileAdministrationCreateOrUpdateTestProfile201Response, + TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, + TestProfileAdministrationDeleteTestProfile204Response, + TestProfileAdministrationDeleteTestProfileDefaultResponse, + TestProfileAdministrationGetTestProfile200Response, + TestProfileAdministrationGetTestProfileDefaultResponse, + TestProfileAdministrationListTestProfiles200Response, + TestProfileAdministrationListTestProfilesDefaultResponse, + TestProfileRunAdministrationGetTestProfileRun200Response, + TestProfileRunAdministrationGetTestProfileRunDefaultResponse, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, + TestProfileRunAdministrationDeleteTestProfileRun204Response, + TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, + TestProfileRunAdministrationStop200Response, + TestProfileRunAdministrationStopDefaultResponse, + TestProfileRunAdministrationListTestProfileRuns200Response, + TestProfileRunAdministrationListTestProfileRunsDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -76,11 +95,11 @@ const responseMap: Record = { "GET /tests/{testId}/app-components": ["200"], "PATCH /tests/{testId}/server-metrics-config": ["200", "201"], "GET /tests/{testId}/server-metrics-config": ["200"], - "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs/{testRunId}": ["200"], "PATCH /test-runs/{testRunId}": ["200", "201"], - "GET /test-runs/{testRunId}/files/{fileName}": ["200"], + "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs": ["200"], + "GET /test-runs/{testRunId}/files/{fileName}": ["200"], "POST /test-runs/{testRunId}:stop": ["200"], "GET /test-runs/{testRunId}/metric-namespaces": ["200"], "GET /test-runs/{testRunId}/metric-definitions": ["200"], @@ -90,6 +109,15 @@ const responseMap: Record = { "GET /test-runs/{testRunId}/app-components": ["200"], "PATCH /test-runs/{testRunId}/server-metrics-config": ["200", "201"], "GET /test-runs/{testRunId}/server-metrics-config": ["200"], + "PATCH /test-profiles/{testProfileId}": ["200", "201"], + "DELETE /test-profiles/{testProfileId}": ["204"], + "GET /test-profiles/{testProfileId}": ["200"], + "GET /test-profiles": ["200"], + "GET /test-profile-runs/{testProfileRunId}": ["200"], + "PATCH /test-profile-runs/{testProfileRunId}": ["200", "201"], + "DELETE /test-profile-runs/{testProfileRunId}": ["204"], + "POST /test-profile-runs/{testProfileRunId}:stop": ["200"], + "GET /test-profile-runs": ["200"], }; export function isUnexpected( @@ -157,26 +185,20 @@ export function isUnexpected( ): response is LoadTestAdministrationGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse, -): response is LoadTestRunDeleteTestRunDefaultResponse; + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse, +): response is LoadTestRunGetTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): response is LoadTestRunCreateOrUpdateTestRunDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse, -): response is LoadTestRunGetTestRunDefaultResponse; -export function isUnexpected( - response: - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse, -): response is LoadTestRunGetTestRunFileDefaultResponse; + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse, +): response is LoadTestRunDeleteTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunListTestRuns200Response @@ -184,9 +206,12 @@ export function isUnexpected( ): response is LoadTestRunListTestRunsDefaultResponse; export function isUnexpected( response: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, -): response is LoadTestRunStopTestRunDefaultResponse; + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse, +): response is LoadTestRunGetTestRunFileDefaultResponse; +export function isUnexpected( + response: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, +): response is LoadTestRunStopDefaultResponse; export function isUnexpected( response: | LoadTestRunListMetricNamespaces200Response @@ -226,9 +251,56 @@ export function isUnexpected( ): response is LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, -): response is LoadTestRunTestRunListServerMetricsConfigDefaultResponse; + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, +): response is LoadTestRunGetServerMetricsConfigDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, +): response is TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse, +): response is TestProfileAdministrationDeleteTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse, +): response is TestProfileAdministrationGetTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse, +): response is TestProfileAdministrationListTestProfilesDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationGetTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse, +): response is TestProfileRunAdministrationStopDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, +): response is TestProfileRunAdministrationListTestProfileRunsDefaultResponse; export function isUnexpected( response: | LoadTestAdministrationCreateOrUpdateTest200Response @@ -258,20 +330,19 @@ export function isUnexpected( | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfig200Response | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStop200Response + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespaces200Response | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitions200Response @@ -288,8 +359,28 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateServerMetricsConfig200Response | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, ): response is | LoadTestAdministrationCreateOrUpdateTestDefaultResponse | LoadTestAdministrationDeleteTestDefaultResponse @@ -303,12 +394,12 @@ export function isUnexpected( | LoadTestAdministrationGetAppComponentsDefaultResponse | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitionsDefaultResponse | LoadTestRunListMetricsDefaultResponse @@ -316,7 +407,16 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateAppComponentsDefaultResponse | LoadTestRunGetAppComponentsDefaultResponse | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse { + | LoadTestRunGetServerMetricsConfigDefaultResponse + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + | TestProfileAdministrationDeleteTestProfileDefaultResponse + | TestProfileAdministrationGetTestProfileDefaultResponse + | TestProfileAdministrationListTestProfilesDefaultResponse + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + | TestProfileRunAdministrationStopDefaultResponse + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts index 2358e988eb..a47ec485da 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts @@ -6,6 +6,12 @@ import { logger } from "../logger.js"; import { TokenCredential } from "@azure/core-auth"; import { LoadTestServiceContext } from "./clientDefinitions.js"; +/** The optional parameters for the client */ +export interface LoadTestServiceContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + /** * Initialize a new instance of `LoadTestServiceContext` * @param endpointParam - A sequence of textual characters. @@ -15,11 +21,13 @@ import { LoadTestServiceContext } from "./clientDefinitions.js"; export default function createClient( endpointParam: string, credentials: TokenCredential, - options: ClientOptions = {}, + { + apiVersion = "2024-05-01-preview", + ...options + }: LoadTestServiceContextOptions = {}, ): LoadTestServiceContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - options.apiVersion = options.apiVersion ?? "2023-04-01-preview"; const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix @@ -39,12 +47,27 @@ export default function createClient( ], }, }; - const client = getClient( endpointUrl, credentials, options, ) as LoadTestServiceContext; + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); return client; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index a102d07cb8..c0a95b9edc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -13,18 +15,24 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ @@ -43,7 +51,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -61,6 +69,16 @@ export interface PassFailMetric { action?: PFAction; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface Secret { /** The value of the secret for the respective type */ @@ -79,12 +97,9 @@ export interface CertificateMetadata { name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -98,54 +113,61 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: Array; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; - /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; - /** Validation status of the file */ - validationStatus?: FileStatus; - /** Validation failure error details */ - validationFailureDetails?: string; -} - -/** Test app component */ + fileName: string; +} + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -155,15 +177,12 @@ export interface TestAppComponents { components: Record; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Kind of Azure resource type */ @@ -177,7 +196,7 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; + metrics: Record; } /** @@ -206,6 +225,8 @@ export interface ResourceMetric { export interface TestRun { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -226,6 +247,10 @@ export interface TestRun { testId?: string; /** The test run description. */ description?: string; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; } /** Error details if there is any failure in load test run */ @@ -243,24 +268,44 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; } -/** Filters to fetch the set of metric */ +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date | string; +} + +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -299,60 +344,106 @@ export interface TestRunServerMetricConfig { metrics?: Record; } +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurations; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurationsParent { + kind: ResourceKind; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurationsParent { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; +} + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export type TargetResourceConfigurations = + | TargetResourceConfigurationsParent + | FunctionFlexConsumptionTargetResourceConfigurations; /** Alias for PFMetrics */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; +export type PFMetrics = string; /** Alias for PFAgFunc */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; +export type PFAgFunc = string; /** Alias for PFAction */ -export type PFAction = "continue" | "stop"; +export type PFAction = string; /** Alias for PFResult */ -export type PFResult = "passed" | "undetermined" | "failed"; +export type PFResult = string; /** Alias for SecretType */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretType = string; /** Alias for CertificateType */ -export type CertificateType = "AKV_CERT_URI"; +export type CertificateType = string; /** Alias for FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +export type FileType = string; /** Alias for FileStatus */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; +export type FileStatus = string; +/** Alias for TestKind */ +export type TestKind = string; /** Alias for PFTestResult */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResult = string; /** Alias for Status */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Alias for Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type Status = string; +/** Alias for RequestDataLevel */ +export type RequestDataLevel = string; +/** Alias for TimeGrain */ +export type TimeGrain = string; +/** Alias for ResourceKind */ +export type ResourceKind = string; +/** Alias for TestProfileRunStatus */ +export type TestProfileRunStatus = string; +/** Alias for RecommendationCategory */ +export type RecommendationCategory = string; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index 392e850e81..bd84788e85 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -3,10 +3,12 @@ import { Paged } from "@azure/core-paging"; -/** Load test model */ +/** Load test model. */ export interface TestOutput { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,31 +17,37 @@ export interface TestOutput { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadataOutput; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifactsOutput; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKindOutput; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -57,7 +65,7 @@ export interface PassFailMetricOutput { clientMetric?: PFMetricsOutput; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -79,6 +87,16 @@ export interface PassFailMetricOutput { readonly result?: PFResultOutput; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteriaOutput { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface SecretOutput { /** The value of the secret for the respective type */ @@ -97,12 +115,9 @@ export interface CertificateMetadataOutput { name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfigurationOutput { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -116,56 +131,73 @@ export interface LoadTestConfigurationOutput { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfigOutput; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: Array; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfigOutput { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfigurationOutput { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + /** The input artifacts for the test. */ export interface TestInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; } -/** File info */ -export interface FileInfoOutput { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfoOutput { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileTypeOutput; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; /** Validation status of the file */ - validationStatus?: FileStatusOutput; + readonly validationStatus?: FileStatusOutput; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Test app component */ +/** Test app components */ export interface TestAppComponentsOutput { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -175,30 +207,24 @@ export interface TestAppComponentsOutput { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponentOutput { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -218,12 +244,12 @@ export interface TestServerMetricConfigOutput { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -255,10 +281,12 @@ export interface ResourceMetricOutput { /** Load test run model */ export interface TestRunOutput { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -273,8 +301,18 @@ export interface TestRunOutput { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: Array; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; /** Collection of test run artifacts */ @@ -291,9 +329,9 @@ export interface TestRunOutput { description?: string; /** The test run status. */ readonly status?: StatusOutput; - /** The test run start DateTime(ISO 8601 literal format). */ + /** The test run start DateTime(RFC 3339 literal format). */ readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ + /** The test run end DateTime(RFC 3339 literal format). */ readonly endDateTime?: string; /** Test run initiated time. */ readonly executedDateTime?: string; @@ -303,11 +341,19 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** Type of test. */ + readonly kind?: TestKindOutput; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevelOutput; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -343,6 +389,18 @@ export interface TestRunStatisticsOutput { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -362,23 +420,53 @@ export interface TestRunArtifactsOutput { /** The input artifacts for the test run. */ export interface TestRunInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestRunFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestRunFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestRunFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestRunFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; +} + +/** Test run file info. */ +export interface TestRunFileInfoOutput { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; + /** Validation status of the file */ + readonly validationStatus?: FileStatusOutput; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifactsOutput { /** File info */ - resultFileInfo?: FileInfoOutput; + resultFileInfo?: TestRunFileInfoOutput; /** File info */ - logsFileInfo?: FileInfoOutput; + logsFileInfo?: TestRunFileInfoOutput; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfoOutput; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfoOutput; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfoOutput { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: string; } /** Represents collection of metric namespaces. */ @@ -451,7 +539,7 @@ export interface TimeSeriesElementOutput { /** Represents a metric value. */ export interface MetricValueOutput { - /** The timestamp for the metric value in ISO 8601 format. */ + /** The timestamp for the metric value in RFC 3339 format. */ timestamp?: string; /** The metric value. */ value?: number; @@ -465,8 +553,14 @@ export interface DimensionValueOutput { value?: string; } +/** Metrics dimension values. */ export interface DimensionValueListOutput { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Test run app component */ @@ -479,11 +573,11 @@ export interface TestRunAppComponentsOutput { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -499,102 +593,176 @@ export interface TestRunServerMetricConfigOutput { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfileOutput { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsOutput; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: string; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: string; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurationsOutputParent { + kind: ResourceKindOutput; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurationsOutput + extends TargetResourceConfigurationsOutputParent { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record< + string, + FunctionFlexConsumptionResourceConfigurationOutput + >; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfigurationOutput { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRunOutput { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsOutput; + /** The test profile run status. */ + readonly status?: TestProfileRunStatusOutput; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: Array; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: string; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: string; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: Array; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: string; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: string; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetailOutput { + /** Status of the test run. */ + status: StatusOutput; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendationOutput { + /** Category of the recommendation. */ + category: RecommendationCategoryOutput; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export type TargetResourceConfigurationsOutput = + | TargetResourceConfigurationsOutputParent + | FunctionFlexConsumptionTargetResourceConfigurationsOutput; /** Alias for PFMetricsOutput */ -export type PFMetricsOutput = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; +export type PFMetricsOutput = string; /** Alias for PFAgFuncOutput */ -export type PFAgFuncOutput = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; +export type PFAgFuncOutput = string; /** Alias for PFActionOutput */ -export type PFActionOutput = "continue" | "stop"; +export type PFActionOutput = string; /** Alias for PFResultOutput */ -export type PFResultOutput = "passed" | "undetermined" | "failed"; +export type PFResultOutput = string; /** Alias for SecretTypeOutput */ -export type SecretTypeOutput = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretTypeOutput = string; /** Alias for CertificateTypeOutput */ -export type CertificateTypeOutput = "AKV_CERT_URI"; +export type CertificateTypeOutput = string; /** Alias for FileTypeOutput */ -export type FileTypeOutput = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS"; +export type FileTypeOutput = string; /** Alias for FileStatusOutput */ -export type FileStatusOutput = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Collection of tests */ +export type FileStatusOutput = string; +/** Alias for TestKindOutput */ +export type TestKindOutput = string; +/** Paged collection of Test items */ export type PagedTestOutput = Paged; -/** Collection of files. */ -export type PagedFileInfoOutput = Paged; +/** Paged collection of TestFileInfo items */ +export type PagedTestFileInfoOutput = Paged; /** Alias for PFTestResultOutput */ -export type PFTestResultOutput = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResultOutput = string; /** Alias for StatusOutput */ -export type StatusOutput = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Collection of test runs */ +export type StatusOutput = string; +/** Alias for RequestDataLevelOutput */ +export type RequestDataLevelOutput = string; +/** Paged collection of TestRun items */ export type PagedTestRunOutput = Paged; /** Alias for AggregationTypeOutput */ -export type AggregationTypeOutput = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; +export type AggregationTypeOutput = string; /** Alias for MetricUnitOutput */ -export type MetricUnitOutput = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +export type MetricUnitOutput = string; /** Alias for TimeGrainOutput */ -export type TimeGrainOutput = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TimeGrainOutput = string; /** The response to a metrics query. */ -export type PagedTimeSeriesElementOutput = Paged; -/** Paged collection of DimensionValueList items */ -export type PagedDimensionValueListOutput = Paged; +export type MetricsOutput = Paged; +/** Alias for ResourceKindOutput */ +export type ResourceKindOutput = string; +/** Paged collection of TestProfile items */ +export type PagedTestProfileOutput = Paged; +/** Alias for TestProfileRunStatusOutput */ +export type TestProfileRunStatusOutput = string; +/** Alias for RecommendationCategoryOutput */ +export type RecommendationCategoryOutput = string; +/** Paged collection of TestProfileRun items */ +export type PagedTestProfileRunOutput = Paged; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 9437426616..55814d74ea 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -8,21 +8,24 @@ import { TestAppComponents, TestServerMetricConfig, TestRun, - Interval, + TimeGrain, MetricRequestPayload, TestRunAppComponents, TestRunServerMetricConfig, + TestProfile, + TestProfileRun, } from "./models.js"; -/** Load test model */ +/** The resource instance. */ export type TestResourceMergeAndPatch = Partial; export interface LoadTestAdministrationCreateOrUpdateTestBodyParam { - /** Load test model */ + /** The resource instance. */ body: TestResourceMergeAndPatch; } export interface LoadTestAdministrationCreateOrUpdateTestMediaTypesParam { + /** This request has a JSON Merge Patch body. */ contentType: "application/merge-patch+json"; } @@ -45,16 +48,10 @@ export interface LoadTestAdministrationListTestsQueryParamProperties { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date | string; /** Number of results in response. */ maxpagesize?: number; } @@ -89,6 +86,7 @@ export interface LoadTestAdministrationUploadTestFileQueryParam { } export interface LoadTestAdministrationUploadTestFileMediaTypesParam { + /** Content type. */ contentType: "application/octet-stream"; } @@ -109,6 +107,7 @@ export interface LoadTestAdministrationCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestAdministrationCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -128,6 +127,7 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigBodyPara } export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -137,7 +137,7 @@ export type LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters = RequestParameters; export type LoadTestAdministrationGetServerMetricsConfigParameters = RequestParameters; -export type LoadTestRunDeleteTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunParameters = RequestParameters; /** The resource instance. */ export type TestRunResourceMergeAndPatch = Partial; @@ -170,8 +170,7 @@ export type LoadTestRunCreateOrUpdateTestRunParameters = LoadTestRunCreateOrUpdateTestRunMediaTypesParam & LoadTestRunCreateOrUpdateTestRunBodyParam & RequestParameters; -export type LoadTestRunGetTestRunParameters = RequestParameters; -export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunDeleteTestRunParameters = RequestParameters; export interface LoadTestRunListTestRunsQueryParamProperties { /** @@ -187,10 +186,10 @@ export interface LoadTestRunListTestRunsQueryParamProperties { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date | string; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date | string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -203,16 +202,17 @@ export interface LoadTestRunListTestRunsQueryParam { export type LoadTestRunListTestRunsParameters = LoadTestRunListTestRunsQueryParam & RequestParameters; -export type LoadTestRunStopTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunStopParameters = RequestParameters; export type LoadTestRunListMetricNamespacesParameters = RequestParameters; export interface LoadTestRunListMetricDefinitionsQueryParamProperties { /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; + metricNamespace: string; } export interface LoadTestRunListMetricDefinitionsQueryParam { - queryParameters?: LoadTestRunListMetricDefinitionsQueryParamProperties; + queryParameters: LoadTestRunListMetricDefinitionsQueryParamProperties; } export type LoadTestRunListMetricDefinitionsParameters = @@ -220,27 +220,24 @@ export type LoadTestRunListMetricDefinitionsParameters = export interface LoadTestRunListMetricsBodyParam { /** Metric dimension filter */ - body: MetricRequestPayload; + body?: MetricRequestPayload; } export interface LoadTestRunListMetricsQueryParamProperties { /** The aggregation */ aggregation?: string; - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; + metricname: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + metricNamespace: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricsQueryParam { - queryParameters?: LoadTestRunListMetricsQueryParamProperties; + queryParameters: LoadTestRunListMetricsQueryParamProperties; } export type LoadTestRunListMetricsParameters = @@ -249,17 +246,14 @@ export type LoadTestRunListMetricsParameters = RequestParameters; export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; + metricname: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ metricNamespace: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricDimensionValuesQueryParam { @@ -278,6 +272,7 @@ export interface LoadTestRunCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestRunCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -296,6 +291,7 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam { } export interface LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -303,5 +299,97 @@ export type LoadTestRunCreateOrUpdateServerMetricsConfigParameters = LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam & LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam & RequestParameters; -export type LoadTestRunTestRunListServerMetricsConfigParameters = +export type LoadTestRunGetServerMetricsConfigParameters = RequestParameters; +/** The resource instance. */ +export type TestProfileResourceMergeAndPatch = Partial; + +export interface TestProfileAdministrationCreateOrUpdateTestProfileBodyParam { + /** The resource instance. */ + body: TestProfileResourceMergeAndPatch; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type TestProfileAdministrationCreateOrUpdateTestProfileParameters = + TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam & + TestProfileAdministrationCreateOrUpdateTestProfileBodyParam & + RequestParameters; +export type TestProfileAdministrationDeleteTestProfileParameters = RequestParameters; +export type TestProfileAdministrationGetTestProfileParameters = + RequestParameters; + +export interface TestProfileAdministrationListTestProfilesQueryParamProperties { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedEndTime?: Date | string; + /** Comma separated list of IDs of the test profiles to filter. */ + testProfileIds?: string; + /** Comma separated list IDs of the tests which should be associated with the test profiles to fetch. */ + testIds?: string; +} + +export interface TestProfileAdministrationListTestProfilesQueryParam { + queryParameters?: TestProfileAdministrationListTestProfilesQueryParamProperties; +} + +export type TestProfileAdministrationListTestProfilesParameters = + TestProfileAdministrationListTestProfilesQueryParam & RequestParameters; +export type TestProfileRunAdministrationGetTestProfileRunParameters = + RequestParameters; +/** The resource instance. */ +export type TestProfileRunResourceMergeAndPatch = Partial; + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam { + /** The resource instance. */ + body: TestProfileRunResourceMergeAndPatch; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters = + TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam & + TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam & + RequestParameters; +export type TestProfileRunAdministrationDeleteTestProfileRunParameters = + RequestParameters; +export type TestProfileRunAdministrationStopParameters = RequestParameters; + +export interface TestProfileRunAdministrationListTestProfileRunsQueryParamProperties { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Minimum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minStartDateTime?: Date | string; + /** Maximum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxStartDateTime?: Date | string; + /** Minimum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minEndDateTime?: Date | string; + /** Maximum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxEndDateTime?: Date | string; + /** Start DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateEndTime?: Date | string; + /** Comma separated list of IDs of the test profile runs to filter. */ + testProfileRunIds?: string; + /** Comma separated IDs of the test profiles which should be associated with the test profile runs to fetch. */ + testProfileIds?: string; + /** Comma separated list of Statuses of the test profile runs to filter. */ + statuses?: string; +} + +export interface TestProfileRunAdministrationListTestProfileRunsQueryParam { + queryParameters?: TestProfileRunAdministrationListTestProfileRunsQueryParamProperties; +} + +export type TestProfileRunAdministrationListTestProfileRunsParameters = + TestProfileRunAdministrationListTestProfileRunsQueryParam & RequestParameters; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts deleted file mode 100644 index 19a90195ba..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { Client, HttpResponse } from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { - CancelOnProgress, - CreateHttpPollerOptions, - RunningOperation, - OperationResponse, - OperationState, - createHttpPoller, -} from "@azure/core-lro"; -import { - LoadTestRunCreateOrUpdateTestRun200Response, - LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, -} from "./responses.js"; - -/** - * A simple poller that can be used to poll a long running operation. - */ -export interface SimplePollerLike< - TState extends OperationState, - TResult, -> { - /** - * Returns true if the poller has finished polling. - */ - isDone(): boolean; - /** - * Returns the state of the operation. - */ - getOperationState(): TState; - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult(): TResult | undefined; - /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - */ - poll(options?: { abortSignal?: AbortSignalLike }): Promise; - /** - * Returns a promise that will resolve once the underlying operation is completed. - */ - pollUntilDone(pollOptions?: { - abortSignal?: AbortSignalLike; - }): Promise; - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback: (state: TState) => void): CancelOnProgress; - - /** - * Returns a promise that could be used for serialized version of the poller's operation - * by invoking the operation's serialize method. - */ - serialize(): Promise; - - /** - * Wait the poller to be submitted. - */ - submitted(): Promise; - - /** - * Returns a string representation of the poller's operation. Similar to serialize but returns a string. - * @deprecated Use serialize() instead. - */ - toString(): string; - - /** - * Stops the poller from continuing to poll. Please note this will only stop the client-side polling - * @deprecated Use abortSignal to stop polling instead. - */ - stopPolling(): void; - - /** - * Returns true if the poller is stopped. - * @deprecated Use abortSignal status to track this instead. - */ - isStopped(): boolean; -} - -/** - * Helper function that builds a Poller object to help polling a long running operation. - * @param client - Client to use for sending the request to get additional pages. - * @param initialResponse - The initial response. - * @param options - Options to set a resume state or custom polling interval. - * @returns - A poller object to poll for operation state updates and eventually get the final response. - */ -export async function getLongRunningPoller< - TResult extends - | LoadTestRunCreateOrUpdateTestRunLogicalResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ->( - client: Client, - initialResponse: - | LoadTestRunCreateOrUpdateTestRun200Response - | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller( - client: Client, - initialResponse: TResult, - options: CreateHttpPollerOptions> = {}, -): Promise, TResult>> { - const abortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - // In the case of Rest Clients we are building the LRO poller object from a response that's the reason - // we are not triggering the initial request here, just extracting the information from the - // response we were provided. - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - pollOptions?: { abortSignal?: AbortSignalLike }, - ) => { - // This is the callback that is going to be called to poll the service - // to get the latest status. We use the client provided and the polling path - // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location - // depending on the lro pattern that the service implements. If non is provided we default to the initial path. - function abortListener(): void { - abortController.abort(); - } - const inputAbortSignal = pollOptions?.abortSignal; - const abortSignal = abortController.signal; - if (inputAbortSignal?.aborted) { - abortController.abort(); - } else if (!abortSignal.aborted) { - inputAbortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client - .pathUnchecked(path ?? initialResponse.request.url) - .get({ abortSignal }); - } finally { - inputAbortSignal?.removeEventListener("abort", abortListener); - } - const lroResponse = getLroResponse(response as TResult); - lroResponse.rawResponse.headers["x-ms-original-url"] = - initialResponse.request.url; - return lroResponse; - }, - }; - - options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; - const httpPoller = createHttpPoller(poller, options); - const simplePoller: SimplePollerLike, TResult> = { - isDone() { - return httpPoller.isDone; - }, - isStopped() { - return abortController.signal.aborted; - }, - getOperationState() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return httpPoller.operationState; - }, - getResult() { - return httpPoller.result; - }, - toString() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return JSON.stringify({ - state: httpPoller.operationState, - }); - }, - stopPolling() { - abortController.abort(); - }, - onProgress: httpPoller.onProgress, - poll: httpPoller.poll, - pollUntilDone: httpPoller.pollUntilDone, - serialize: httpPoller.serialize, - submitted: httpPoller.submitted, - }; - return simplePoller; -} - -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResult, -): OperationResponse { - if (Number.isNaN(response.status)) { - throw new TypeError( - `Status code of the response is not a number. Value: ${response.status}`, - ); - } - - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index 2c79e0b52c..8e1df1b17a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,18 +6,23 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - FileInfoOutput, - PagedFileInfoOutput, + FileTypeOutput, + FileStatusOutput, + PagedTestFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, - PagedTimeSeriesElementOutput, - PagedDimensionValueListOutput, + MetricsOutput, + DimensionValueListOutput, TestRunAppComponentsOutput, TestRunServerMetricConfigOutput, + TestProfileOutput, + PagedTestProfileOutput, + TestProfileRunOutput, + PagedTestProfileRunOutput, } from "./outputModels.js"; /** The request has succeeded. */ @@ -106,7 +111,13 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: FileInfoOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -125,7 +136,13 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -162,7 +179,7 @@ export interface LoadTestAdministrationDeleteTestFileDefaultResponse export interface LoadTestAdministrationListTestFiles200Response extends HttpResponse { status: "200"; - body: PagedFileInfoOutput; + body: PagedTestFileInfoOutput; } export interface LoadTestAdministrationListTestFilesDefaultHeaders { @@ -271,25 +288,21 @@ export interface LoadTestAdministrationGetServerMetricsConfigDefaultResponse LoadTestAdministrationGetServerMetricsConfigDefaultHeaders; } -/** There is no content to send for this request, but the headers may be useful. */ -export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { - status: "204"; +/** The request has succeeded. */ +export interface LoadTestRunGetTestRun200Response extends HttpResponse { + status: "200"; + body: TestRunOutput; } -export interface LoadTestRunDeleteTestRunDefaultHeaders { +export interface LoadTestRunGetTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; -} - -export interface LoadTestRunCreateOrUpdateTestRun200Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; + headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; } /** The request has succeeded. */ @@ -297,12 +310,6 @@ export interface LoadTestRunCreateOrUpdateTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun200Headers; -} - -export interface LoadTestRunCreateOrUpdateTestRun201Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; } /** The request has succeeded and a new resource has been created as a result. */ @@ -310,7 +317,6 @@ export interface LoadTestRunCreateOrUpdateTestRun201Response extends HttpResponse { status: "201"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun201Headers; } export interface LoadTestRunCreateOrUpdateTestRunDefaultHeaders { @@ -325,79 +331,77 @@ export interface LoadTestRunCreateOrUpdateTestRunDefaultResponse headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRunDefaultHeaders; } -/** The final response for long-running CreateOrUpdateTestRun operation */ -export interface LoadTestRunCreateOrUpdateTestRunLogicalResponse - extends HttpResponse { - status: "200"; - body: TestRunOutput; -} - -/** The request has succeeded. */ -export interface LoadTestRunGetTestRun200Response extends HttpResponse { - status: "200"; - body: TestRunOutput; +/** There is no content to send for this request, but the headers may be useful. */ +export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { + status: "204"; } -export interface LoadTestRunGetTestRunDefaultHeaders { +export interface LoadTestRunDeleteTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { +export interface LoadTestRunListTestRuns200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: PagedTestRunOutput; } -export interface LoadTestRunGetTestRunFileDefaultHeaders { +export interface LoadTestRunListTestRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { +export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunListTestRuns200Response extends HttpResponse { +export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: PagedTestRunOutput; + body: { + url?: string; + fileType?: FileTypeOutput; + expireDateTime?: string; + validationStatus?: FileStatusOutput; + validationFailureDetails?: string; + }; } -export interface LoadTestRunListTestRunsDefaultHeaders { +export interface LoadTestRunGetTestRunFileDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunStopTestRun200Response extends HttpResponse { +export interface LoadTestRunStop200Response extends HttpResponse { status: "200"; body: TestRunOutput; } -export interface LoadTestRunStopTestRunDefaultHeaders { +export interface LoadTestRunStopDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunStopTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunStopDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunStopTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunStopDefaultHeaders; } /** The request has succeeded. */ @@ -441,7 +445,7 @@ export interface LoadTestRunListMetricDefinitionsDefaultResponse /** The request has succeeded. */ export interface LoadTestRunListMetrics200Response extends HttpResponse { status: "200"; - body: PagedTimeSeriesElementOutput; + body: MetricsOutput; } export interface LoadTestRunListMetricsDefaultHeaders { @@ -459,7 +463,7 @@ export interface LoadTestRunListMetricsDefaultResponse extends HttpResponse { export interface LoadTestRunListMetricDimensionValues200Response extends HttpResponse { status: "200"; - body: PagedDimensionValueListOutput; + body: DimensionValueListOutput; } export interface LoadTestRunListMetricDimensionValuesDefaultHeaders { @@ -547,21 +551,211 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse } /** The request has succeeded. */ -export interface LoadTestRunTestRunListServerMetricsConfig200Response +export interface LoadTestRunGetServerMetricsConfig200Response extends HttpResponse { status: "200"; body: TestRunServerMetricConfigOutput; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultHeaders { +export interface LoadTestRunGetServerMetricsConfigDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface LoadTestRunGetServerMetricsConfigDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & LoadTestRunGetServerMetricsConfigDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationCreateOrUpdateTestProfile200Response + extends HttpResponse { + status: "200"; + body: TestProfileOutput; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface TestProfileAdministrationCreateOrUpdateTestProfile201Response + extends HttpResponse { + status: "201"; + body: TestProfileOutput; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface TestProfileAdministrationDeleteTestProfile204Response + extends HttpResponse { + status: "204"; +} + +export interface TestProfileAdministrationDeleteTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationDeleteTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationDeleteTestProfileDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationGetTestProfile200Response + extends HttpResponse { + status: "200"; + body: TestProfileOutput; +} + +export interface TestProfileAdministrationGetTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationGetTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationGetTestProfileDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationListTestProfiles200Response + extends HttpResponse { + status: "200"; + body: PagedTestProfileOutput; +} + +export interface TestProfileAdministrationListTestProfilesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationListTestProfilesDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationListTestProfilesDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationGetTestProfileRun200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationGetTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationGetTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationGetTestProfileRunDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + extends HttpResponse { + status: "201"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface TestProfileRunAdministrationDeleteTestProfileRun204Response + extends HttpResponse { + status: "204"; +} + +export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationStop200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationStopDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationStopDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & TestProfileRunAdministrationStopDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationListTestProfileRuns200Response + extends HttpResponse { + status: "200"; + body: PagedTestProfileRunOutput; +} + +export interface TestProfileRunAdministrationListTestProfileRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultResponse +export interface TestProfileRunAdministrationListTestProfileRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & - LoadTestRunTestRunListServerMetricsConfigDefaultHeaders; + TestProfileRunAdministrationListTestProfileRunsDefaultHeaders; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts new file mode 100644 index 0000000000..d9fc4ff2ea --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createOrUpdateTestProfile, + deleteTestProfile, + getTestProfile, + listTestProfiles, +} from "./operations.js"; +export { + createTestProfileAdministrationOperations, + TestProfileAdministrationOperationsClientOptions, + LoadTestServiceContext, +} from "./testProfileAdministrationOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts new file mode 100644 index 0000000000..521d111758 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + targetResourceConfigurationsUnionSerializer, + TestProfile, + ResourceKind, + _PagedTestProfile, +} from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; +import { + isUnexpected, + LoadTestServiceContext as Client, + TestProfileAdministrationCreateOrUpdateTestProfile200Response, + TestProfileAdministrationCreateOrUpdateTestProfile201Response, + TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, + TestProfileAdministrationDeleteTestProfile204Response, + TestProfileAdministrationDeleteTestProfileDefaultResponse, + TestProfileAdministrationGetTestProfile200Response, + TestProfileAdministrationGetTestProfileDefaultResponse, + TestProfileAdministrationListTestProfiles200Response, + TestProfileAdministrationListTestProfilesDefaultResponse, +} from "../../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, + createRestError, +} from "@azure-rest/core-client"; +import { + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, +} from "../models/options.js"; + +export function _createOrUpdateTestProfileSend( + context: Client, + testProfileId: string, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse +> { + return context + .path("/test-profiles/{testProfileId}", testProfileId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/merge-patch+json", + body: { + displayName: body["displayName"], + description: body["description"], + testId: body["testId"], + targetResourceId: body["targetResourceId"], + targetResourceConfigurations: !body.targetResourceConfigurations + ? body.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + body.targetResourceConfigurations, + ), + }, + }); +} + +export async function _createOrUpdateTestProfileDeserialize( + result: + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + testProfileId: result.body["testProfileId"], + displayName: result.body["displayName"], + description: result.body["description"], + testId: result.body["testId"], + targetResourceId: result.body["targetResourceId"], + targetResourceConfigurations: !result.body.targetResourceConfigurations + ? undefined + : { + kind: result.body.targetResourceConfigurations?.[ + "kind" + ] as ResourceKind, + }, + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, + createdBy: result.body["createdBy"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: result.body["lastModifiedBy"], + }; +} + +/** Create a new test profile or update an existing test profile by providing the test profile Id. */ +export async function createOrUpdateTestProfile( + context: Client, + testProfileId: string, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestProfileSend( + context, + testProfileId, + body, + options, + ); + return _createOrUpdateTestProfileDeserialize(result); +} + +export function _deleteTestProfileSend( + context: Client, + testProfileId: string, + options: DeleteTestProfileOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse +> { + return context + .path("/test-profiles/{testProfileId}", testProfileId) + .delete({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _deleteTestProfileDeserialize( + result: + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** Delete a test profile by its test profile Id. */ +export async function deleteTestProfile( + context: Client, + testProfileId: string, + options: DeleteTestProfileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestProfileSend(context, testProfileId, options); + return _deleteTestProfileDeserialize(result); +} + +export function _getTestProfileSend( + context: Client, + testProfileId: string, + options: GetTestProfileOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse +> { + return context + .path("/test-profiles/{testProfileId}", testProfileId) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getTestProfileDeserialize( + result: + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + testProfileId: result.body["testProfileId"], + displayName: result.body["displayName"], + description: result.body["description"], + testId: result.body["testId"], + targetResourceId: result.body["targetResourceId"], + targetResourceConfigurations: !result.body.targetResourceConfigurations + ? undefined + : { + kind: result.body.targetResourceConfigurations?.[ + "kind" + ] as ResourceKind, + }, + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, + createdBy: result.body["createdBy"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: result.body["lastModifiedBy"], + }; +} + +/** Get load test profile details by test profile Id. */ +export async function getTestProfile( + context: Client, + testProfileId: string, + options: GetTestProfileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTestProfileSend(context, testProfileId, options); + return _getTestProfileDeserialize(result); +} + +export function _listTestProfilesSend( + context: Client, + options: ListTestProfilesOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse +> { + return context + .path("/test-profiles") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxpagesize: options?.maxpagesize, + lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), + testProfileIds: options?.testProfileIds, + testIds: options?.testIds, + }, + }); +} + +export async function _listTestProfilesDeserialize( + result: + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse, +): Promise<_PagedTestProfile> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: result.body["value"].map((p) => ({ + testProfileId: p["testProfileId"], + displayName: p["displayName"], + description: p["description"], + testId: p["testId"], + targetResourceId: p["targetResourceId"], + targetResourceConfigurations: !p.targetResourceConfigurations + ? undefined + : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + })), + nextLink: result.body["nextLink"], + }; +} + +/** Get all test profiles for the given filters. */ +export function listTestProfiles( + context: Client, + options: ListTestProfilesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTestProfilesSend(context, options), + _listTestProfilesDeserialize, + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/pagingHelpers.ts new file mode 100644 index 0000000000..754f1e613b --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/pagingHelpers.ts @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; +import { + BuildPagedAsyncIteratorOptions, + ContinuablePage, + PageSettings, + PagedAsyncIterableIterator, + PagedResult, +} from "../models/pagingTypes.js"; +import { isUnexpected } from "../../rest/index.js"; + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => PromiseLike, + options: BuildPagedAsyncIteratorOptions = {}, +): PagedAsyncIterableIterator { + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; + const pagedResult: PagedResult = { + getPage: async (pageLink?: string) => { + const result = + pageLink === undefined + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + checkPagingRequest(result); + const results = await processResponseBody(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName) as TPage; + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }, + }; + return getPagedAsyncIterator(pagedResult); +} + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ + +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {}, +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { + throw new RestError( + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, + ); + } + + if (nextLink === null) { + return undefined; + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + if (!Array.isArray(value)) { + throw new RestError( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + if (isUnexpected(response)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts new file mode 100644 index 0000000000..b386495817 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { TokenCredential } from "@azure/core-auth"; +import { ClientOptions } from "@azure-rest/core-client"; +import { LoadTestServiceContext } from "../../rest/index.js"; +import getClient from "../../rest/index.js"; + +/** Optional parameters for the client. */ +export interface TestProfileAdministrationOperationsClientOptions + extends ClientOptions { + /** The API version to use for this operation. */ + apiVersion?: string; +} + +export { LoadTestServiceContext } from "../../rest/index.js"; + +export function createTestProfileAdministrationOperations( + endpointParam: string, + credential: TokenCredential, + options: TestProfileAdministrationOperationsClientOptions = {}, +): LoadTestServiceContext { + const clientContext = getClient(endpointParam, credential, options); + return clientContext; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts new file mode 100644 index 0000000000..2e0e8078ae --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + TestProfileAdministrationOperationsClient, + TestProfileAdministrationOperationsClientOptions, +} from "./testProfileAdministrationOperationsClient.js"; +export { + Test, + PassFailCriteria, + PassFailMetric, + PFMetrics, + PFAgFunc, + PFAction, + PFResult, + AutoStopCriteria, + Secret, + SecretType, + CertificateMetadata, + CertificateType, + LoadTestConfiguration, + OptionalLoadTestConfig, + RegionalConfiguration, + TestInputArtifacts, + TestFileInfo, + FileType, + FileStatus, + TestKind, + TestAppComponents, + AppComponent, + TestServerMetricConfig, + ResourceMetric, + APIVersions, + TestRun, + ErrorDetails, + TestRunStatistics, + TestRunArtifacts, + TestRunInputArtifacts, + TestRunFileInfo, + TestRunOutputArtifacts, + ArtifactsContainerInfo, + PFTestResult, + Status, + RequestDataLevel, + TestRunAppComponents, + TestRunServerMetricConfig, + TimeGrain, + DimensionValueList, + MetricDefinitionCollection, + MetricDefinition, + NameAndDesc, + AggregationType, + MetricUnit, + MetricAvailability, + MetricNamespaceCollection, + MetricNamespace, + MetricRequestPayload, + DimensionFilter, + TimeSeriesElement, + MetricValue, + DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts new file mode 100644 index 0000000000..3428af974e --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + Test, + PassFailCriteria, + PassFailMetric, + PFMetrics, + PFAgFunc, + PFAction, + PFResult, + AutoStopCriteria, + Secret, + SecretType, + CertificateMetadata, + CertificateType, + LoadTestConfiguration, + OptionalLoadTestConfig, + RegionalConfiguration, + TestInputArtifacts, + TestFileInfo, + FileType, + FileStatus, + TestKind, + TestAppComponents, + AppComponent, + TestServerMetricConfig, + ResourceMetric, + APIVersions, + TestRun, + ErrorDetails, + TestRunStatistics, + TestRunArtifacts, + TestRunInputArtifacts, + TestRunFileInfo, + TestRunOutputArtifacts, + ArtifactsContainerInfo, + PFTestResult, + Status, + RequestDataLevel, + TestRunAppComponents, + TestRunServerMetricConfig, + TimeGrain, + DimensionValueList, + MetricDefinitionCollection, + MetricDefinition, + NameAndDesc, + AggregationType, + MetricUnit, + MetricAvailability, + MetricNamespaceCollection, + MetricNamespace, + MetricRequestPayload, + DimensionFilter, + TimeSeriesElement, + MetricValue, + DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, +} from "./models.js"; +export { + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, +} from "./options.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts new file mode 100644 index 0000000000..31dd6af57e --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts @@ -0,0 +1,1244 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { serializeRecord } from "../../helpers/serializerHelpers.js"; +import { + Test as TestRest, + PassFailCriteria as PassFailCriteriaRest, + PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, + Secret as SecretRest, + CertificateMetadata as CertificateMetadataRest, + LoadTestConfiguration as LoadTestConfigurationRest, + OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, + TestAppComponents as TestAppComponentsRest, + AppComponent as AppComponentRest, + TestServerMetricConfig as TestServerMetricConfigRest, + ResourceMetric as ResourceMetricRest, + TestRun as TestRunRest, + TestRunAppComponents as TestRunAppComponentsRest, + TestRunServerMetricConfig as TestRunServerMetricConfigRest, + MetricRequestPayload as MetricRequestPayloadRest, + DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, +} from "../../rest/index.js"; + +/** Load test model. */ +export interface Test { + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata. */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; + /** The input artifacts for the test. */ + readonly inputArtifacts?: TestInputArtifacts; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; + /** The test description. */ + description?: string; + /** Display name of a test. */ + displayName?: string; + /** Subnet ID on which the load test instances should run. */ + subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; + /** Type of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityType?: string; + /** Resource Id of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testSerializer(item: Test): TestRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + }; +} + +/** Pass fail criteria for a test. */ +export interface PassFailCriteria { + /** Map of id and pass fail metrics { id : pass fail metrics }. */ + passFailMetrics?: Record; +} + +export function passFailCriteriaSerializer( + item: PassFailCriteria, +): PassFailCriteriaRest { + return { + passFailMetrics: !item.passFailMetrics + ? item.passFailMetrics + : (serializeRecord( + item.passFailMetrics as any, + passFailMetricSerializer, + ) as any), + }; +} + +/** Pass fail metric */ +export interface PassFailMetric { + /** The client metric on which the criteria should be applied. */ + clientMetric?: PFMetrics; + /** + * The aggregation function to be applied on the client metric. Allowed functions + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, + * ‘count’ - for requests + */ + aggregate?: PFAgFunc; + /** The comparison operator. Supported types ‘>’, ‘<’ */ + condition?: string; + /** Request name for which the Pass fail criteria has to be applied */ + requestName?: string; + /** + * The value to compare with the client metric. Allowed values - ‘error : [0.0 , + * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + */ + value?: number; + /** Action taken after the threshold is met. Default is ‘continue’. */ + action?: PFAction; + /** The actual value of the client metric for the test run. */ + readonly actualValue?: number; + /** Outcome of the test run. */ + readonly result?: PFResult; +} + +export function passFailMetricSerializer( + item: PassFailMetric, +): PassFailMetricRest { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + }; +} + +/** Metrics for pass/fail criteria. */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Aggregation functions for pass/fail criteria. */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p75" + | "p90" + | "p95" + | "p96" + | "p97" + | "p98" + | "p99" + | "p99.9" + | "p99.99" + | "min" + | "max"; +/** Action to take on failure of pass/fail criteria. */ +export type PFAction = "continue" | "stop"; +/** Pass/fail criteria result. */ +export type PFResult = "passed" | "undetermined" | "failed"; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + +/** Secret */ +export interface Secret { + /** The value of the secret for the respective type */ + value?: string; + /** Type of secret */ + type?: SecretType; +} + +export function secretSerializer(item: Secret): SecretRest { + return { + value: item["value"], + type: item["type"], + }; +} + +/** Types of secrets supported. */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; + +/** Certificates metadata */ +export interface CertificateMetadata { + /** The value of the certificate for respective type */ + value?: string; + /** Type of certificate */ + type?: CertificateType; + /** Name of the certificate. */ + name?: string; +} + +export function certificateMetadataSerializer( + item: CertificateMetadata, +): CertificateMetadataRest { + return { + value: item["value"], + type: item["type"], + name: item["name"], + }; +} + +/** Types of certificates supported. */ +export type CertificateType = "AKV_CERT_URI"; + +/** Configurations for the load test. */ +export interface LoadTestConfiguration { + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + engineInstances?: number; + /** + * If false, Azure Load Testing copies and processes your input files unmodified + * across all test engine instances. If true, Azure Load Testing splits the CSV + * input data evenly across all engine instances. If you provide multiple CSV + * files, each file will be split evenly. + */ + splitAllCSVs?: boolean; + /** + * If true, optionalLoadTestConfig is required and JMX script for the load test is + * not required to upload. + */ + quickStartTest?: boolean; + /** Configuration for quick load test */ + optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; +} + +export function loadTestConfigurationSerializer( + item: LoadTestConfiguration, +): LoadTestConfigurationRest { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item.optionalLoadTestConfig + ? item.optionalLoadTestConfig + : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), + }; +} + +/** Configuration for quick load test */ +export interface OptionalLoadTestConfig { + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + endpointUrl?: string; + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ + virtualUsers?: number; + /** Ramp up time in seconds. */ + rampUpTime?: number; + /** Test run duration in seconds. */ + duration?: number; +} + +export function optionalLoadTestConfigSerializer( + item: OptionalLoadTestConfig, +): OptionalLoadTestConfigRest { + return { + endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + +/** The input artifacts for the test. */ +export interface TestInputArtifacts { + /** File info */ + configFileInfo?: TestFileInfo; + /** File info */ + testScriptFileInfo?: TestFileInfo; + /** File info */ + userPropFileInfo?: TestFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestFileInfo[]; +} + +/** Test file info. */ +export interface TestFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +/** Types of file supported. */ +export type FileType = + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG" + | "TEST_SCRIPT"; +/** File status. */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; +/** Test kind */ +export type TestKind = "URL" | "JMX" | "Locust"; + +/** Test app components */ +export interface TestAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test identifier */ + readonly testId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testAppComponentsSerializer( + item: TestAppComponents, +): TestAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +export interface AppComponent { + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; + /** Azure resource name, required while creating the app component. */ + resourceName: string; + /** Azure resource type, required while creating the app component. */ + resourceType: string; + /** Azure resource display name */ + displayName?: string; + /** Resource group name of the Azure resource */ + readonly resourceGroup?: string; + /** Subscription Id of the Azure resource */ + readonly subscriptionId?: string; + /** Kind of Azure resource type */ + kind?: string; +} + +export function appComponentSerializer(item: AppComponent): AppComponentRest { + return { + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + kind: item["kind"], + }; +} + +/** Test server metrics configuration */ +export interface TestServerMetricConfig { + /** Test identifier */ + readonly testId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testServerMetricConfigSerializer( + item: TestServerMetricConfig, +): TestServerMetricConfigRest { + return { + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, + }; +} + +/** + * Associated metric definition for particular metrics of the azure resource ( + * Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). + */ +export interface ResourceMetric { + /** Unique name for metric. */ + readonly id?: string; + /** Azure resource id. */ + resourceId: string; + /** Metric name space. */ + metricNamespace: string; + /** Metric description. */ + displayDescription?: string; + /** The invariant value of metric name */ + name: string; + /** Metric aggregation. */ + aggregation: string; + /** Metric unit. */ + unit?: string; + /** Azure resource type. */ + resourceType: string; +} + +export function resourceMetricSerializer( + item: ResourceMetric, +): ResourceMetricRest { + return { + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; + +/** Load test run model */ +export interface TestRun { + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testRunId: string; + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** Error details if there is any failure in load test run */ + readonly errorDetails?: ErrorDetails[]; + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ + readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Collection of test run artifacts */ + readonly testArtifacts?: TestRunArtifacts; + /** Test result for pass/Fail criteria used during the test run. */ + readonly testResult?: PFTestResult; + /** Number of virtual users, for which test has been run. */ + readonly virtualUsers?: number; + /** Display name of a testRun. */ + displayName?: string; + /** Associated test Id. */ + testId?: string; + /** The test run description. */ + description?: string; + /** The test run status. */ + readonly status?: Status; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test run initiated time. */ + readonly executedDateTime?: Date; + /** Portal url. */ + readonly portalUrl?: string; + /** Test run duration in milliseconds. */ + readonly duration?: number; + /** Subnet ID on which the load test instances should run. */ + readonly subnetId?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunSerializer(item: TestRun): TestRunRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], + }; +} + +/** Error details if there is any failure in load test run */ +export interface ErrorDetails { + /** Error details in case test run was not successfully run. */ + readonly message?: string; +} + +/** Test run statistics. */ +export interface TestRunStatistics { + /** Transaction name. */ + readonly transaction?: string; + /** Sampler count. */ + readonly sampleCount?: number; + /** Error count. */ + readonly errorCount?: number; + /** Error percentage. */ + readonly errorPct?: number; + /** Mean response time. */ + readonly meanResTime?: number; + /** Median response time. */ + readonly medianResTime?: number; + /** Max response time. */ + readonly maxResTime?: number; + /** Minimum response time. */ + readonly minResTime?: number; + /** 90 percentile response time. */ + readonly pct1ResTime?: number; + /** 95 percentile response time. */ + readonly pct2ResTime?: number; + /** 99 percentile response time. */ + readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; + /** Throughput. */ + readonly throughput?: number; + /** Received network bytes. */ + readonly receivedKBytesPerSec?: number; + /** Send network bytes. */ + readonly sentKBytesPerSec?: number; +} + +/** Collection of test run artifacts */ +export interface TestRunArtifacts { + /** The input artifacts for the test run. */ + readonly inputArtifacts?: TestRunInputArtifacts; + /** The output artifacts for the test run. */ + outputArtifacts?: TestRunOutputArtifacts; +} + +/** The input artifacts for the test run. */ +export interface TestRunInputArtifacts { + /** File info */ + configFileInfo?: TestRunFileInfo; + /** File info */ + testScriptFileInfo?: TestRunFileInfo; + /** File info */ + userPropFileInfo?: TestRunFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +/** The output artifacts for the test run. */ +export interface TestRunOutputArtifacts { + /** File info */ + resultFileInfo?: TestRunFileInfo; + /** File info */ + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Test run status. */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; +/** Request data collection level for test run */ +export type RequestDataLevel = "NONE" | "ERRORS"; + +/** Test run app component */ +export interface TestRunAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test run identifier */ + readonly testRunId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunAppComponentsSerializer( + item: TestRunAppComponents, +): TestRunAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** Test run server metrics configuration */ +export interface TestRunServerMetricConfig { + /** Test run identifier */ + readonly testRunId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics?: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunServerMetricConfigSerializer( + item: TestRunServerMetricConfig, +): TestRunServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + +/** Time Grain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + +/** Metrics dimension values. */ +export interface DimensionValueList { + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; +} + +/** Represents collection of metric definitions. */ +export interface MetricDefinitionCollection { + /** the values for the metric definitions. */ + value: MetricDefinition[]; +} + +/** Metric definition */ +export interface MetricDefinition { + /** List of dimensions */ + dimensions?: NameAndDesc[]; + /** The metric description */ + description?: string; + /** The metric name */ + name?: string; + /** The namespace the metric belongs to. */ + namespace?: string; + /** The primary aggregation type value defining how to use the values for display. */ + primaryAggregationType?: AggregationType; + /** The collection of what all aggregation types are supported. */ + supportedAggregationTypes?: string[]; + /** The unit of the metric. */ + unit?: MetricUnit; + /** + * Metric availability specifies the time grain (aggregation interval or + * frequency). + */ + metricAvailabilities?: MetricAvailability[]; +} + +/** The name and description */ +export interface NameAndDesc { + /** The description */ + description?: string; + /** The name */ + name?: string; +} + +/** Aggregation type. */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile75" + | "Percentile90" + | "Percentile95" + | "Percentile96" + | "Percentile97" + | "Percentile98" + | "Percentile99" + | "Percentile999" + | "Percentile9999"; +/** Metric unit. */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; + +/** Metric availability specifies the time grain (aggregation interval or frequency) */ +export interface MetricAvailability { + /** + * The time grain specifies the aggregation interval for the metric. Expressed as + * a duration 'PT1M', 'PT1H', etc. + */ + timeGrain?: TimeGrain; +} + +/** Represents collection of metric namespaces. */ +export interface MetricNamespaceCollection { + /** The values for the metric namespaces. */ + value: MetricNamespace[]; +} + +/** Metric namespace class specifies the metadata for a metric namespace. */ +export interface MetricNamespace { + /** The namespace description. */ + description?: string; + /** The metric namespace name. */ + name?: string; +} + +/** Filters to fetch the set of metric. */ +export interface MetricRequestPayload { + /** + * Get metrics for specific dimension values. Example: Metric contains dimension + * like SamplerName, Error. To retrieve all the time series data where SamplerName + * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be + * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} + */ + filters?: DimensionFilter[]; +} + +export function metricRequestPayloadSerializer( + item: MetricRequestPayload, +): MetricRequestPayloadRest { + return { + filters: + item["filters"] === undefined + ? item["filters"] + : item["filters"].map(dimensionFilterSerializer), + }; +} + +/** Dimension name and values to filter */ +export interface DimensionFilter { + /** The dimension name */ + name?: string; + /** The dimension values. Maximum values can be 20. */ + values?: string[]; +} + +export function dimensionFilterSerializer( + item: DimensionFilter, +): DimensionFilterRest { + return { + name: item["name"], + values: item["values"], + }; +} + +/** The response to a metrics query. */ +export interface _Metrics { + /** The TimeSeriesElement items on this page */ + value: TimeSeriesElement[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** The time series returned when a data query is performed. */ +export interface TimeSeriesElement { + /** An array of data points representing the metric values. */ + data?: MetricValue[]; + /** The dimension values */ + dimensionValues?: DimensionValue[]; +} + +/** Represents a metric value. */ +export interface MetricValue { + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; + /** The metric value. */ + value?: number; +} + +/** Represents a metric dimension value. */ +export interface DimensionValue { + /** The name of the dimension. */ + name?: string; + /** The value of the dimension. */ + value?: string; +} + +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Kind of the resource on which test profile is created. */ +export type ResourceKind = "FunctionsFlexConsumption"; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Test profile run status. */ +export type TestProfileRunStatus = + | "ACCEPTED" + | "NOTSTARTED" + | "EXECUTING" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED"; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Category of Recommendation. */ +export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ +export interface _PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/options.ts new file mode 100644 index 0000000000..cd1ee9166e --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/options.ts @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +/** Optional parameters. */ +export interface CreateOrUpdateTestProfileOptionalParams + extends OperationOptions { + /** This request has a JSON Merge Patch body. */ + contentType?: string; +} + +/** Optional parameters. */ +export interface DeleteTestProfileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface GetTestProfileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface ListTestProfilesOptionalParams extends OperationOptions { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedStartTime?: Date; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedEndTime?: Date; + /** Comma separated list of IDs of the test profiles to filter. */ + testProfileIds?: string; + /** Comma separated list IDs of the tests which should be associated with the test profiles to fetch. */ + testIds?: string; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/pagingTypes.ts new file mode 100644 index 0000000000..f734b48e62 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/pagingTypes.ts @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** + * Options for the byPage method + */ +export interface PageSettings { + /** + * A reference to a specific page to start iterating from. + */ + continuationToken?: string; +} + +/** + * An interface that describes a page of results. + */ +export type ContinuablePage = TPage & { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +}; + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; +} + +/** + * An interface that describes how to communicate with the service. + */ +export interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * Link to the first page of results. + */ + firstPageLink?: string; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink?: string, + ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => TElement[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts new file mode 100644 index 0000000000..f77231f925 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { TokenCredential } from "@azure/core-auth"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TestProfile } from "./models/models.js"; +import { + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, +} from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; +import { + createOrUpdateTestProfile, + deleteTestProfile, + getTestProfile, + listTestProfiles, + createTestProfileAdministrationOperations, + TestProfileAdministrationOperationsClientOptions, + LoadTestServiceContext, +} from "./api/index.js"; + +export { TestProfileAdministrationOperationsClientOptions } from "./api/testProfileAdministrationOperationsContext.js"; + +export class TestProfileAdministrationOperationsClient { + private _client: LoadTestServiceContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + constructor( + endpointParam: string, + credential: TokenCredential, + options: TestProfileAdministrationOperationsClientOptions = {}, + ) { + this._client = createTestProfileAdministrationOperations( + endpointParam, + credential, + options, + ); + this.pipeline = this._client.pipeline; + } + + /** Create a new test profile or update an existing test profile by providing the test profile Id. */ + createOrUpdateTestProfile( + testProfileId: string, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTestProfile( + this._client, + testProfileId, + body, + options, + ); + } + + /** Delete a test profile by its test profile Id. */ + deleteTestProfile( + testProfileId: string, + options: DeleteTestProfileOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTestProfile(this._client, testProfileId, options); + } + + /** Get load test profile details by test profile Id. */ + getTestProfile( + testProfileId: string, + options: GetTestProfileOptionalParams = { requestOptions: {} }, + ): Promise { + return getTestProfile(this._client, testProfileId, options); + } + + /** Get all test profiles for the given filters. */ + listTestProfiles( + options: ListTestProfilesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestProfiles(this._client, options); + } +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts new file mode 100644 index 0000000000..5acd70fe5d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createOrUpdateTestProfileRun, + deleteTestProfileRun, + getTestProfileRun, + listTestProfileRuns, + stop, +} from "./operations.js"; +export { + createTestProfileRunOperations, + TestProfileRunOperationsClientOptions, + LoadTestServiceContext, +} from "./testProfileRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts new file mode 100644 index 0000000000..2fccd67a52 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts @@ -0,0 +1,433 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + RecommendationCategory, + _PagedTestProfileRun, +} from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; +import { + isUnexpected, + LoadTestServiceContext as Client, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, + TestProfileRunAdministrationDeleteTestProfileRun204Response, + TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, + TestProfileRunAdministrationGetTestProfileRun200Response, + TestProfileRunAdministrationGetTestProfileRunDefaultResponse, + TestProfileRunAdministrationListTestProfileRuns200Response, + TestProfileRunAdministrationListTestProfileRunsDefaultResponse, + TestProfileRunAdministrationStop200Response, + TestProfileRunAdministrationStopDefaultResponse, +} from "../../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, + createRestError, +} from "@azure-rest/core-client"; +import { + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams, +} from "../models/options.js"; + +export function _createOrUpdateTestProfileRunSend( + context: Client, + testProfileRunId: string, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse +> { + return context + .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/merge-patch+json", + body: { + displayName: body["displayName"], + description: body["description"], + testProfileId: body["testProfileId"], + }, + }); +} + +export async function _createOrUpdateTestProfileRunDeserialize( + result: + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + testProfileRunId: result.body["testProfileRunId"], + displayName: result.body["displayName"], + description: result.body["description"], + testProfileId: result.body["testProfileId"], + targetResourceId: result.body["targetResourceId"], + targetResourceConfigurations: !result.body.targetResourceConfigurations + ? undefined + : { + kind: result.body.targetResourceConfigurations?.[ + "kind" + ] as ResourceKind, + }, + status: result.body["status"] as TestProfileRunStatus, + errorDetails: + result.body["errorDetails"] === undefined + ? result.body["errorDetails"] + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + durationInSeconds: result.body["durationInSeconds"], + testRunDetails: result.body["testRunDetails"], + recommendations: + result.body["recommendations"] === undefined + ? result.body["recommendations"] + : result.body["recommendations"].map((p) => ({ + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + })), + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, + createdBy: result.body["createdBy"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: result.body["lastModifiedBy"], + }; +} + +/** Create and start a new test profile run with the given test profile run Id. */ +export async function createOrUpdateTestProfileRun( + context: Client, + testProfileRunId: string, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestProfileRunSend( + context, + testProfileRunId, + body, + options, + ); + return _createOrUpdateTestProfileRunDeserialize(result); +} + +export function _deleteTestProfileRunSend( + context: Client, + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse +> { + return context + .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) + .delete({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _deleteTestProfileRunDeserialize( + result: + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return; +} + +/** Delete an existing load test profile run by providing the test profile run Id. */ +export async function deleteTestProfileRun( + context: Client, + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestProfileRunSend( + context, + testProfileRunId, + options, + ); + return _deleteTestProfileRunDeserialize(result); +} + +export function _getTestProfileRunSend( + context: Client, + testProfileRunId: string, + options: GetTestProfileRunOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse +> { + return context + .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getTestProfileRunDeserialize( + result: + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + testProfileRunId: result.body["testProfileRunId"], + displayName: result.body["displayName"], + description: result.body["description"], + testProfileId: result.body["testProfileId"], + targetResourceId: result.body["targetResourceId"], + targetResourceConfigurations: !result.body.targetResourceConfigurations + ? undefined + : { + kind: result.body.targetResourceConfigurations?.[ + "kind" + ] as ResourceKind, + }, + status: result.body["status"] as TestProfileRunStatus, + errorDetails: + result.body["errorDetails"] === undefined + ? result.body["errorDetails"] + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + durationInSeconds: result.body["durationInSeconds"], + testRunDetails: result.body["testRunDetails"], + recommendations: + result.body["recommendations"] === undefined + ? result.body["recommendations"] + : result.body["recommendations"].map((p) => ({ + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + })), + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, + createdBy: result.body["createdBy"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: result.body["lastModifiedBy"], + }; +} + +/** Get test profile run details by test profile run Id. */ +export async function getTestProfileRun( + context: Client, + testProfileRunId: string, + options: GetTestProfileRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTestProfileRunSend( + context, + testProfileRunId, + options, + ); + return _getTestProfileRunDeserialize(result); +} + +export function _listTestProfileRunsSend( + context: Client, + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse +> { + return context + .path("/test-profile-runs") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxpagesize: options?.maxpagesize, + minStartDateTime: options?.minStartDateTime?.toISOString(), + maxStartDateTime: options?.maxStartDateTime?.toISOString(), + minEndDateTime: options?.minEndDateTime?.toISOString(), + maxEndDateTime: options?.maxEndDateTime?.toISOString(), + createdDateStartTime: options?.createdDateStartTime?.toISOString(), + createdDateEndTime: options?.createdDateEndTime?.toISOString(), + testProfileRunIds: options?.testProfileRunIds, + testProfileIds: options?.testProfileIds, + statuses: options?.statuses, + }, + }); +} + +export async function _listTestProfileRunsDeserialize( + result: + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, +): Promise<_PagedTestProfileRun> { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + value: result.body["value"].map((p) => ({ + testProfileRunId: p["testProfileRunId"], + displayName: p["displayName"], + description: p["description"], + testProfileId: p["testProfileId"], + targetResourceId: p["targetResourceId"], + targetResourceConfigurations: !p.targetResourceConfigurations + ? undefined + : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, + status: p["status"] as TestProfileRunStatus, + errorDetails: + p["errorDetails"] === undefined + ? p["errorDetails"] + : p["errorDetails"].map((p) => ({ message: p["message"] })), + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, + durationInSeconds: p["durationInSeconds"], + testRunDetails: p["testRunDetails"], + recommendations: + p["recommendations"] === undefined + ? p["recommendations"] + : p["recommendations"].map((p) => ({ + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + })), + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + })), + nextLink: result.body["nextLink"], + }; +} + +/** Get all test profile runs for the given filters. */ +export function listTestProfileRuns( + context: Client, + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTestProfileRunsSend(context, options), + _listTestProfileRunsDeserialize, + { itemName: "value", nextLinkName: "nextLink" }, + ); +} + +export function _stopSend( + context: Client, + testProfileRunId: string, + options: StopOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse +> { + return context + .path("/test-profile-runs/{testProfileRunId}:stop", testProfileRunId) + .post({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _stopDeserialize( + result: + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + testProfileRunId: result.body["testProfileRunId"], + displayName: result.body["displayName"], + description: result.body["description"], + testProfileId: result.body["testProfileId"], + targetResourceId: result.body["targetResourceId"], + targetResourceConfigurations: !result.body.targetResourceConfigurations + ? undefined + : { + kind: result.body.targetResourceConfigurations?.[ + "kind" + ] as ResourceKind, + }, + status: result.body["status"] as TestProfileRunStatus, + errorDetails: + result.body["errorDetails"] === undefined + ? result.body["errorDetails"] + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + durationInSeconds: result.body["durationInSeconds"], + testRunDetails: result.body["testRunDetails"], + recommendations: + result.body["recommendations"] === undefined + ? result.body["recommendations"] + : result.body["recommendations"].map((p) => ({ + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + })), + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, + createdBy: result.body["createdBy"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: result.body["lastModifiedBy"], + }; +} + +/** Stop test profile run for the given test profile run Id. */ +export async function stop( + context: Client, + testProfileRunId: string, + options: StopOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _stopSend(context, testProfileRunId, options); + return _stopDeserialize(result); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/pagingHelpers.ts new file mode 100644 index 0000000000..754f1e613b --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/pagingHelpers.ts @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; +import { + BuildPagedAsyncIteratorOptions, + ContinuablePage, + PageSettings, + PagedAsyncIterableIterator, + PagedResult, +} from "../models/pagingTypes.js"; +import { isUnexpected } from "../../rest/index.js"; + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => PromiseLike, + options: BuildPagedAsyncIteratorOptions = {}, +): PagedAsyncIterableIterator { + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; + const pagedResult: PagedResult = { + getPage: async (pageLink?: string) => { + const result = + pageLink === undefined + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + checkPagingRequest(result); + const results = await processResponseBody(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName) as TPage; + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }, + }; + return getPagedAsyncIterator(pagedResult); +} + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ + +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {}, +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { + throw new RestError( + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, + ); + } + + if (nextLink === null) { + return undefined; + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + if (!Array.isArray(value)) { + throw new RestError( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + if (isUnexpected(response)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts new file mode 100644 index 0000000000..40b15e8933 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { TokenCredential } from "@azure/core-auth"; +import { ClientOptions } from "@azure-rest/core-client"; +import { LoadTestServiceContext } from "../../rest/index.js"; +import getClient from "../../rest/index.js"; + +/** Optional parameters for the client. */ +export interface TestProfileRunOperationsClientOptions extends ClientOptions { + /** The API version to use for this operation. */ + apiVersion?: string; +} + +export { LoadTestServiceContext } from "../../rest/index.js"; + +export function createTestProfileRunOperations( + endpointParam: string, + credential: TokenCredential, + options: TestProfileRunOperationsClientOptions = {}, +): LoadTestServiceContext { + const clientContext = getClient(endpointParam, credential, options); + return clientContext; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts new file mode 100644 index 0000000000..1e4d04259a --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + TestProfileRunOperationsClient, + TestProfileRunOperationsClientOptions, +} from "./testProfileRunOperationsClient.js"; +export { + Test, + PassFailCriteria, + PassFailMetric, + PFMetrics, + PFAgFunc, + PFAction, + PFResult, + AutoStopCriteria, + Secret, + SecretType, + CertificateMetadata, + CertificateType, + LoadTestConfiguration, + OptionalLoadTestConfig, + RegionalConfiguration, + TestInputArtifacts, + TestFileInfo, + FileType, + FileStatus, + TestKind, + TestAppComponents, + AppComponent, + TestServerMetricConfig, + ResourceMetric, + APIVersions, + TestRun, + ErrorDetails, + TestRunStatistics, + TestRunArtifacts, + TestRunInputArtifacts, + TestRunFileInfo, + TestRunOutputArtifacts, + ArtifactsContainerInfo, + PFTestResult, + Status, + RequestDataLevel, + TestRunAppComponents, + TestRunServerMetricConfig, + TimeGrain, + DimensionValueList, + MetricDefinitionCollection, + MetricDefinition, + NameAndDesc, + AggregationType, + MetricUnit, + MetricAvailability, + MetricNamespaceCollection, + MetricNamespace, + MetricRequestPayload, + DimensionFilter, + TimeSeriesElement, + MetricValue, + DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams, + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts new file mode 100644 index 0000000000..9b0e075fff --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + Test, + PassFailCriteria, + PassFailMetric, + PFMetrics, + PFAgFunc, + PFAction, + PFResult, + AutoStopCriteria, + Secret, + SecretType, + CertificateMetadata, + CertificateType, + LoadTestConfiguration, + OptionalLoadTestConfig, + RegionalConfiguration, + TestInputArtifacts, + TestFileInfo, + FileType, + FileStatus, + TestKind, + TestAppComponents, + AppComponent, + TestServerMetricConfig, + ResourceMetric, + APIVersions, + TestRun, + ErrorDetails, + TestRunStatistics, + TestRunArtifacts, + TestRunInputArtifacts, + TestRunFileInfo, + TestRunOutputArtifacts, + ArtifactsContainerInfo, + PFTestResult, + Status, + RequestDataLevel, + TestRunAppComponents, + TestRunServerMetricConfig, + TimeGrain, + DimensionValueList, + MetricDefinitionCollection, + MetricDefinition, + NameAndDesc, + AggregationType, + MetricUnit, + MetricAvailability, + MetricNamespaceCollection, + MetricNamespace, + MetricRequestPayload, + DimensionFilter, + TimeSeriesElement, + MetricValue, + DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, +} from "./models.js"; +export { + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams, +} from "./options.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts new file mode 100644 index 0000000000..31dd6af57e --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts @@ -0,0 +1,1244 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { serializeRecord } from "../../helpers/serializerHelpers.js"; +import { + Test as TestRest, + PassFailCriteria as PassFailCriteriaRest, + PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, + Secret as SecretRest, + CertificateMetadata as CertificateMetadataRest, + LoadTestConfiguration as LoadTestConfigurationRest, + OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, + TestAppComponents as TestAppComponentsRest, + AppComponent as AppComponentRest, + TestServerMetricConfig as TestServerMetricConfigRest, + ResourceMetric as ResourceMetricRest, + TestRun as TestRunRest, + TestRunAppComponents as TestRunAppComponentsRest, + TestRunServerMetricConfig as TestRunServerMetricConfigRest, + MetricRequestPayload as MetricRequestPayloadRest, + DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, +} from "../../rest/index.js"; + +/** Load test model. */ +export interface Test { + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata. */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; + /** The input artifacts for the test. */ + readonly inputArtifacts?: TestInputArtifacts; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; + /** The test description. */ + description?: string; + /** Display name of a test. */ + displayName?: string; + /** Subnet ID on which the load test instances should run. */ + subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; + /** Type of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityType?: string; + /** Resource Id of the managed identity referencing the Key vault. */ + keyvaultReferenceIdentityId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testSerializer(item: Test): TestRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], + description: item["description"], + displayName: item["displayName"], + subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], + keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], + }; +} + +/** Pass fail criteria for a test. */ +export interface PassFailCriteria { + /** Map of id and pass fail metrics { id : pass fail metrics }. */ + passFailMetrics?: Record; +} + +export function passFailCriteriaSerializer( + item: PassFailCriteria, +): PassFailCriteriaRest { + return { + passFailMetrics: !item.passFailMetrics + ? item.passFailMetrics + : (serializeRecord( + item.passFailMetrics as any, + passFailMetricSerializer, + ) as any), + }; +} + +/** Pass fail metric */ +export interface PassFailMetric { + /** The client metric on which the criteria should be applied. */ + clientMetric?: PFMetrics; + /** + * The aggregation function to be applied on the client metric. Allowed functions + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, + * ‘count’ - for requests + */ + aggregate?: PFAgFunc; + /** The comparison operator. Supported types ‘>’, ‘<’ */ + condition?: string; + /** Request name for which the Pass fail criteria has to be applied */ + requestName?: string; + /** + * The value to compare with the client metric. Allowed values - ‘error : [0.0 , + * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + */ + value?: number; + /** Action taken after the threshold is met. Default is ‘continue’. */ + action?: PFAction; + /** The actual value of the client metric for the test run. */ + readonly actualValue?: number; + /** Outcome of the test run. */ + readonly result?: PFResult; +} + +export function passFailMetricSerializer( + item: PassFailMetric, +): PassFailMetricRest { + return { + clientMetric: item["clientMetric"], + aggregate: item["aggregate"], + condition: item["condition"], + requestName: item["requestName"], + value: item["value"], + action: item["action"], + }; +} + +/** Metrics for pass/fail criteria. */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Aggregation functions for pass/fail criteria. */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p75" + | "p90" + | "p95" + | "p96" + | "p97" + | "p98" + | "p99" + | "p99.9" + | "p99.99" + | "min" + | "max"; +/** Action to take on failure of pass/fail criteria. */ +export type PFAction = "continue" | "stop"; +/** Pass/fail criteria result. */ +export type PFResult = "passed" | "undetermined" | "failed"; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + +/** Secret */ +export interface Secret { + /** The value of the secret for the respective type */ + value?: string; + /** Type of secret */ + type?: SecretType; +} + +export function secretSerializer(item: Secret): SecretRest { + return { + value: item["value"], + type: item["type"], + }; +} + +/** Types of secrets supported. */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; + +/** Certificates metadata */ +export interface CertificateMetadata { + /** The value of the certificate for respective type */ + value?: string; + /** Type of certificate */ + type?: CertificateType; + /** Name of the certificate. */ + name?: string; +} + +export function certificateMetadataSerializer( + item: CertificateMetadata, +): CertificateMetadataRest { + return { + value: item["value"], + type: item["type"], + name: item["name"], + }; +} + +/** Types of certificates supported. */ +export type CertificateType = "AKV_CERT_URI"; + +/** Configurations for the load test. */ +export interface LoadTestConfiguration { + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + engineInstances?: number; + /** + * If false, Azure Load Testing copies and processes your input files unmodified + * across all test engine instances. If true, Azure Load Testing splits the CSV + * input data evenly across all engine instances. If you provide multiple CSV + * files, each file will be split evenly. + */ + splitAllCSVs?: boolean; + /** + * If true, optionalLoadTestConfig is required and JMX script for the load test is + * not required to upload. + */ + quickStartTest?: boolean; + /** Configuration for quick load test */ + optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; +} + +export function loadTestConfigurationSerializer( + item: LoadTestConfiguration, +): LoadTestConfigurationRest { + return { + engineInstances: item["engineInstances"], + splitAllCSVs: item["splitAllCSVs"], + quickStartTest: item["quickStartTest"], + optionalLoadTestConfig: !item.optionalLoadTestConfig + ? item.optionalLoadTestConfig + : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), + }; +} + +/** Configuration for quick load test */ +export interface OptionalLoadTestConfig { + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + endpointUrl?: string; + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ + virtualUsers?: number; + /** Ramp up time in seconds. */ + rampUpTime?: number; + /** Test run duration in seconds. */ + duration?: number; +} + +export function optionalLoadTestConfigSerializer( + item: OptionalLoadTestConfig, +): OptionalLoadTestConfigRest { + return { + endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], + virtualUsers: item["virtualUsers"], + rampUpTime: item["rampUpTime"], + duration: item["duration"], + }; +} + +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + +/** The input artifacts for the test. */ +export interface TestInputArtifacts { + /** File info */ + configFileInfo?: TestFileInfo; + /** File info */ + testScriptFileInfo?: TestFileInfo; + /** File info */ + userPropFileInfo?: TestFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestFileInfo[]; +} + +/** Test file info. */ +export interface TestFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +/** Types of file supported. */ +export type FileType = + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG" + | "TEST_SCRIPT"; +/** File status. */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; +/** Test kind */ +export type TestKind = "URL" | "JMX" | "Locust"; + +/** Test app components */ +export interface TestAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test identifier */ + readonly testId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testAppComponentsSerializer( + item: TestAppComponents, +): TestAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +export interface AppComponent { + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; + /** Azure resource name, required while creating the app component. */ + resourceName: string; + /** Azure resource type, required while creating the app component. */ + resourceType: string; + /** Azure resource display name */ + displayName?: string; + /** Resource group name of the Azure resource */ + readonly resourceGroup?: string; + /** Subscription Id of the Azure resource */ + readonly subscriptionId?: string; + /** Kind of Azure resource type */ + kind?: string; +} + +export function appComponentSerializer(item: AppComponent): AppComponentRest { + return { + resourceName: item["resourceName"], + resourceType: item["resourceType"], + displayName: item["displayName"], + kind: item["kind"], + }; +} + +/** Test server metrics configuration */ +export interface TestServerMetricConfig { + /** Test identifier */ + readonly testId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testServerMetricConfigSerializer( + item: TestServerMetricConfig, +): TestServerMetricConfigRest { + return { + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, + }; +} + +/** + * Associated metric definition for particular metrics of the azure resource ( + * Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). + */ +export interface ResourceMetric { + /** Unique name for metric. */ + readonly id?: string; + /** Azure resource id. */ + resourceId: string; + /** Metric name space. */ + metricNamespace: string; + /** Metric description. */ + displayDescription?: string; + /** The invariant value of metric name */ + name: string; + /** Metric aggregation. */ + aggregation: string; + /** Metric unit. */ + unit?: string; + /** Azure resource type. */ + resourceType: string; +} + +export function resourceMetricSerializer( + item: ResourceMetric, +): ResourceMetricRest { + return { + resourceId: item["resourceId"], + metricNamespace: item["metricNamespace"], + displayDescription: item["displayDescription"], + name: item["name"], + aggregation: item["aggregation"], + unit: item["unit"], + resourceType: item["resourceType"], + }; +} + +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; + +/** Load test run model */ +export interface TestRun { + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testRunId: string; + /** Pass fail criteria for a test. */ + passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; + /** + * Secrets can be stored in an Azure Key Vault or any other secret store. If the + * secret is stored in an Azure Key Vault, the value should be the secret + * identifier and the type should be AKV_SECRET_URI. If the secret is stored + * elsewhere, the secret value should be provided directly and the type should be + * SECRET_VALUE. + */ + secrets?: Record; + /** Certificates metadata */ + certificate?: CertificateMetadata; + /** Environment variables which are defined as a set of pairs. */ + environmentVariables?: Record; + /** Error details if there is any failure in load test run */ + readonly errorDetails?: ErrorDetails[]; + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ + readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; + /** The load test configuration. */ + loadTestConfiguration?: LoadTestConfiguration; + /** Collection of test run artifacts */ + readonly testArtifacts?: TestRunArtifacts; + /** Test result for pass/Fail criteria used during the test run. */ + readonly testResult?: PFTestResult; + /** Number of virtual users, for which test has been run. */ + readonly virtualUsers?: number; + /** Display name of a testRun. */ + displayName?: string; + /** Associated test Id. */ + testId?: string; + /** The test run description. */ + description?: string; + /** The test run status. */ + readonly status?: Status; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test run initiated time. */ + readonly executedDateTime?: Date; + /** Portal url. */ + readonly portalUrl?: string; + /** Test run duration in milliseconds. */ + readonly duration?: number; + /** Subnet ID on which the load test instances should run. */ + readonly subnetId?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunSerializer(item: TestRun): TestRunRest { + return { + passFailCriteria: !item.passFailCriteria + ? item.passFailCriteria + : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), + secrets: !item.secrets + ? item.secrets + : (serializeRecord(item.secrets as any, secretSerializer) as any), + certificate: !item.certificate + ? item.certificate + : certificateMetadataSerializer(item.certificate), + environmentVariables: !item.environmentVariables + ? item.environmentVariables + : (serializeRecord(item.environmentVariables as any) as any), + loadTestConfiguration: !item.loadTestConfiguration + ? item.loadTestConfiguration + : loadTestConfigurationSerializer(item.loadTestConfiguration), + displayName: item["displayName"], + testId: item["testId"], + description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], + }; +} + +/** Error details if there is any failure in load test run */ +export interface ErrorDetails { + /** Error details in case test run was not successfully run. */ + readonly message?: string; +} + +/** Test run statistics. */ +export interface TestRunStatistics { + /** Transaction name. */ + readonly transaction?: string; + /** Sampler count. */ + readonly sampleCount?: number; + /** Error count. */ + readonly errorCount?: number; + /** Error percentage. */ + readonly errorPct?: number; + /** Mean response time. */ + readonly meanResTime?: number; + /** Median response time. */ + readonly medianResTime?: number; + /** Max response time. */ + readonly maxResTime?: number; + /** Minimum response time. */ + readonly minResTime?: number; + /** 90 percentile response time. */ + readonly pct1ResTime?: number; + /** 95 percentile response time. */ + readonly pct2ResTime?: number; + /** 99 percentile response time. */ + readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; + /** Throughput. */ + readonly throughput?: number; + /** Received network bytes. */ + readonly receivedKBytesPerSec?: number; + /** Send network bytes. */ + readonly sentKBytesPerSec?: number; +} + +/** Collection of test run artifacts */ +export interface TestRunArtifacts { + /** The input artifacts for the test run. */ + readonly inputArtifacts?: TestRunInputArtifacts; + /** The output artifacts for the test run. */ + outputArtifacts?: TestRunOutputArtifacts; +} + +/** The input artifacts for the test run. */ +export interface TestRunInputArtifacts { + /** File info */ + configFileInfo?: TestRunFileInfo; + /** File info */ + testScriptFileInfo?: TestRunFileInfo; + /** File info */ + userPropFileInfo?: TestRunFileInfo; + /** File info */ + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; + /** Additional supported files for the test run */ + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; +} + +/** The output artifacts for the test run. */ +export interface TestRunOutputArtifacts { + /** File info */ + resultFileInfo?: TestRunFileInfo; + /** File info */ + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Test run status. */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; +/** Request data collection level for test run */ +export type RequestDataLevel = "NONE" | "ERRORS"; + +/** Test run app component */ +export interface TestRunAppComponents { + /** + * Azure resource collection { resource id (fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + * : resource object } + */ + components: Record; + /** Test run identifier */ + readonly testRunId?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunAppComponentsSerializer( + item: TestRunAppComponents, +): TestRunAppComponentsRest { + return { + components: serializeRecord( + item.components as any, + appComponentSerializer, + ) as any, + }; +} + +/** Test run server metrics configuration */ +export interface TestRunServerMetricConfig { + /** Test run identifier */ + readonly testRunId?: string; + /** + * Azure resource metrics collection {metric id : metrics object} (Refer : + * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + * for metric id). + */ + metrics?: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testRunServerMetricConfigSerializer( + item: TestRunServerMetricConfig, +): TestRunServerMetricConfigRest { + return { + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + }; +} + +/** Time Grain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + +/** Metrics dimension values. */ +export interface DimensionValueList { + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; +} + +/** Represents collection of metric definitions. */ +export interface MetricDefinitionCollection { + /** the values for the metric definitions. */ + value: MetricDefinition[]; +} + +/** Metric definition */ +export interface MetricDefinition { + /** List of dimensions */ + dimensions?: NameAndDesc[]; + /** The metric description */ + description?: string; + /** The metric name */ + name?: string; + /** The namespace the metric belongs to. */ + namespace?: string; + /** The primary aggregation type value defining how to use the values for display. */ + primaryAggregationType?: AggregationType; + /** The collection of what all aggregation types are supported. */ + supportedAggregationTypes?: string[]; + /** The unit of the metric. */ + unit?: MetricUnit; + /** + * Metric availability specifies the time grain (aggregation interval or + * frequency). + */ + metricAvailabilities?: MetricAvailability[]; +} + +/** The name and description */ +export interface NameAndDesc { + /** The description */ + description?: string; + /** The name */ + name?: string; +} + +/** Aggregation type. */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile75" + | "Percentile90" + | "Percentile95" + | "Percentile96" + | "Percentile97" + | "Percentile98" + | "Percentile99" + | "Percentile999" + | "Percentile9999"; +/** Metric unit. */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; + +/** Metric availability specifies the time grain (aggregation interval or frequency) */ +export interface MetricAvailability { + /** + * The time grain specifies the aggregation interval for the metric. Expressed as + * a duration 'PT1M', 'PT1H', etc. + */ + timeGrain?: TimeGrain; +} + +/** Represents collection of metric namespaces. */ +export interface MetricNamespaceCollection { + /** The values for the metric namespaces. */ + value: MetricNamespace[]; +} + +/** Metric namespace class specifies the metadata for a metric namespace. */ +export interface MetricNamespace { + /** The namespace description. */ + description?: string; + /** The metric namespace name. */ + name?: string; +} + +/** Filters to fetch the set of metric. */ +export interface MetricRequestPayload { + /** + * Get metrics for specific dimension values. Example: Metric contains dimension + * like SamplerName, Error. To retrieve all the time series data where SamplerName + * is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be + * {"SamplerName", ["HTTPRequest1", "HTTPRequest2"} + */ + filters?: DimensionFilter[]; +} + +export function metricRequestPayloadSerializer( + item: MetricRequestPayload, +): MetricRequestPayloadRest { + return { + filters: + item["filters"] === undefined + ? item["filters"] + : item["filters"].map(dimensionFilterSerializer), + }; +} + +/** Dimension name and values to filter */ +export interface DimensionFilter { + /** The dimension name */ + name?: string; + /** The dimension values. Maximum values can be 20. */ + values?: string[]; +} + +export function dimensionFilterSerializer( + item: DimensionFilter, +): DimensionFilterRest { + return { + name: item["name"], + values: item["values"], + }; +} + +/** The response to a metrics query. */ +export interface _Metrics { + /** The TimeSeriesElement items on this page */ + value: TimeSeriesElement[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** The time series returned when a data query is performed. */ +export interface TimeSeriesElement { + /** An array of data points representing the metric values. */ + data?: MetricValue[]; + /** The dimension values */ + dimensionValues?: DimensionValue[]; +} + +/** Represents a metric value. */ +export interface MetricValue { + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; + /** The metric value. */ + value?: number; +} + +/** Represents a metric dimension value. */ +export interface DimensionValue { + /** The name of the dimension. */ + name?: string; + /** The value of the dimension. */ + value?: string; +} + +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Kind of the resource on which test profile is created. */ +export type ResourceKind = "FunctionsFlexConsumption"; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Test profile run status. */ +export type TestProfileRunStatus = + | "ACCEPTED" + | "NOTSTARTED" + | "EXECUTING" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED"; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Category of Recommendation. */ +export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ +export interface _PagedTestRun { + /** The TestRun items on this page */ + value: TestRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts new file mode 100644 index 0000000000..998363629b --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +/** Optional parameters. */ +export interface CreateOrUpdateTestProfileRunOptionalParams + extends OperationOptions { + /** This request has a JSON Merge Patch body. */ + contentType?: string; +} + +/** Optional parameters. */ +export interface DeleteTestProfileRunOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface GetTestProfileRunOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface ListTestProfileRunsOptionalParams extends OperationOptions { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Minimum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minStartDateTime?: Date; + /** Maximum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxStartDateTime?: Date; + /** Minimum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minEndDateTime?: Date; + /** Maximum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxEndDateTime?: Date; + /** Start DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateStartTime?: Date; + /** End DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateEndTime?: Date; + /** Comma separated list of IDs of the test profile runs to filter. */ + testProfileRunIds?: string; + /** Comma separated IDs of the test profiles which should be associated with the test profile runs to fetch. */ + testProfileIds?: string; + /** Comma separated list of Statuses of the test profile runs to filter. */ + statuses?: string; +} + +/** Optional parameters. */ +export interface StopOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/pagingTypes.ts new file mode 100644 index 0000000000..f734b48e62 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/pagingTypes.ts @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** + * Options for the byPage method + */ +export interface PageSettings { + /** + * A reference to a specific page to start iterating from. + */ + continuationToken?: string; +} + +/** + * An interface that describes a page of results. + */ +export type ContinuablePage = TPage & { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +}; + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; +} + +/** + * An interface that describes how to communicate with the service. + */ +export interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * Link to the first page of results. + */ + firstPageLink?: string; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink?: string, + ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => TElement[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts new file mode 100644 index 0000000000..686d77063c --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { TokenCredential } from "@azure/core-auth"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TestProfileRun } from "./models/models.js"; +import { + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams, +} from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; +import { + createOrUpdateTestProfileRun, + deleteTestProfileRun, + getTestProfileRun, + listTestProfileRuns, + stop, + createTestProfileRunOperations, + TestProfileRunOperationsClientOptions, + LoadTestServiceContext, +} from "./api/index.js"; + +export { TestProfileRunOperationsClientOptions } from "./api/testProfileRunOperationsContext.js"; + +export class TestProfileRunOperationsClient { + private _client: LoadTestServiceContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + constructor( + endpointParam: string, + credential: TokenCredential, + options: TestProfileRunOperationsClientOptions = {}, + ) { + this._client = createTestProfileRunOperations( + endpointParam, + credential, + options, + ); + this.pipeline = this._client.pipeline; + } + + /** Create and start a new test profile run with the given test profile run Id. */ + createOrUpdateTestProfileRun( + testProfileRunId: string, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { + requestOptions: {}, + }, + ): Promise { + return createOrUpdateTestProfileRun( + this._client, + testProfileRunId, + body, + options, + ); + } + + /** Delete an existing load test profile run by providing the test profile run Id. */ + deleteTestProfileRun( + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTestProfileRun(this._client, testProfileRunId, options); + } + + /** Get test profile run details by test profile run Id. */ + getTestProfileRun( + testProfileRunId: string, + options: GetTestProfileRunOptionalParams = { requestOptions: {} }, + ): Promise { + return getTestProfileRun(this._client, testProfileRunId, options); + } + + /** Get all test profile runs for the given filters. */ + listTestProfileRuns( + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestProfileRuns(this._client, options); + } + + /** Stop test profile run for the given test profile run Id. */ + stop( + testProfileRunId: string, + options: StopOptionalParams = { requestOptions: {} }, + ): Promise { + return stop(this._client, testProfileRunId, options); + } +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index 53a26b11df..8e35dc0cd3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. export { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -15,10 +15,10 @@ export { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, } from "./operations.js"; export { createTestRunOperations, TestRunOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./testRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 4d72bc85cd..57274f20b7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -1,34 +1,40 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { getLongRunningPoller } from "./pollingHelpers.js"; -import { PollerLike, OperationState } from "@azure/core-lro"; import { passFailCriteriaSerializer, + autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, dimensionFilterSerializer, - FileInfo, + CertificateType, + FileType, + FileStatus, + TestKind, TestRun, + PFTestResult, + Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + TimeGrain, DimensionValueList, MetricDefinitionCollection, + AggregationType, + MetricUnit, MetricNamespaceCollection, MetricRequestPayload, TimeSeriesElement, - _PagedDimensionValueList, + _Metrics, _PagedTestRun, - _PagedTimeSeriesElement, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestRunCreateOrUpdateAppComponents200Response, LoadTestRunCreateOrUpdateAppComponents201Response, LoadTestRunCreateOrUpdateAppComponentsDefaultResponse, @@ -38,11 +44,12 @@ import { LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunDeleteTestRun204Response, LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunGetAppComponents200Response, LoadTestRunGetAppComponentsDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, LoadTestRunGetTestRun200Response, LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, @@ -57,10 +64,9 @@ import { LoadTestRunListMetricsDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -69,7 +75,7 @@ import { } from "@azure-rest/core-client"; import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -82,19 +88,18 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "../models/options.js"; -export function _testRunSend( +export function _createOrUpdateTestRunSend( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse > { return context .path("/test-runs/{testRunId}", testRunId) @@ -104,51 +109,62 @@ export function _testRunSend( (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, body: { - passFailCriteria: !resource.passFailCriteria - ? resource.passFailCriteria - : passFailCriteriaSerializer(resource.passFailCriteria), - secrets: !resource.secrets - ? resource.secrets - : (serializeRecord(resource.secrets as any, secretSerializer) as any), - certificate: !resource.certificate - ? resource.certificate - : certificateMetadataSerializer(resource.certificate), - environmentVariables: !resource.environmentVariables - ? resource.environmentVariables - : (serializeRecord(resource.environmentVariables as any) as any), - loadTestConfiguration: !resource.loadTestConfiguration - ? resource.loadTestConfiguration - : loadTestConfigurationSerializer(resource.loadTestConfiguration), - displayName: resource["displayName"], - testId: resource["testId"], - description: resource["description"], + passFailCriteria: !body.passFailCriteria + ? body.passFailCriteria + : passFailCriteriaSerializer(body.passFailCriteria), + autoStopCriteria: !body.autoStopCriteria + ? body.autoStopCriteria + : autoStopCriteriaSerializer(body.autoStopCriteria), + secrets: !body.secrets + ? body.secrets + : (serializeRecord(body.secrets as any, secretSerializer) as any), + certificate: !body.certificate + ? body.certificate + : certificateMetadataSerializer(body.certificate), + environmentVariables: !body.environmentVariables + ? body.environmentVariables + : (serializeRecord(body.environmentVariables as any) as any), + loadTestConfiguration: !body.loadTestConfiguration + ? body.loadTestConfiguration + : loadTestConfigurationSerializer(body.loadTestConfiguration), + displayName: body["displayName"], + testId: body["testId"], + description: body["description"], + requestDataLevel: body["requestDataLevel"], + debugLogsEnabled: body["debugLogsEnabled"], }, }); } -export async function _testRunDeserialize( +export async function _createOrUpdateTestRunDeserialize( result: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse, + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); } - result = result as LoadTestRunCreateOrUpdateTestRunLogicalResponse; return { testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], + type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, environmentVariables: result.body["environmentVariables"], @@ -157,6 +173,7 @@ export async function _testRunDeserialize( ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -172,6 +189,14 @@ export async function _testRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -185,6 +210,16 @@ export async function _testRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + })), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -196,20 +231,25 @@ export async function _testRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -218,20 +258,25 @@ export async function _testRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -240,20 +285,25 @@ export async function _testRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -262,26 +312,60 @@ export async function _testRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"] as FileType, + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -292,11 +376,14 @@ export async function _testRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -307,20 +394,25 @@ export async function _testRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.resultFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -329,58 +421,126 @@ export async function _testRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - fileType: + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"] as FileType, + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.logsFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], + ?.logsFileInfo?.["validationFailureDetails"], + }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - validationStatus: + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"] as FileType, + expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.reportFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], + ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"], + testResult: result.body["testResult"] as PFTestResult, virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + status: result.body["status"] as Status, + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"] as TestKind, + requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create and start a new test run with the given name. */ -export function testRun( +/** Create and start a new test run with the given test run Id. */ +export async function createOrUpdateTestRun( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, -): PollerLike, TestRun> { - return getLongRunningPoller(context, _testRunDeserialize, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _testRunSend(context, testRunId, resource, options), - }) as PollerLike, TestRun>; + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestRunSend( + context, + testRunId, + body, + options, + ); + return _createOrUpdateTestRunDeserialize(result); } export function _createOrUpdateAppComponentsSend( @@ -421,14 +581,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test run */ +/** Add an app component to a test run by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testRunId: string, @@ -486,9 +652,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -535,7 +707,7 @@ export async function _deleteTestRunDeserialize( return; } -/** Delete a test run by its name. */ +/** Delete an existing load test run by providing the testRunId. */ export async function deleteTestRun( context: Client, testRunId: string, @@ -570,9 +742,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -595,8 +773,8 @@ export function _getServerMetricsConfigSend( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse > { return context .path("/test-runs/{testRunId}/server-metrics-config", testRunId) @@ -605,8 +783,8 @@ export function _getServerMetricsConfigSend( export async function _getServerMetricsConfigDeserialize( result: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -615,14 +793,20 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** List server metrics configuration for the given test run. */ +/** Get associated server metrics configuration for the given test run. */ export async function getServerMetricsConfig( context: Client, testRunId: string, @@ -658,12 +842,20 @@ export async function _getTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], + type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, environmentVariables: result.body["environmentVariables"], @@ -672,6 +864,7 @@ export async function _getTestRunDeserialize( ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -687,6 +880,14 @@ export async function _getTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -700,6 +901,16 @@ export async function _getTestRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + })), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -711,20 +922,25 @@ export async function _getTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -733,20 +949,25 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -755,20 +976,25 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -777,26 +1003,60 @@ export async function _getTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"] as FileType, + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -807,11 +1067,14 @@ export async function _getTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -822,20 +1085,25 @@ export async function _getTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.resultFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -844,46 +1112,113 @@ export async function _getTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - fileType: + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"] as FileType, + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.logsFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], + ?.logsFileInfo?.["validationFailureDetails"], + }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - validationStatus: + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"] as FileType, + expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.reportFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], + ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"], + testResult: result.body["testResult"] as PFTestResult, virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + status: result.body["status"] as Status, + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"] as TestKind, + requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get test run details by name. */ +/** Get test run details by test run Id. */ export async function getTestRun( context: Client, testRunId: string, @@ -911,17 +1246,25 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { if (isUnexpected(result)) { throw createRestError(result); } return { url: result.body["url"], - fileName: result.body["fileName"], - fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], - validationStatus: result.body["validationStatus"], + fileType: result.body["fileType"] as FileType, + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, + validationStatus: result.body["validationStatus"] as FileStatus, validationFailureDetails: result.body["validationFailureDetails"], }; } @@ -932,7 +1275,13 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; +}> { const result = await _getTestRunFileSend( context, testRunId, @@ -946,7 +1295,9 @@ export function _listMetricDimensionValuesSend( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDimensionValues200Response @@ -961,10 +1312,10 @@ export function _listMetricDimensionValuesSend( .get({ ...operationOptionsToRequestParameters(options), queryParameters: { + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, metricNamespace: metricNamespace, - timespan: options?.timespan, + timespan: timespan, }, }); } @@ -973,43 +1324,44 @@ export async function _listMetricDimensionValuesDeserialize( result: | LoadTestRunListMetricDimensionValues200Response | LoadTestRunListMetricDimensionValuesDefaultResponse, -): Promise<_PagedDimensionValueList> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - value: result.body["value"].map((p) => ({ value: p["value"] })), + name: result.body["name"], + value: result.body["value"], nextLink: result.body["nextLink"], }; } /** List the dimension values for the given metric dimension name. */ -export function listMetricDimensionValues( +export async function listMetricDimensionValues( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( +): Promise { + const result = await _listMetricDimensionValuesSend( context, - () => - _listMetricDimensionValuesSend( - context, - testRunId, - name, - metricNamespace, - options, - ), - _listMetricDimensionValuesDeserialize, - { itemName: "value", nextLinkName: "nextLink" }, + testRunId, + name, + metricname, + metricNamespace, + timespan, + options, ); + return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response @@ -1019,7 +1371,7 @@ export function _listMetricDefinitionsSend( .path("/test-runs/{testRunId}/metric-definitions", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: options?.metricNamespace }, + queryParameters: { metricNamespace: metricNamespace }, }); } @@ -1044,14 +1396,14 @@ export async function _listMetricDefinitionsDeserialize( description: p["description"], name: p["name"], namespace: p["namespace"], - primaryAggregationType: p["primaryAggregationType"], + primaryAggregationType: p["primaryAggregationType"] as AggregationType, supportedAggregationTypes: p["supportedAggregationTypes"], - unit: p["unit"], + unit: p["unit"] as MetricUnit, metricAvailabilities: p["metricAvailabilities"] === undefined ? p["metricAvailabilities"] : p["metricAvailabilities"].map((p) => ({ - timeGrain: p["timeGrain"], + timeGrain: p["timeGrain"] as TimeGrain, })), })), }; @@ -1061,9 +1413,15 @@ export async function _listMetricDefinitionsDeserialize( export async function listMetricDefinitions( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _listMetricDefinitionsSend(context, testRunId, options); + const result = await _listMetricDefinitionsSend( + context, + testRunId, + metricNamespace, + options, + ); return _listMetricDefinitionsDeserialize(result); } @@ -1110,7 +1468,10 @@ export async function listMetricNamespaces( export function _listMetricsSend( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse @@ -1121,17 +1482,20 @@ export function _listMetricsSend( ...operationOptionsToRequestParameters(options), queryParameters: { aggregation: options?.aggregation, + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, - metricNamespace: options?.metricNamespace, - timespan: options?.timespan, - }, - body: { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map(dimensionFilterSerializer), + metricNamespace: metricNamespace, + timespan: timespan, }, + body: + body === undefined + ? body + : { + filters: + body["filters"] === undefined + ? body["filters"] + : body["filters"].map(dimensionFilterSerializer), + }, }); } @@ -1139,7 +1503,7 @@ export async function _listMetricsDeserialize( result: | LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse, -): Promise<_PagedTimeSeriesElement> { +): Promise<_Metrics> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1150,7 +1514,10 @@ export async function _listMetricsDeserialize( p["data"] === undefined ? p["data"] : p["data"].map((p) => ({ - timestamp: p["timestamp"], + timestamp: + p["timestamp"] !== undefined + ? new Date(p["timestamp"]) + : undefined, value: p["value"], })), dimensionValues: @@ -1169,12 +1536,24 @@ export async function _listMetricsDeserialize( export function listMetrics( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listMetricsSend(context, testRunId, body, options), + () => + _listMetricsSend( + context, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ), _listMetricsDeserialize, { itemName: "value", nextLinkName: "nextLink" }, ); @@ -1194,8 +1573,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom, - executionTo: options?.executionTo, + executionFrom: options?.executionFrom?.toISOString(), + executionTo: options?.executionTo?.toISOString(), status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1217,12 +1596,20 @@ export async function _listTestRunsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined : { value: p.certificate?.["value"], - type: p.certificate?.["type"], + type: p.certificate?.["type"] as CertificateType, name: p.certificate?.["name"], }, environmentVariables: p["environmentVariables"], @@ -1231,6 +1618,7 @@ export async function _listTestRunsDeserialize( ? p["errorDetails"] : p["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: p["testRunStatistics"], + regionalStatistics: p["regionalStatistics"], loadTestConfiguration: !p.loadTestConfiguration ? undefined : { @@ -1245,6 +1633,14 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1258,6 +1654,15 @@ export async function _listTestRunsDeserialize( "duration" ], }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + }), + ), }, testArtifacts: !p.testArtifacts ? undefined @@ -1269,25 +1674,26 @@ export async function _listTestRunsDeserialize( ?.configFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileName" ], - fileType: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "fileType" - ], + url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "url" + ], + fileType: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], - validationStatus: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -1297,24 +1703,27 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "fileName" ], - fileType: - p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ - "fileType" - ], + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], - validationStatus: - p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -1324,24 +1733,27 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileName" ], - fileType: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ], + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], - validationStatus: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -1351,26 +1763,64 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - fileType: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - validationStatus: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" ], }, + urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] === undefined @@ -1378,11 +1828,14 @@ export async function _listTestRunsDeserialize( : p.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), @@ -1394,25 +1847,26 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileName" ], - fileType: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "fileType" - ], + url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "url" + ], + fileType: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ], - validationStatus: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "validationStatus" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationFailureDetails" @@ -1421,54 +1875,117 @@ export async function _listTestRunsDeserialize( logsFileInfo: !p.testArtifacts?.outputArtifacts?.logsFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileName" ], - fileType: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "fileType" - ], + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" + ], + fileType: p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"] as FileType, expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ], - validationStatus: + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationStatus"] as FileStatus, + validationFailureDetails: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "validationStatus" + "validationFailureDetails" ], + }, + artifactsContainerInfo: !p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo + ? undefined + : { + url: p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !p.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "url" + ], + fileType: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ "validationFailureDetails" ], }, }, }, - testResult: p["testResult"], + testResult: p["testResult"] as PFTestResult, virtualUsers: p["virtualUsers"], displayName: p["displayName"], testId: p["testId"], description: p["description"], - status: p["status"], - startDateTime: p["startDateTime"], - endDateTime: p["endDateTime"], - executedDateTime: p["executedDateTime"], + status: p["status"] as Status, + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, + executedDateTime: + p["executedDateTime"] !== undefined + ? new Date(p["executedDateTime"]) + : undefined, portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - createdDateTime: p["createdDateTime"], + kind: p["kind"] as TestKind, + requestDataLevel: p["requestDataLevel"] as RequestDataLevel, + debugLogsEnabled: p["debugLogsEnabled"], + publicIPDisabled: p["publicIPDisabled"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], })), nextLink: result.body["nextLink"], }; } -/** Get all test runs with given filters */ +/** Get all test runs for the given filters. */ export function listTestRuns( context: Client, options: ListTestRunsOptionalParams = { requestOptions: {} }, @@ -1481,22 +1998,20 @@ export function listTestRuns( ); } -export function _stopTestRunSend( +export function _stopSend( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse + LoadTestRunStop200Response | LoadTestRunStopDefaultResponse > { return context .path("/test-runs/{testRunId}:stop", testRunId) .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestRunDeserialize( - result: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, +export async function _stopDeserialize( + result: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -1507,12 +2022,20 @@ export async function _stopTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"], + type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, environmentVariables: result.body["environmentVariables"], @@ -1521,6 +2044,7 @@ export async function _stopTestRunDeserialize( ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -1536,6 +2060,14 @@ export async function _stopTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1549,6 +2081,16 @@ export async function _stopTestRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => ({ + engineInstances: p["engineInstances"], + region: p["region"], + })), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -1560,20 +2102,25 @@ export async function _stopTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -1582,20 +2129,25 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -1604,20 +2156,25 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["validationStatus"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -1626,26 +2183,60 @@ export async function _stopTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["validationStatus"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"] as FileType, + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1656,11 +2247,14 @@ export async function _stopTestRunDeserialize( : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" ].map((p) => ({ - url: p["url"], fileName: p["fileName"], - fileType: p["fileType"], - expireDateTime: p["expireDateTime"], - validationStatus: p["validationStatus"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, validationFailureDetails: p["validationFailureDetails"], })), }, @@ -1671,20 +2265,25 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"] as FileType, expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.resultFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -1693,51 +2292,118 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - fileType: + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"] as FileType, + expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.logsFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationFailureDetails"], + }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - validationStatus: + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"] as FileType, + expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"], + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: result.body.testArtifacts + ?.outputArtifacts?.reportFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationFailureDetails"], + ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"], + testResult: result.body["testResult"] as PFTestResult, virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + status: result.body["status"] as Status, + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"] as TestKind, + requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Stop test run by name. */ -export async function stopTestRun( +/** Stop test run by test run Id. */ +export async function stop( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestRunSend(context, testRunId, options); - return _stopTestRunDeserialize(result); + const result = await _stopSend(context, testRunId, options); + return _stopDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts deleted file mode 100644 index d4d54d4e32..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - ResourceLocationConfig, - RunningOperation, - createHttpPoller, - OperationResponse, -} from "@azure/core-lro"; - -import { - Client, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { isUnexpected } from "../../rest/index.js"; - -export interface GetLongRunningPollerOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** - * The potential location of the result of the LRO if specified by the LRO extension in the swagger. - */ - resourceLocationConfig?: ResourceLocationConfig; - /** - * The original url of the LRO - * Should not be null when restoreFrom is set - */ - initialRequestUrl?: string; - /** - * A serialized poller which can be used to resume an existing paused Long-Running-Operation. - */ - restoreFrom?: string; - /** - * The function to get the initial response - */ - getInitialResponse?: () => PromiseLike; -} -export function getLongRunningPoller< - TResponse extends PathUncheckedResponse, - TResult = void, ->( - client: Client, - processResponseBody: (result: TResponse) => Promise, - options: GetLongRunningPollerOptions, -): PollerLike, TResult> { - const { restoreFrom, getInitialResponse } = options; - if (!restoreFrom && !getInitialResponse) { - throw new Error( - "Either restoreFrom or getInitialResponse must be specified", - ); - } - let initialResponse: TResponse | undefined = undefined; - const pollAbortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - if (!getInitialResponse) { - throw new Error( - "getInitialResponse is required when initializing a new poller", - ); - } - initialResponse = await getInitialResponse(); - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - pollOptions?: { - abortSignal?: AbortSignalLike; - }, - ) => { - // The poll request would both listen to the user provided abort signal and the poller's own abort signal - function abortListener(): void { - pollAbortController.abort(); - } - const abortSignal = pollAbortController.signal; - if (options.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (pollOptions?.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (!abortSignal.aborted) { - options.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - pollOptions?.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client.pathUnchecked(path).get({ abortSignal }); - } finally { - options.abortSignal?.removeEventListener("abort", abortListener); - pollOptions?.abortSignal?.removeEventListener("abort", abortListener); - } - if (options.initialRequestUrl || initialResponse) { - response.headers["x-ms-original-url"] = - options.initialRequestUrl ?? initialResponse!.request.url; - } - - return getLroResponse(response as TResponse); - }, - }; - return createHttpPoller(poller, { - intervalInMs: options?.updateIntervalInMs, - resourceLocationConfig: options?.resourceLocationConfig, - restoreFrom: options?.restoreFrom, - processResult: (result: unknown) => { - return processResponseBody(result as TResponse); - }, - }); -} -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @param deserializeFn - deserialize function to convert Rest response to modular output - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResponse, -): OperationResponse { - if (isUnexpected(response as PathUncheckedResponse)) { - throw createRestError(response); - } - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index df5682bd18..cff7cc0f3f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ @@ -12,13 +12,13 @@ export interface TestRunOperationsClientOptions extends ClientOptions { apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createTestRunOperations( endpointParam: string, credential: TokenCredential, options: TestRunOperationsClientOptions = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index d5ab0cdb96..a975e76b1e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -5,7 +5,6 @@ export { TestRunOperationsClient, TestRunOperationsClientOptions, } from "./testRunOperationsClient.js"; -export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Test, PassFailCriteria, @@ -14,16 +13,19 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -34,12 +36,15 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -47,7 +52,6 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -55,7 +59,18 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestRunOptionalParams, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -68,7 +83,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index cfa3ac60f4..cda684bcff 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -9,16 +9,19 @@ export { PFAgFunc, PFAction, PFResult, + AutoStopCriteria, Secret, SecretType, CertificateMetadata, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, FileType, FileStatus, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -29,12 +32,15 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, PFTestResult, Status, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, @@ -42,7 +48,6 @@ export { AggregationType, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -50,9 +55,20 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + ResourceKind, + TestProfileRun, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + RecommendationCategory, + TargetResourceConfigurationsUnion, } from "./models.js"; export { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -65,7 +81,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index 3a7491a214..31dd6af57e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -6,10 +6,12 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -19,12 +21,19 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -33,32 +42,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -68,6 +83,9 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -80,9 +98,12 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -113,7 +134,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -148,29 +169,55 @@ export function passFailMetricSerializer( }; } -/** Type of PFMetrics */ +/** Metrics for pass/fail criteria. */ export type PFMetrics = | "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; -/** Type of PFAgFunc */ +/** Aggregation functions for pass/fail criteria. */ export type PFAgFunc = | "count" | "percentage" | "avg" | "p50" + | "p75" | "p90" | "p95" + | "p96" + | "p97" + | "p98" | "p99" + | "p99.9" + | "p99.99" | "min" | "max"; -/** Type of PFAction */ +/** Action to take on failure of pass/fail criteria. */ export type PFAction = "continue" | "stop"; -/** Type of PFResult */ +/** Pass/fail criteria result. */ export type PFResult = "passed" | "undetermined" | "failed"; +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} + /** Secret */ export interface Secret { /** The value of the secret for the respective type */ @@ -186,7 +233,7 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Type of SecretType */ +/** Types of secrets supported. */ export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ @@ -209,15 +256,12 @@ export function certificateMetadataSerializer( }; } -/** Type of CertificateType */ +/** Types of certificates supported. */ export type CertificateType = "AKV_CERT_URI"; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -231,8 +275,10 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -245,21 +291,26 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } @@ -268,53 +319,86 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Type of FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** Type of FileStatus */ +/** Types of file supported. */ +export type FileType = + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS" + | "ZIPPED_ARTIFACTS" + | "URL_TEST_CONFIG" + | "TEST_SCRIPT"; +/** File status. */ export type FileStatus = | "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +/** Test kind */ +export type TestKind = "URL" | "JMX" | "Locust"; -/** Test app component */ +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -324,12 +408,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -345,20 +429,14 @@ export function testAppComponentsSerializer( }; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -387,13 +465,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -402,9 +480,10 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, }; } @@ -446,31 +525,21 @@ export function resourceMetricSerializer( }; } -/** Collection of files. */ -export interface _PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Type of APIVersions */ -export type APIVersions = "2022-11-01"; +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -485,8 +554,18 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -503,24 +582,32 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -530,6 +617,9 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -545,6 +635,8 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -578,6 +670,18 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -597,28 +701,58 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; } -/** Type of PFTestResult */ +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Test result based on pass/fail criteria. */ export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Type of Status */ +/** Test run status. */ export type Status = | "ACCEPTED" | "NOTSTARTED" @@ -636,6 +770,8 @@ export type Status = | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +/** Request data collection level for test run */ +export type RequestDataLevel = "NONE" | "ERRORS"; /** Test run app component */ export interface TestRunAppComponents { @@ -647,12 +783,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -678,12 +814,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -698,11 +834,17 @@ export function testRunServerMetricConfigSerializer( }; } -/** Type of Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Time Grain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -742,16 +884,22 @@ export interface NameAndDesc { name?: string; } -/** Type of AggregationType */ +/** Aggregation type. */ export type AggregationType = | "Average" | "Count" | "None" | "Total" + | "Percentile75" | "Percentile90" | "Percentile95" - | "Percentile99"; -/** Type of MetricUnit */ + | "Percentile96" + | "Percentile97" + | "Percentile98" + | "Percentile99" + | "Percentile999" + | "Percentile9999"; +/** Metric unit. */ export type MetricUnit = | "NotSpecified" | "Percent" @@ -771,9 +919,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** Type of TimeGrain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -788,7 +933,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -828,7 +973,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _PagedTimeSeriesElement { +export interface _Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -845,8 +990,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -859,7 +1004,217 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Kind of the resource on which test profile is created. */ +export type ResourceKind = "FunctionsFlexConsumption"; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Test profile run status. */ +export type TestProfileRunStatus = + | "ACCEPTED" + | "NOTSTARTED" + | "EXECUTING" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED"; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Category of Recommendation. */ +export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -867,10 +1222,23 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface _PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; /** The link to the next page of items */ nextLink?: string; } + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index 965a8a192f..b7d2fc2c49 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -2,12 +2,10 @@ // Licensed under the MIT license. import { OperationOptions } from "@azure-rest/core-client"; -import { Interval } from "./models.js"; +import { TimeGrain } from "./models.js"; /** Optional parameters. */ -export interface TestRunOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; +export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { /** This request has a JSON Merge Patch body. */ contentType?: string; /** @@ -22,12 +20,14 @@ export interface TestRunOptionalParams extends OperationOptions { /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -51,21 +51,11 @@ export interface GetTestRunFileOptionalParams extends OperationOptions {} export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } /** Optional parameters. */ -export interface ListMetricDefinitionsOptionalParams extends OperationOptions { - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; -} +export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface ListMetricNamespacesOptionalParams extends OperationOptions {} @@ -75,16 +65,7 @@ export interface ListMetricsOptionalParams extends OperationOptions { /** The aggregation */ aggregation?: string; /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } /** Optional parameters. */ @@ -102,10 +83,10 @@ export interface ListTestRunsOptionalParams extends OperationOptions { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -113,4 +94,4 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopTestRunOptionalParams extends OperationOptions {} +export interface StopOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts deleted file mode 100644 index a96372d9f9..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - deserializeState, - ResourceLocationConfig, -} from "@azure/core-lro"; -import { TestRunOperationsClient } from "./testRunOperationsClient.js"; -import { getLongRunningPoller } from "./api/pollingHelpers.js"; -import { _testRunDeserialize } from "./api/operations.js"; -import { - PathUncheckedResponse, - OperationOptions, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; - -export interface RestorePollerOptions< - TResult, - TResponse extends PathUncheckedResponse = PathUncheckedResponse, -> extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** Deserialization function for raw response body */ - processResponseBody?: (result: TResponse) => Promise; -} - -/** - * Creates a poller from the serialized state of another poller. This can be - * useful when you want to create pollers on a different host or a poller - * needs to be constructed after the original one is not in scope. - */ -export function restorePoller( - client: TestRunOperationsClient, - serializedState: string, - sourceOperation: ( - ...args: any[] - ) => PollerLike, TResult>, - options?: RestorePollerOptions, -): PollerLike, TResult> { - const pollerConfig = deserializeState(serializedState).config; - const { initialRequestUrl, requestMethod, metadata } = pollerConfig; - if (!initialRequestUrl || !requestMethod) { - throw new Error( - `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, - ); - } - const resourceLocationConfig = metadata?.["resourceLocationConfig"] as - | ResourceLocationConfig - | undefined; - const deserializeHelper = - options?.processResponseBody ?? - getDeserializationHelper(initialRequestUrl, requestMethod); - if (!deserializeHelper) { - throw new Error( - `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, - ); - } - return getLongRunningPoller( - (client as any)["_client"] ?? client, - deserializeHelper as (result: TResponse) => Promise, - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - resourceLocationConfig, - restoreFrom: serializedState, - initialRequestUrl, - }, - ); -} - -const deserializeMap: Record = { - "PATCH /test-runs/{testRunId}": _testRunDeserialize, -}; - -function getDeserializationHelper( - urlStr: string, - method: string, -): ((result: unknown) => Promise) | undefined { - const path = new URL(urlStr).pathname; - const pathParts = path.split("/"); - - // Traverse list to match the longest candidate - // matchedLen: the length of candidate path - // matchedValue: the matched status code array - let matchedLen = -1, - matchedValue: ((result: unknown) => Promise) | undefined; - - // Iterate the responseMap to find a match - for (const [key, value] of Object.entries(deserializeMap)) { - // Extracting the path from the map key which is in format - // GET /path/foo - if (!key.startsWith(method)) { - continue; - } - const candidatePath = getPathFromMapKey(key); - // Get each part of the url path - const candidateParts = candidatePath.split("/"); - - // track if we have found a match to return the values found. - let found = true; - for ( - let i = candidateParts.length - 1, j = pathParts.length - 1; - i >= 1 && j >= 1; - i--, j-- - ) { - if ( - candidateParts[i]?.startsWith("{") && - candidateParts[i]?.indexOf("}") !== -1 - ) { - const start = candidateParts[i]!.indexOf("}") + 1, - end = candidateParts[i]?.length; - // If the current part of the candidate is a "template" part - // Try to use the suffix of pattern to match the path - // {guid} ==> $ - // {guid}:export ==> :export$ - const isMatched = new RegExp( - `${candidateParts[i]?.slice(start, end)}`, - ).test(pathParts[j] || ""); - - if (!isMatched) { - found = false; - break; - } - continue; - } - - // If the candidate part is not a template and - // the parts don't match mark the candidate as not found - // to move on with the next candidate path. - if (candidateParts[i] !== pathParts[j]) { - found = false; - break; - } - } - - // We finished evaluating the current candidate parts - // Update the matched value if and only if we found the longer pattern - if (found && candidatePath.length > matchedLen) { - matchedLen = candidatePath.length; - matchedValue = value as (result: unknown) => Promise; - } - } - - return matchedValue; -} - -function getPathFromMapKey(mapKey: string): string { - const pathStart = mapKey.indexOf("/"); - return mapKey.slice(pathStart); -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index af36f1eef8..3ee7201db9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -1,11 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { PollerLike, OperationState } from "@azure/core-lro"; import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - FileInfo, + FileType, + FileStatus, TestRun, TestRunAppComponents, TestRunServerMetricConfig, @@ -16,7 +16,7 @@ import { TimeSeriesElement, } from "./models/models.js"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -29,11 +29,11 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -46,16 +46,16 @@ import { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, createTestRunOperations, TestRunOperationsClientOptions, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./api/index.js"; export { TestRunOperationsClientOptions } from "./api/testRunOperationsContext.js"; export class TestRunOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -68,16 +68,16 @@ export class TestRunOperationsClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given name. */ - testRun( + /** Create and start a new test run with the given test run Id. */ + createOrUpdateTestRun( testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, - ): PollerLike, TestRun> { - return testRun(this._client, testRunId, resource, options); + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTestRun(this._client, testRunId, body, options); } - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ createOrUpdateAppComponents( testRunId: string, body: TestRunAppComponents, @@ -102,7 +102,7 @@ export class TestRunOperationsClient { ); } - /** Delete a test run by its name. */ + /** Delete an existing load test run by providing the testRunId. */ deleteTestRun( testRunId: string, options: DeleteTestRunOptionalParams = { requestOptions: {} }, @@ -121,7 +121,7 @@ export class TestRunOperationsClient { return getAppComponents(this._client, testRunId, options); } - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ getServerMetricsConfig( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, @@ -129,7 +129,7 @@ export class TestRunOperationsClient { return getServerMetricsConfig(this._client, testRunId, options); } - /** Get test run details by name. */ + /** Get test run details by test run Id. */ getTestRun( testRunId: string, options: GetTestRunOptionalParams = { requestOptions: {} }, @@ -142,7 +142,13 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }> { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -150,14 +156,18 @@ export class TestRunOperationsClient { listMetricDimensionValues( testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): Promise { return listMetricDimensionValues( this._client, testRunId, name, + metricname, metricNamespace, + timespan, options, ); } @@ -165,9 +175,15 @@ export class TestRunOperationsClient { /** List the metric definitions for a load test run. */ listMetricDefinitions( testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - return listMetricDefinitions(this._client, testRunId, options); + return listMetricDefinitions( + this._client, + testRunId, + metricNamespace, + options, + ); } /** List the metric namespaces for a load test run. */ @@ -181,24 +197,35 @@ export class TestRunOperationsClient { /** List the metric values for a load test run. */ listMetrics( testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { - return listMetrics(this._client, testRunId, body, options); + return listMetrics( + this._client, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ); } - /** Get all test runs with given filters */ + /** Get all test runs for the given filters. */ listTestRuns( options: ListTestRunsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } - /** Stop test run by name. */ - stopTestRun( + /** Stop test run by test run Id. */ + stop( testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - return stopTestRun(this._client, testRunId, options); + return stop(this._client, testRunId, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp index 203666d54f..021393f03c 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp @@ -3,47 +3,85 @@ import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Versioning; using Azure.ClientGenerator.Core; -using AzureLoadTesting; +using Microsoft.LoadTestService; @useDependency(APIVersions.v2022_11_01) +@useDependency(APIVersions.v2023_04_01_preview) +@useDependency(APIVersions.v2024_05_01_preview) namespace Customizations; +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestAdministrationClient", - service: AzureLoadTesting, + name: "LoadTestAdministrationClient", + service: Microsoft.LoadTestService, }) interface AdministrationOperations { - CreateOrUpdateTest is LoadTestAdministration.CreateOrUpdateTest; - CreateOrUpdateAppComponents is LoadTestAdministration.CreateOrUpdateAppComponents; - CreateOrUpdateServerMetricsConfig is LoadTestAdministration.CreateOrUpdateServerMetricsConfig; - GetAppComponents is LoadTestAdministration.GetAppComponents; - GetServerMetricsConfig is LoadTestAdministration.GetServerMetricsConfig; - GetTest is LoadTestAdministration.GetTest; - GetTestFile is LoadTestAdministration.GetTestFile; - ListTestFiles is LoadTestAdministration.ListTestFiles; - ListTests is LoadTestAdministration.ListTests; - UploadTestFile is LoadTestAdministration.UploadTestFile; - DeleteTestFile is LoadTestAdministration.DeleteTestFile; - DeleteTest is LoadTestAdministration.DeleteTest; -}; + createOrUpdateTest is LoadTestAdministration.createOrUpdateTest; + createOrUpdateAppComponents is LoadTestAdministration.createOrUpdateAppComponents; + createOrUpdateServerMetricsConfig is LoadTestAdministration.createOrUpdateServerMetricsConfig; + getAppComponents is LoadTestAdministration.getAppComponents; + getServerMetricsConfig is LoadTestAdministration.getServerMetricsConfig; + getTest is LoadTestAdministration.getTest; + getTestFile is LoadTestAdministration.getTestFile; + listTestFiles is LoadTestAdministration.listTestFiles; + listTests is LoadTestAdministration.listTests; + #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." + @clientName("BeginUploadTestFile", "python") + uploadTestFile is LoadTestAdministration.uploadTestFile; + deleteTestFile is LoadTestAdministration.deleteTestFile; + deleteTest is LoadTestAdministration.deleteTest; +} +#suppress "@azure-tools/typespec-azure-core/use-standard-operations" @client({ - name: "LoadTestRunClient", - service: AzureLoadTesting, + name: "LoadTestRunClient", + service: Microsoft.LoadTestService, }) interface TestRunOperations { - TestRun is LoadTestRun.CreateOrUpdateTestRun; - CreateOrUpdateAppComponents is LoadTestRun.CreateOrUpdateAppComponents; - CreateOrUpdateServerMetricsConfig is LoadTestRun.CreateOrUpdateServerMetricsConfig; - DeleteTestRun is LoadTestRun.DeleteTestRun; - GetAppComponents is LoadTestRun.GetAppComponents; - GetServerMetricsConfig is LoadTestRun.GetServerMetricsConfig; - GetTestRun is LoadTestRun.GetTestRun; - GetTestRunFile is LoadTestRun.GetTestRunFile; - ListMetricDimensionValues is LoadTestRun.ListMetricDimensionValues; - ListMetricDefinitions is LoadTestRun.ListMetricDefinitions; - ListMetricNamespaces is LoadTestRun.ListMetricNamespaces; - ListMetrics is LoadTestRun.ListMetrics; - ListTestRuns is LoadTestRun.ListTestRuns; - StopTestRun is LoadTestRun.StopTestRun; -}; + @clientName("BeginTestRun", "python") + createOrUpdateTestRun is LoadTestRun.createOrUpdateTestRun; + createOrUpdateAppComponents is LoadTestRun.createOrUpdateAppComponents; + createOrUpdateServerMetricsConfig is LoadTestRun.createOrUpdateServerMetricsConfig; + deleteTestRun is LoadTestRun.deleteTestRun; + getAppComponents is LoadTestRun.getAppComponents; + getServerMetricsConfig is LoadTestRun.getServerMetricsConfig; + getTestRun is LoadTestRun.getTestRun; + getTestRunFile is LoadTestRun.getTestRunFile; + listMetricDimensionValues is LoadTestRun.listMetricDimensionValues; + @clientName("get_metric_definitions", "python") + @clientName("getMetricDefinitions", "java") + listMetricDefinitions is LoadTestRun.listMetricDefinitions; + @clientName("get_metric_namespaces", "python") + @clientName("getMetricNamespaces", "java") + listMetricNamespaces is LoadTestRun.listMetricNamespaces; + listMetrics is LoadTestRun.listMetrics; + listTestRuns is LoadTestRun.listTestRuns; + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + @clientName("stopTestRun", "javascript,python,java,csharp,go") + stop is LoadTestRun.stop; +} + +@client({ + name: "TestProfileAdministrationClient", + service: Microsoft.LoadTestService, +}) +interface TestProfileAdministrationOperations { + createOrUpdateTestProfile is TestProfileAdministration.createOrUpdateTestProfile; + deleteTestProfile is TestProfileAdministration.deleteTestProfile; + getTestProfile is TestProfileAdministration.getTestProfile; + listTestProfiles is TestProfileAdministration.listTestProfiles; +} + +@client({ + name: "TestProfileRunClient", + service: Microsoft.LoadTestService, +}) +interface TestProfileRunOperations { + createOrUpdateTestProfileRun is TestProfileRunAdministration.createOrUpdateTestProfileRun; + deleteTestProfileRun is TestProfileRunAdministration.deleteTestProfileRun; + getTestProfileRun is TestProfileRunAdministration.getTestProfileRun; + listTestProfileRuns is TestProfileRunAdministration.listTestProfileRuns; + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + @clientName("stopTestProfileRun", "javascript,python,java,csharp,go") + stop is TestProfileRunAdministration.stop; +} diff --git a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp index 6fc3242049..9eeccba0b3 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp @@ -1,5 +1,6 @@ import "@typespec/rest"; import "@typespec/http"; +import "@typespec/versioning"; import "./routes.tsp"; using TypeSpec.Rest; @@ -9,7 +10,9 @@ using Azure.Core; @versioned(APIVersions) @useAuth(Oauth2) -@service({title: "Azure Load Testing"}) +@service({ + title: "Azure Load Testing", +}) @server( "https://{endpoint}", "These APIs allow end users to create, view and run load tests using Azure Load Test Service.", @@ -18,17 +21,30 @@ using Azure.Core; } ) @doc(""" -These APIs allow end users to create, view and run load tests using Azure Load -Test Service. -""") -namespace AzureLoadTesting; + These APIs allow end users to create, view and run load tests using Azure Load Test Service. + """) +namespace Microsoft.LoadTestService; +@doc("Azure Load Testing API versions.") enum APIVersions { + @doc("The 2022-11-01 version of the Azure Load Testing API.") @useDependency(Azure.Core.Versions.v1_0_Preview_2) v2022_11_01: "2022-11-01", + + @doc("The 2023-04-01-preview version of the Azure Load Testing API.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + v2023_04_01_preview: "2023-04-01-preview", + + @doc("The 2024-03-01-preview version of the Azure Load Testing API.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + v2024_03_01_preview: "2024-03-01-preview", + + @doc("The 2024-05-01-preview version of the Azure Load Testing API.") + @useDependency(Azure.Core.Versions.v1_0_Preview_2) + v2024_05_01_preview: "2024-05-01-preview", } -@doc("The Azure Active Directory OAuth2 Flow") +@doc("OAuth 2.0 Flow with Microsoft Entra ID.") model Oauth2 is OAuth2Auth<[ { @@ -36,4 +52,4 @@ model Oauth2 authorizationUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; scopes: ["https://cnt-prod.loadtesting.azure.com/.default"]; } - ]>; \ No newline at end of file + ]>; diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp new file mode 100644 index 0000000000..02e1e85232 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp @@ -0,0 +1,324 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; + +using TypeSpec.Rest; +using TypeSpec.Http; +using TypeSpec.Versioning; +using Azure.ClientGenerator.Core; + +namespace Microsoft.LoadTestService; + +@doc("Test Profile Id path parameter.") +@added(APIVersions.v2024_05_01_preview) +model TestProfileIdPathParameter { + @doc("Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @maxLength(50) + @minLength(2) + @key + @visibility("read") + @pattern("^[a-z0-9_-]*$") + testProfileId: string; +} + +@doc("Test Profile Run Id path parameter.") +@added(APIVersions.v2024_05_01_preview) +model TestProfileRunIdPathParameter { + @doc("Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @visibility("read") + @maxLength(50) + @minLength(2) + @key + @pattern("^[a-z0-9_-]*$") + testProfileRunId: string; +} + +@doc("Kind of the resource on which test profile is created.") +@added(APIVersions.v2024_05_01_preview) +union ResourceKind { + string, + + @doc("Resource is a Azure FunctionApp on Flex Consumption Plan.") + FunctionsFlexConsumption: "FunctionsFlexConsumption", +} + +@doc("Test profile run status.") +union TestProfileRunStatus { + string, + + @doc("Test profile run request is accepted.") + ACCEPTED: "ACCEPTED", + + @doc("Test profile run is not yet started.") + NOTSTARTED: "NOTSTARTED", + + @doc("Test profile run has started executing.") + EXECUTING: "EXECUTING", + + @doc("Test profile run has completed successfully.") + DONE: "DONE", + + @doc("Test profile run is being cancelled.") + CANCELLING: "CANCELLING", + + @doc("Test profile run is cancelled.") + CANCELLED: "CANCELLED", + + @doc("Test profile run has failed.") + FAILED: "FAILED", +} + +@doc("Category of Recommendation.") +@added(APIVersions.v2024_05_01_preview) +union RecommendationCategory { + string, + + @doc("The recommendation for this category optimizes the throughput/RPS (Requests per Second) of the app.") + ThroughputOptimized: "ThroughputOptimized", + + @doc("The recommendation for this category optimizes the cost of the app.") + CostOptimized: "CostOptimized", +} + +@doc("Resource configuration instance for a Flex Consumption based Azure Function App.") +@added(APIVersions.v2024_05_01_preview) +model FunctionFlexConsumptionResourceConfiguration { + #suppress "@azure-tools/typespec-azure-core/casing-style" "Abbreviating MB to Mb changes the meaning of the value." + @doc("Memory size of the instance. Supported values are 512, 2048, 2096.") + instanceMemoryMB: int64; + + @doc("HTTP Concurrency for the function app.") + httpConcurrency: int64; +} + +@doc("Details of a particular test run for a test profile run.") +@added(APIVersions.v2024_05_01_preview) +model TestRunDetail { + @doc("Status of the test run.") + status: Status; + + @doc("ID of the configuration on which the test ran.") + configurationId: string; + + @doc("Key value pair of extra properties associated with the test run.") + properties: Record; +} + +@doc("A recommendation object that provides a list of configuration that optimizes its category.") +@added(APIVersions.v2024_05_01_preview) +model TestProfileRunRecommendation { + @doc("Category of the recommendation.") + category: RecommendationCategory; + + @doc("List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations.") + configurations?: string[]; +} + +@doc("Configurations of a target resource. This varies with the kind of resource.") +@added(APIVersions.v2024_05_01_preview) +@discriminator("kind") +model TargetResourceConfigurations { + @doc("Kind of the resource for which the configurations apply.") + @visibility("create", "read") + kind: ResourceKind; +} + +@doc("Configurations for a Function App using Flex Consumption Plan.") +@added(APIVersions.v2024_05_01_preview) +model FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + @doc(""" + The kind value to use when providing configuration. + This should typically be not changed from its value. + """) + kind: ResourceKind.FunctionsFlexConsumption; + + @doc("A map of configurations for a Function app using Flex Consumption Plan.") + configurations?: Record; +} + +@doc("The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource.") +@summary("Test Profile Model.") +@resource("test-profiles") +@added(APIVersions.v2024_05_01_preview) +model TestProfile { + ...TestProfileIdPathParameter; + + @maxLength(50) + @minLength(2) + @doc("Display name of the test profile.") + displayName?: string; + + @maxLength(100) + @doc("Description for the test profile.") + description?: string; + + @doc("Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated.") + @visibility("create", "read") + testId?: string; + + @doc("Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated.") + @visibility("create", "read") + targetResourceId?: string; + + @doc("Configurations of the target resource on which testing would be done.") + targetResourceConfigurations?: TargetResourceConfigurations; + + ...SystemMetaData; +} + +@doc("The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource.") +@summary("Test Profile Run model.") +@resource("test-profile-runs") +@added(APIVersions.v2024_05_01_preview) +model TestProfileRun { + ...TestProfileRunIdPathParameter; + + // Begin section: Properties provided by user + @maxLength(50) + @minLength(2) + @doc("Display name for the test profile run.") + displayName?: string; + + @maxLength(100) + @doc("The test profile run description") + description?: string; + + @doc("Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated.") + @visibility("create", "read") + testProfileId?: string; + + // End section: Properties provided by user + + // Begin section: Properties populated from Test Profile + @doc("Target resource ID on which the test profile run is created") + @visibility("read") + targetResourceId?: string; + + @doc("Configurations of the target resource on which the test profile ran.") + @visibility("read") + targetResourceConfigurations?: TargetResourceConfigurations; + + // End section: Properties populated from Test Profile + + // Begin section: Test profile Run specific information + @doc("The test profile run status.") + @visibility("read") + status?: TestProfileRunStatus; + + @doc("Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run.") + @visibility("read") + errorDetails?: ErrorDetails[]; + + @doc("The test profile run start DateTime(RFC 3339 literal format).") + @visibility("read") + startDateTime?: utcDateTime; + + @doc("The test profile run end DateTime(RFC 3339 literal format).") + @visibility("read") + endDateTime?: utcDateTime; + + @doc("Test profile run duration in seconds.") + @visibility("read") + durationInSeconds?: int64; + + @doc(""" + Details of the test runs ran as part of the test profile run. + Key is the testRunId of the corresponding testRun. + """) + @visibility("read") + testRunDetails?: Record; + + @doc("Recommendations provided based on a successful test profile run.") + @visibility("read") + recommendations?: TestProfileRunRecommendation[]; + + // End section: Test profile run specific information + + ...SystemMetaData; +} + +@doc("Parameters for list test profile operation") +@added(APIVersions.v2024_05_01_preview) +model ListTestProfileQueryParams { + @doc("Maximum number of results to include in a single response.") + @query + maxpagesize?: int32; + + @doc(""" + Start DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. + """) + @query + lastModifiedStartTime?: utcDateTime; + + @doc(""" + End DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. + """) + @query + lastModifiedEndTime?: utcDateTime; + + @doc("Comma separated list of IDs of the test profiles to filter.") + @query + testProfileIds?: string; + + @doc("Comma separated list IDs of the tests which should be associated with the test profiles to fetch.") + @query + testIds?: string; +} + +@doc("Parameters for list test profile run operation") +@added(APIVersions.v2024_05_01_preview) +model ListTestProfileRunQueryParams { + @doc("Maximum number of results to include in a single response.") + @query + maxpagesize?: int32; + + @doc(""" + Minimum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. + """) + @query + minStartDateTime?: utcDateTime; + + @doc(""" + Maximum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. + """) + @query + maxStartDateTime?: utcDateTime; + + @doc(""" + Minimum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. + """) + @query + minEndDateTime?: utcDateTime; + + @doc(""" + Maximum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. + """) + @query + maxEndDateTime?: utcDateTime; + + @doc(""" + Start DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. + """) + @query + createdDateStartTime?: utcDateTime; + + @doc(""" + End DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. + """) + @query + createdDateEndTime?: utcDateTime; + + @doc("Comma separated list of IDs of the test profile runs to filter.") + @query + testProfileRunIds?: string; + + @doc("Comma separated IDs of the test profiles which should be associated with the test profile runs to fetch.") + @query + testProfileIds?: string; + + @doc("Comma separated list of Statuses of the test profile runs to filter.") + @query + statuses?: string; +} diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp index cb943d38b7..5f1ccb5d57 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp @@ -1,152 +1,283 @@ import "@typespec/rest"; import "@typespec/http"; import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-client-generator-core"; using TypeSpec.Rest; using TypeSpec.Http; +using TypeSpec.Versioning; +using Azure.ClientGenerator.Core; -namespace AzureLoadTesting; +namespace Microsoft.LoadTestService; -enum PFMetrics { - @doc("Pass fail criteria for response time metric") response_time_ms, - @doc("Pass fail criteria for response time metric") latency, - @doc("Pass fail criteria for error metric") error, - @doc("Pass fail criteria for total requests") requests, - @doc("Pass fail criteria for request rate.") requests_per_sec, -} - -enum PFAgFunc { - @doc("Criteria applies for count value") count, - @doc("Criteria applies for given percentage value") percentage, - @doc("Criteria applies for avg value") avg, - @doc("Criteria applies for 50th percentile value") p50, - @doc("Criteria applies for 90th percentile value") p90, - @doc("Criteria applies for 95th percentile value") p95, - @doc("Criteria applies for 99th percentile value") p99, - @doc("Criteria applies for minimum value") min, - @doc("Criteria applies for maximum value") max, -} - -enum PFAction { - @doc("Test will continue to run even if pass fail metric criteria metric gets failed") - continue, - @doc("Test run will stop if pass fail criteria metric is not passed.") stop, -} - -enum PFResult { - @doc("Given pass fail criteria metric has passed.") passed, - @doc("Given pass fail criteria metric couldn't determine.") undetermined, - @doc("Given pass fail criteria metric has failed.") failed, -} - -enum SecretType { - @doc("If the secret is stored in an Azure Key Vault") AKV_SECRET_URI, - @doc("If the Plain text secret value provided") SECRET_VALUE, -} - -enum CertificateType { - @doc("If the certificate is stored in an Azure Key Vault") AKV_CERT_URI, -} - -enum FileType { - @doc("If file is jmx script") JMX_FILE, - @doc("If file is user properties") USER_PROPERTIES, - @doc("If file is not any of other supported type") ADDITIONAL_ARTIFACTS, -} - -enum FileStatus { - @doc("File is not validated.") NOT_VALIDATED, - @doc("File is validated.") VALIDATION_SUCCESS, - @doc("File validation is failed.") VALIDATION_FAILURE, - @doc("File validation is in progress.") VALIDATION_INITIATED, - @doc("Validation is not required.") VALIDATION_NOT_REQUIRED, -} - -enum PFTestResult { - @doc("Pass/fail criteria has passed.") PASSED, - @doc("Pass/fail criteria is not applicable.") NOT_APPLICABLE, - @doc("Pass/fail criteria has failed.") FAILED, -} - -enum Status { - @doc("Test run request is accepted") ACCEPTED, - @doc("Test run is not yet started.") NOTSTARTED, - @doc("Test run is getting provision") PROVISIONING, - @doc("Test run is provisioned") PROVISIONED, - @doc("Test run is getting configure") CONFIGURING, - @doc("Test run configuration is done") CONFIGURED, - @doc("Test run has started executing") EXECUTING, - @doc("Test run has been executed") EXECUTED, - @doc("Test run is getting deprovision") DEPROVISIONING, - @doc("Test run request is deprovisioned") DEPROVISIONED, - @doc("Test run request is finished") DONE, - @doc("Test run request is getting cancelled") CANCELLING, - @doc("Test run request is cancelled") CANCELLED, - @doc("Test run request is failed") FAILED, - @doc("Test run JMX file is validated") VALIDATION_SUCCESS, - @doc("Test run JMX file validation is failed") VALIDATION_FAILURE, -} - -enum AggregationType { - @doc("Average value") Average, - @doc("Total count") Count, - @doc("Aggregation will be average in this case") None, - @doc("Total sum") Total, - @doc("90th percentile") Percentile90, - @doc("95th percentile") Percentile95, - @doc("99th percentile") Percentile99, -} - -enum MetricUnit { - @doc("No unit specified") NotSpecified, - @doc("Percentage") Percent, - @doc("Value count") Count, - @doc("Seconds") Seconds, - @doc("Milliseconds") Milliseconds, - @doc("Bytes") Bytes, - @doc("Bytes per second") BytesPerSecond, - @doc("Count per second") CountPerSecond, -} - -enum TimeGrain { - @doc("5 seconds, available only if test run duration is less than 10 minutes") - PT5S, - @doc("10 seconds, available only if test run duration is less than 10 minutes") - PT10S, - @doc("1 minute") PT1M, - @doc("5 minutes, available only if test run duration is greater than 1 minute") - PT5M, - @doc("1 hour, available only if test run duration is greater than 1 minute") - PT1H, -} - -enum Interval { - @doc("5 seconds, available only if test run duration is less than 10 minutes") - PT5S, - @doc("10 seconds, available only if test run duration is less than 10 minutes") - PT10S, - @doc("1 minute") PT1M, - @doc("5 minutes, available only if test run duration is greater than 1 minute") - PT5M, - @doc("1 hour, available only if test run duration is greater than 1 minute") - PT1H, -} - -@doc("Load test model") +@doc("Metrics for pass/fail criteria.") +union PFMetrics { + string, + + @doc("Pass fail criteria for response time metric in milliseconds.") + "response_time_ms", + + @doc("Pass fail criteria for latency metric in milliseconds.") "latency", + @doc("Pass fail criteria for error metric.") "error", + @doc("Pass fail criteria for total requests.") "requests", + @doc("Pass fail criteria for request per second.") "requests_per_sec", +} + +@doc("Aggregation functions for pass/fail criteria.") +union PFAgFunc { + string, + @doc("Criteria applies for count value.") "count", + @doc("Criteria applies for given percentage value.") "percentage", + @doc("Criteria applies for avg value.") "avg", + @doc("Criteria applies for 50th percentile value.") "p50", + + @doc("Criteria applies for 75th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p75", + + @doc("Criteria applies for 90th percentile value.") "p90", + @doc("Criteria applies for 95th percentile value.") "p95", + + @doc("Criteria applies for 96th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p96", + + @doc("Criteria applies for 97th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p97", + + @doc("Criteria applies for 98th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p98", + + @doc("Criteria applies for 99th percentile value.") "p99", + + @doc("Criteria applies for 99.9th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p99.9", + + @doc("Criteria applies for 99.99th percentile value.") + @added(APIVersions.v2024_05_01_preview) + "p99.99", + + @doc("Criteria applies for minimum value.") "min", + @doc("Criteria applies for maximum value.") "max", +} + +@doc("Action to take on failure of pass/fail criteria.") +union PFAction { + string, + + @doc("Test will continue to run even if pass fail metric criteria metric gets failed.") + continue: "continue", + + @doc("Test run will stop if pass fail criteria metric is not passed.") + stop: "stop", +} + +@doc("Pass/fail criteria result.") +union PFResult { + string, + @doc("Given pass fail criteria metric has passed.") "passed", + @doc("Given pass fail criteria metric couldn't determine.") "undetermined", + @doc("Given pass fail criteria metric has failed.") "failed", +} + +@doc("Types of secrets supported.") +union SecretType { + string, + @doc("If the secret is stored in an Azure Key Vault.") "AKV_SECRET_URI", + @doc("If the secret value provided as plain text.") "SECRET_VALUE", +} + +@doc("Types of certificates supported.") +union CertificateType { + string, + @doc("If the certificate is stored in an Azure Key Vault.") "AKV_CERT_URI", +} + +@doc("Types of file supported.") +union FileType { + string, + + @doc("If the file is a JMX script.") + "JMX_FILE", + + @doc("If the file is a user properties file.") + "USER_PROPERTIES", + + @doc("If the file is not among any of the other supported file types.") + "ADDITIONAL_ARTIFACTS", + + @added(APIVersions.v2023_04_01_preview) + @doc("If the file is a compressed archive containing a collection of various artifacts or resources.") + "ZIPPED_ARTIFACTS", + + @added(APIVersions.v2023_04_01_preview) + @doc("If the file is a JSON config file to define the requests for a URL test.") + "URL_TEST_CONFIG", + + @added(APIVersions.v2024_03_01_preview) + @doc("If the file is a test script.") + "TEST_SCRIPT", +} + +@doc("File status.") +union FileStatus { + string, + @doc("File is not validated.") "NOT_VALIDATED", + @doc("File is validated.") "VALIDATION_SUCCESS", + @doc("File validation is failed.") "VALIDATION_FAILURE", + @doc("File validation is in progress.") "VALIDATION_INITIATED", + @doc("Validation is not required.") "VALIDATION_NOT_REQUIRED", +} + +@doc("Test result based on pass/fail criteria.") +union PFTestResult { + string, + @doc("Pass/fail criteria has passed.") "PASSED", + @doc("Pass/fail criteria is not applicable.") "NOT_APPLICABLE", + @doc("Pass/fail criteria has failed.") "FAILED", +} + +@doc("Test run status.") +union Status { + string, + @doc("Test run request is accepted.") "ACCEPTED", + @doc("Test run is not yet started.") "NOTSTARTED", + @doc("Test run is provisioning.") "PROVISIONING", + @doc("Test run is provisioned.") "PROVISIONED", + @doc("Test run is getting configured.") "CONFIGURING", + @doc("Test run configuration is done.") "CONFIGURED", + @doc("Test run has started executing.") "EXECUTING", + @doc("Test run execution is completed.") "EXECUTED", + @doc("Test run is getting deprovisioned.") "DEPROVISIONING", + @doc("Test run is deprovisioned.") "DEPROVISIONED", + @doc("Test run is completed.") "DONE", + @doc("Test run is being cancelled.") "CANCELLING", + @doc("Test run request is cancelled.") "CANCELLED", + @doc("Test run request is failed.") "FAILED", + @doc("Test run JMX file is validated.") "VALIDATION_SUCCESS", + @doc("Test run JMX file validation is failed.") "VALIDATION_FAILURE", +} + +@doc("Aggregation type.") +union AggregationType { + string, + @doc("Average value.") "Average", + @doc("Total count.") "Count", + @doc("Aggregation will be average in this case.") "None", + @doc("Total sum.") "Total", + + @doc("75th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile75", + + @doc("90th percentile.") "Percentile90", + @doc("95th percentile.") "Percentile95", + + @doc("96th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile96", + + @doc("97th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile97", + + @doc("98th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile98", + + @doc("99th percentile.") "Percentile99", + + @doc("99.9th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile999", + + @doc("99.99th percentile.") + @added(APIVersions.v2024_05_01_preview) + "Percentile9999", +} + +@doc("Metric unit.") +union MetricUnit { + string, + @doc("No unit specified.") "NotSpecified", + @doc("Percentage.") "Percent", + @doc("Value count.") "Count", + @doc("Seconds.") "Seconds", + @doc("Milliseconds") "Milliseconds", + @doc("Bytes") "Bytes", + @doc("Bytes per second") "BytesPerSecond", + @doc("Count per second") "CountPerSecond", +} + +@doc("Time Grain") +union TimeGrain { + string, + + @doc("5 seconds, available only if test run duration is less than 10 minutes.") + PT5S: "PT5S", + + @doc("10 seconds, available only if test run duration is less than 10 minutes.") + PT10S: "PT10S", + + @doc("1 minute") + PT1M: "PT1M", + + @doc("5 minutes, available only if test run duration is greater than 1 minute.") + PT5M: "PT5M", + + @doc("1 hour, available only if test run duration is greater than 1 minute.") + PT1H: "PT1H", +} + +@added(APIVersions.v2023_04_01_preview) +@doc("Test kind") +union TestKind { + string, + + @doc("URL Test") + "URL", + + @doc("JMX Test") + "JMX", + + @added(APIVersions.v2024_03_01_preview) + @doc("Locust Test") + "Locust", +} + +@doc("Test file info.") +@resource("files") +@parentResource(Test) +model TestFileInfo is FileInfo; + +@doc("Test run file info.") +@resource("files") +@parentResource(TestRun) +model TestRunFileInfo is FileInfo; + +@doc("Load test model.") +@resource("tests") model Test { @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; + @added(APIVersions.v2023_04_01_preview) + @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") + autoStopCriteria?: AutoStopCriteria; + @doc(""" -Secrets can be stored in an Azure Key Vault or any other secret store. If the -secret is stored in an Azure Key Vault, the value should be the secret -identifier and the type should be AKV_SECRET_URI. If the secret is stored -elsewhere, the secret value should be provided directly and the type should be -SECRET_VALUE. -""") + Secrets can be stored in an Azure Key Vault or any other secret store. If the + secret is stored in an Azure Key Vault, the value should be the secret + identifier and the type should be AKV_SECRET_URI. If the secret is stored + elsewhere, the secret value should be provided directly and the type should be + SECRET_VALUE. + """) secrets?: Record; - @doc("Certificates metadata") + @doc("Certificates metadata.") certificate?: CertificateMetadata; @doc("Environment variables which are defined as a set of pairs.") @@ -155,44 +286,44 @@ SECRET_VALUE. @doc("The load test configuration.") loadTestConfiguration?: LoadTestConfiguration; + @added(APIVersions.v2023_04_01_preview) + @doc("Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs") + baselineTestRunId?: string; + @doc("The input artifacts for the test.") @visibility("read") inputArtifacts?: TestInputArtifacts; - @doc("Unique test name as identifier.") - @visibility("read") - testId?: string; + ...TestIdPathParameter; + @maxLength(100) @doc("The test description.") description?: string; + @maxLength(50) + @minLength(2) @doc("Display name of a test.") displayName?: string; @doc("Subnet ID on which the load test instances should run.") subnetId?: string; + @added(APIVersions.v2023_04_01_preview) + @doc("Kind of test.") + kind?: TestKind; + + #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" + @added(APIVersions.v2023_04_01_preview) + @doc("Inject load test engines without deploying public IP for outbound access") + publicIPDisabled?: boolean; + @doc("Type of the managed identity referencing the Key vault.") keyvaultReferenceIdentityType?: string; @doc("Resource Id of the managed identity referencing the Key vault.") keyvaultReferenceIdentityId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc("Pass fail criteria for a test.") @@ -207,11 +338,11 @@ model PassFailMetric { clientMetric?: PFMetrics; @doc(""" -The aggregation function to be applied on the client metric. Allowed functions -- ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, -‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, -‘count’ - for requests -""") + The aggregation function to be applied on the client metric. Allowed functions + - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, + ‘count’ - for requests + """) aggregate?: PFAgFunc; @doc("The comparison operator. Supported types ‘>’, ‘<’ ") @@ -221,17 +352,17 @@ The aggregation function to be applied on the client metric. Allowed functions requestName?: string; @doc(""" -The value to compare with the client metric. Allowed values - ‘error : [0.0 , -100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. -""") - value?: float32; + The value to compare with the client metric. Allowed values - ‘error : [0.0 , + 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. + """) + value?: float64; @doc("Action taken after the threshold is met. Default is ‘continue’.") - action?: PFAction; + action?: PFAction = PFAction.continue; @doc("The actual value of the client metric for the test run.") @visibility("read") - actualValue?: float32; + actualValue?: float64; @doc("Outcome of the test run.") @visibility("read") @@ -259,165 +390,170 @@ model CertificateMetadata { name?: string; } -@doc("The load test configuration.") +@added(APIVersions.v2023_04_01_preview) +@doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") +model AutoStopCriteria { + @doc("Whether auto-stop should be disabled. The default value is false.") + autoStopDisabled?: boolean = false; + + @doc("Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0") + errorRate?: float32 = 90; + + @doc("Time window during which the error percentage should be evaluated in seconds.") + errorRateTimeWindowInSeconds?: int32 = 60; +} + +@doc("Configurations for the load test.") model LoadTestConfiguration { @doc(""" -The number of engine instances to execute load test. Supported values are in -range of 1-45. Required for creating a new test. -""") + The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. + """) engineInstances?: int32; + #suppress "@azure-tools/typespec-azure-core/casing-style" "CSV is an abbervation and should be all caps" @doc(""" -If false, Azure Load Testing copies and processes your input files unmodified -across all test engine instances. If true, Azure Load Testing splits the CSV -input data evenly across all engine instances. If you provide multiple CSV -files, each file will be split evenly. -""") - splitAllCSVs?: boolean; + If false, Azure Load Testing copies and processes your input files unmodified + across all test engine instances. If true, Azure Load Testing splits the CSV + input data evenly across all engine instances. If you provide multiple CSV + files, each file will be split evenly. + """) + splitAllCSVs?: boolean = false; @doc(""" -If true, optionalLoadTestConfig is required and JMX script for the load test is -not required to upload. -""") - quickStartTest?: boolean; + If true, optionalLoadTestConfig is required and JMX script for the load test is + not required to upload. + """) + quickStartTest?: boolean = false; - @doc("Optional load test config") + @doc("Configuration for quick load test") optionalLoadTestConfig?: OptionalLoadTestConfig; + + @added(APIVersions.v2024_03_01_preview) + @doc("Region distribution configuration for the load test.") + regionalLoadTestConfig?: RegionalConfiguration[]; } -@doc("Optional load test config") -model OptionalLoadTestConfig { +@doc("Region distribution configuration for the load test.") +model RegionalConfiguration { + @doc(""" + The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. + """) + engineInstances: int32; + @doc(""" -Test URL. Provide the complete HTTP URL. For example, -http://contoso-app.azurewebsites.net/login -""") + Azure region name. + The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + """) + region: string; +} + +@doc("Configuration for quick load test") +model OptionalLoadTestConfig { + @doc("Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login") endpointUrl?: string; - @doc("No of concurrent virtual users") + @doc("Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it.") + @added(APIVersions.v2023_04_01_preview) + requestsPerSecond?: int32; + + @doc("Maximum response time in milliseconds of the API/endpoint.") + @added(APIVersions.v2023_04_01_preview) + maxResponseTimeInMs?: int32; + + @doc("No of concurrent virtual users.") virtualUsers?: int32; - @doc("Ramp up time") + @doc("Ramp up time in seconds.") rampUpTime?: int32; - @doc("Test run duration") + @doc("Test run duration in seconds.") duration?: int32; } @doc("The input artifacts for the test.") model TestInputArtifacts { @doc("File info") - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; @doc("File info") - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; @doc("File info") - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; @doc("File info") - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + + @added(APIVersions.v2023_04_01_preview) + @doc("The config json file for url based test") + urlTestConfigFileInfo?: TestFileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: FileInfo[]; + additionalFileInfo?: TestFileInfo[]; } @doc("File info") model FileInfo { - @doc("File URL.") - url?: string; - @doc("Name of the file.") - fileName?: string; + @key + @visibility + fileName: string; + + @doc("File URL.") + //update description + @visibility("read") + url?: url; @doc("File type") + @visibility("read") fileType?: FileType; - @doc("Expiry time of the file (ISO 8601 literal format)") - expireDateTime?: offsetDateTime; + @doc("Expiry time of the file (RFC 3339 literal format)") + @visibility("read") + expireDateTime?: utcDateTime; @doc("Validation status of the file") + @visibility("read") validationStatus?: FileStatus; @doc("Validation failure error details") + @visibility("read") validationFailureDetails?: string; } -@doc("The definition of an error object.") -@error -model ErrorResponseBody { - @doc("Error from a REST request.") - error: Error; -} - -@doc("Error from a REST request.") -model Error { - @doc("The error code.") - code: string; - - @doc("The error message.") - message: string; - - @doc("The error target.") - target?: string; - - @doc("Additional details and inner errors.") - details?: Error[]; -} - -@doc("Collection of tests") -model TestsList is Azure.Core.Page; - -@doc("Collection of files.") -model FileInfoList is Azure.Core.Page; - -@doc("Test app component") +@doc("Test app components") model TestAppComponents { @doc(""" -Azure resource collection { resource id (fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) -: resource object } -""") + Azure resource collection { resource id (fully qualified resource Id e.g + subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + : resource object } + """) components: Record; @doc("Test identifier") @visibility("read") testId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc(""" -An Azure resource object (Refer azure generic resource model : -https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) -""") + An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + """) model AppComponent { @doc(""" -fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} -""") + fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + """) @visibility("read") - resourceId?: string; + resourceId: string; @doc("Azure resource name, required while creating the app component.") - resourceName?: string; + resourceName: string; @doc("Azure resource type, required while creating the app component.") - resourceType?: string; + resourceType: string; @doc("Azure resource display name") displayName?: string; @@ -441,34 +577,20 @@ model TestServerMetricConfig { testId?: string; @doc(""" -Azure resource metrics collection {metric id : metrics object} (Refer : -https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition -for metric id). -""") - metrics?: Record; - - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; + Azure resource metrics collection {metric id : metrics object} (Refer : + https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + for metric id). + """) + metrics: Record; - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc(""" -Associated metric definition for particular metrics of the azure resource ( -Refer : -https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). -""") + Associated metric definition for particular metrics of the azure resource ( + Refer : + https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition). + """) model ResourceMetric { @doc("Unique name for metric.") @visibility("read") @@ -498,28 +620,23 @@ model ResourceMetric { @doc("Load test run model") @resource("test-runs") -model TestRuns { - // FIXME: is testRunId optional or required in the response? Resource key and path params cannot be optional - @key - @doc("Unique test run name as identifier") - @visibility("read") - testRunId: string; -} - -@doc("Load test run model") model TestRun { - ...TestRuns, + ...TestRunIdPathParameter; @doc("Pass fail criteria for a test.") passFailCriteria?: PassFailCriteria; + @doc("Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window.") + @added(APIVersions.v2023_04_01_preview) + autoStopCriteria?: AutoStopCriteria; + @doc(""" -Secrets can be stored in an Azure Key Vault or any other secret store. If the -secret is stored in an Azure Key Vault, the value should be the secret -identifier and the type should be AKV_SECRET_URI. If the secret is stored -elsewhere, the secret value should be provided directly and the type should be -SECRET_VALUE. -""") + Secrets can be stored in an Azure Key Vault or any other secret store. If the + secret is stored in an Azure Key Vault, the value should be the secret + identifier and the type should be AKV_SECRET_URI. If the secret is stored + elsewhere, the secret value should be provided directly and the type should be + SECRET_VALUE. + """) secrets?: Record; @doc("Certificates metadata") @@ -532,10 +649,23 @@ SECRET_VALUE. @visibility("read") errorDetails?: ErrorDetails[]; - @doc("Test run statistics.") + @doc(""" + Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + The sampler name is the same as the name mentioned in the test script. + Sampler name "Total" represents the aggregated statistics of all the samplers. + """) @visibility("read") testRunStatistics?: Record; + @doc(""" + Regional statistics. Key is the Azure region name and value is the test run statistics. + The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + """) + @visibility("read") + @added(APIVersions.v2024_03_01_preview) + regionalStatistics?: Record; + @doc("The load test configuration.") loadTestConfiguration?: LoadTestConfiguration; @@ -551,12 +681,17 @@ SECRET_VALUE. @visibility("read") virtualUsers?: int32; + @maxLength(50) + @minLength(2) @doc("Display name of a testRun.") displayName?: string; + @maxLength(50) + @minLength(2) @doc("Associated test Id.") testId?: string; + @maxLength(100) @doc("The test run description.") description?: string; @@ -564,17 +699,17 @@ SECRET_VALUE. @visibility("read") status?: Status; - @doc("The test run start DateTime(ISO 8601 literal format).") + @doc("The test run start DateTime(RFC 3339 literal format).") @visibility("read") - startDateTime?: offsetDateTime; + startDateTime?: utcDateTime; - @doc("The test run end DateTime(ISO 8601 literal format).") + @doc("The test run end DateTime(RFC 3339 literal format).") @visibility("read") - endDateTime?: offsetDateTime; + endDateTime?: utcDateTime; @doc("Test run initiated time.") @visibility("read") - executedDateTime?: offsetDateTime; + executedDateTime?: utcDateTime; @doc("Portal url.") @visibility("read") @@ -582,27 +717,32 @@ SECRET_VALUE. @doc("Test run duration in milliseconds.") @visibility("read") - duration?: int32; + duration?: int64; @doc("Subnet ID on which the load test instances should run.") @visibility("read") subnetId?: string; - @doc("The creation datetime(ISO 8601 literal format).") + @added(APIVersions.v2023_04_01_preview) + @doc("Type of test.") @visibility("read") - createdDateTime?: offsetDateTime; + kind?: TestKind; - @doc("The user that created.") - @visibility("read") - createdBy?: string; + @added(APIVersions.v2024_05_01_preview) + @doc("Request data collection level for test run") + requestDataLevel?: RequestDataLevel; - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; + @added(APIVersions.v2024_05_01_preview) + @doc("Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise") + debugLogsEnabled?: boolean; - @doc("The user that last modified.") + #suppress "@azure-tools/typespec-azure-core/casing-style" "IP is an abbervation and should be all caps" + @added(APIVersions.v2023_04_01_preview) + @doc("Inject load test engines without deploying public IP for outbound access") @visibility("read") - lastModifiedBy?: string; + publicIPDisabled?: boolean; + + ...SystemMetaData; } @doc("Error details if there is any failure in load test run") @@ -620,55 +760,87 @@ model TestRunStatistics { @doc("Sampler count.") @visibility("read") - sampleCount?: float32; + sampleCount?: float64; @doc("Error count.") @visibility("read") - errorCount?: float32; + errorCount?: float64; @doc("Error percentage.") @visibility("read") - errorPct?: float32; + errorPct?: float64; @doc("Mean response time.") @visibility("read") - meanResTime?: float32; + meanResTime?: float64; @doc("Median response time.") @visibility("read") - medianResTime?: float32; + medianResTime?: float64; @doc("Max response time.") @visibility("read") - maxResTime?: float32; + maxResTime?: float64; @doc("Minimum response time.") @visibility("read") - minResTime?: float32; + minResTime?: float64; @doc("90 percentile response time.") @visibility("read") - pct1ResTime?: float32; + pct1ResTime?: float64; @doc("95 percentile response time.") @visibility("read") - pct2ResTime?: float32; + pct2ResTime?: float64; @doc("99 percentile response time.") @visibility("read") - pct3ResTime?: float32; + pct3ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("75 percentile response time.") + @visibility("read") + pct75ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("96 percentile response time.") + @visibility("read") + pct96ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("97 percentile response time.") + @visibility("read") + pct97ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("98 percentile response time.") + @visibility("read") + pct98ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("99.9 percentile response time.") + @visibility("read") + pct999ResTime?: float64; + + @added(APIVersions.v2024_05_01_preview) + @doc("99.99 percentile response time.") + @visibility("read") + pct9999ResTime?: float64; @doc("Throughput.") @visibility("read") - throughput?: float32; + throughput?: float64; + #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Received network bytes.") @visibility("read") - receivedKBytesPerSec?: float32; + receivedKBytesPerSec?: float64; + #suppress "@azure-tools/typespec-azure-core/casing-style" "KBytes is expected" @doc("Send network bytes.") @visibility("read") - sentKBytesPerSec?: float32; + sentKBytesPerSec?: float64; } @doc("Collection of test run artifacts") @@ -684,33 +856,52 @@ model TestRunArtifacts { @doc("The input artifacts for the test run.") model TestRunInputArtifacts { @doc("File info") - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; @doc("File info") - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; @doc("File info") - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; @doc("File info") - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + + @added(APIVersions.v2023_04_01_preview) + @doc("The config json file for url based test") + urlTestConfigFileInfo?: TestRunFileInfo; @doc("Additional supported files for the test run") @visibility("read") - additionalFileInfo?: FileInfo[]; + additionalFileInfo?: TestRunFileInfo[]; } @doc("The output artifacts for the test run.") model TestRunOutputArtifacts { @doc("File info") - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; @doc("File info") - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + + @doc("The container for test run artifacts.") + @added(APIVersions.v2023_04_01_preview) + artifactsContainerInfo?: ArtifactsContainerInfo; + + @added(APIVersions.v2024_05_01_preview) + @doc("The report file for the test run.") + reportFileInfo?: TestRunFileInfo; } -@doc("Collection of test runs") -model TestRunsList is Azure.Core.Page; +@doc("Artifacts container info.") +@added(APIVersions.v2023_04_01_preview) +model ArtifactsContainerInfo { + @doc("This is a SAS URI to an Azure Storage Container that contains the test run artifacts.") + url?: url; + + @doc("Expiry time of the container (RFC 3339 literal format)") + expireDateTime?: utcDateTime; +} @doc("Represents collection of metric namespaces.") model MetricNamespaceCollection { @@ -757,9 +948,9 @@ model MetricDefinition { unit?: MetricUnit; @doc(""" -Metric availability specifies the time grain (aggregation interval or -frequency). -""") + Metric availability specifies the time grain (aggregation interval or + frequency). + """) metricAvailabilities?: MetricAvailability[]; } @@ -775,20 +966,20 @@ model NameAndDesc { @doc("Metric availability specifies the time grain (aggregation interval or frequency)") model MetricAvailability { @doc(""" -The time grain specifies the aggregation interval for the metric. Expressed as -a duration 'PT1M', 'PT1H', etc. -""") + The time grain specifies the aggregation interval for the metric. Expressed as + a duration 'PT1M', 'PT1H', etc. + """) timeGrain?: TimeGrain; } -@doc("Filters to fetch the set of metric") +@doc("Filters to fetch the set of metric.") model MetricRequestPayload { @doc(""" -Get metrics for specific dimension values. Example: Metric contains dimension -like SamplerName, Error. To retrieve all the time series data where SamplerName -is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be -{\"SamplerName\", [\"HTTPRequest1\", \"HTTPRequest2\"} -""") + Get metrics for specific dimension values. Example: Metric contains dimension + like SamplerName, Error. To retrieve all the time series data where SamplerName + is equals to HTTPRequest1 or HTTPRequest2, the DimensionFilter value will be + {\"SamplerName\", [\"HTTPRequest1\", \"HTTPRequest2\"} + """) filters?: DimensionFilter[]; } @@ -802,6 +993,8 @@ model DimensionFilter { } @doc("The response to a metrics query.") +@friendlyName("Metrics") +// using friendlyName to change the name of the model due to issue in using projectedName '@encodedName("application/json", "Metrics")' https://github.com/microsoft/typespec/issues/2276 model Metrics is Azure.Core.Page; @doc("The time series returned when a data query is performed.") @@ -815,11 +1008,11 @@ model TimeSeriesElement { @doc("Represents a metric value.") model MetricValue { - @doc("The timestamp for the metric value in ISO 8601 format.") - timestamp?: string; + @doc("The timestamp for the metric value in RFC 3339 format.") + timestamp?: utcDateTime; @doc("The metric value.") - value?: float32; + value?: float64; } @doc("Represents a metric dimension value.") @@ -831,71 +1024,56 @@ model DimensionValue { value?: string; } -@resource("values") -@parentResource(Dimension) +@doc("Metrics dimension values.") model DimensionValueList { - @key - value: string[]; -} + @doc("The dimension name") + @visibility("read") + @added(APIVersions.v2023_04_01_preview) + name?: string; -@resource("metric-dimensions") -@parentResource(TestRuns) -model Dimension { - @key - @doc("Dimension name") - @visibility("query") - name: string; + @doc("The dimension value") + value?: string[]; + + @doc("Link for the next set of values in case of paginated results, if applicable.") + nextLink?: ResourceLocation; } -model MetricDimensions { - @doc("The interval (i.e. timegrain) of the query.") +@doc("Metric Dimensions") +model MetricDimensionsRequest { + @doc("Metric name") @query - interval?: Interval; + metricname: string; - @doc("Metric name") + @doc("The interval (i.e. timegrain) of the query.") @query - metricName?: string; + interval?: TimeGrain = TimeGrain.PT1M; @doc("Metric namespace to query metric definitions for.") @query metricNamespace: string; @doc(""" - The timespan of the query. It is a string with the following format - 'startDateTime_ISO/endDateTime_ISO'. - """) + The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. + """) @query - timespan?: string; -}; + @clientName("time_interval", "python") + timespan: string; +} @doc("Test run app component") model TestRunAppComponents { @doc(""" -Azure resource collection { resource id (fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) -: resource object } -""") + Azure resource collection { resource id (fully qualified resource Id e.g + subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}) + : resource object } + """) components: Record; @doc("Test run identifier") @visibility("read") testRunId?: string; - @doc("The creation datetime(ISO 8601 literal format).") - @visibility("read") - createdDateTime?: offsetDateTime; - - @doc("The user that created.") - @visibility("read") - createdBy?: string; - - @doc("The last Modified datetime(ISO 8601 literal format).") - @visibility("read") - lastModifiedDateTime?: offsetDateTime; - - @doc("The user that last modified.") - @visibility("read") - lastModifiedBy?: string; + ...SystemMetaData; } @doc("Test run server metrics configuration") @@ -905,29 +1083,154 @@ model TestRunServerMetricConfig { testRunId?: string; @doc(""" -Azure resource metrics collection {metric id : metrics object} (Refer : -https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition -for metric id). -""") + Azure resource metrics collection {metric id : metrics object} (Refer : + https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition + for metric id). + """) metrics?: Record; - @doc("The creation datetime(ISO 8601 literal format).") + ...SystemMetaData; +} + +@doc("Query parameters for list test run operation") +model OldTestRunIdQueryParam { + @doc(""" + Existing test run identifier that should be rerun, if this is provided, the + test will run with the JMX file, configuration and app components from the + existing test run. You can override the configuration values for new test run + in the request body. + """) + @query + oldTestRunId?: string; +} + +@doc("Parameters for list test run operation") +model ListTestRunQueryParams { + @doc(""" + Sort on the supported fields in (field asc/desc) format. eg: executedDateTime + asc. Supported fields - executedDateTime + """) + @query + orderby?: string; + + @doc(""" + Prefix based, case sensitive search on searchable fields - description, + executedUser. For example, to search for a test run, with description 500 VUs, + the search parameter can be 500. + """) + @query + search?: string; + + @doc("Unique name of an existing load test.") + @query + testId?: string; + + @doc("Start DateTime(RFC 3339 literal format) of test-run execution time filter range.") + @query + executionFrom?: utcDateTime; + + @doc("End DateTime(RFC 3339 literal format) of test-run execution time filter range.") + @query + executionTo?: utcDateTime; + + @doc("Comma separated list of test run status.") + @query + status?: string; + + @doc("Number of results in response.") + @query + maxpagesize?: int32 = 50; +} + +@doc("Parameters for list test operation") +model ListTestQueryParams { + @doc(""" + Sort on the supported fields in (field asc/desc) format. eg: + lastModifiedDateTime asc. Supported fields - lastModifiedDateTime + """) + @query + orderby?: string; + + @doc(""" + Prefix based, case sensitive search on searchable fields - displayName, + createdBy. For example, to search for a test, with display name is Login Test, + the search parameter can be Login. + """) + @query + search?: string; + + @doc(""" + Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. + """) + @query + lastModifiedStartTime?: utcDateTime; + + @doc(""" + End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. + """) + @query + lastModifiedEndTime?: utcDateTime; + + @doc("Number of results in response.") + @query + maxpagesize?: int32 = 50; +} + +@doc("System metadata.") +model SystemMetaData { + @doc("The creation datetime(RFC 3339 literal format).") @visibility("read") - createdDateTime?: offsetDateTime; + createdDateTime?: utcDateTime; @doc("The user that created.") @visibility("read") createdBy?: string; - @doc("The last Modified datetime(ISO 8601 literal format).") + @doc("The last Modified datetime(RFC 3339 literal format).") @visibility("read") - lastModifiedDateTime?: offsetDateTime; + lastModifiedDateTime?: utcDateTime; @doc("The user that last modified.") @visibility("read") lastModifiedBy?: string; } -alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & T; +@doc("Test Id path parameter.") +model TestIdPathParameter { + @doc("Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @maxLength(50) + @minLength(2) + @key + @visibility("read") + @pattern("^[a-z0-9_-]*$") + testId: string; +} + +@doc("Test run Id path parameter.") +model TestRunIdPathParameter { + @doc("Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters.") + @visibility("read") + @maxLength(50) + @minLength(2) + @key + @pattern("^[a-z0-9_-]*$") + testRunId: string; +} + +@added(APIVersions.v2024_05_01_preview) +@doc("Request data collection level for test run") +union RequestDataLevel { + string, + + @doc("No request data will be collected") + NONE: "NONE", + + @doc("Request data will be collected in case of failed requests") + ERRORS: "ERRORS", +} + +alias ResourceCreatedResponse = TypeSpec.Http.Response<201> & + T; -alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | TypeSpec.Http.Response<200> & T; +alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | (TypeSpec.Http.Response<200> & + T); diff --git a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp index fd8f628931..eccc08c3d8 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp @@ -1,136 +1,82 @@ import "@azure-tools/typespec-azure-core"; import "@typespec/rest"; +import "@typespec/http"; +import "@typespec/openapi"; +import "@azure-tools/typespec-client-generator-core"; import "./models.tsp"; +import "./models.testprofile.tsp"; using Azure.Core; using Azure.Core.Traits; using TypeSpec.Rest; using TypeSpec.Http; +using TypeSpec.Versioning; +using OpenAPI; +using Azure.ClientGenerator.Core; -namespace AzureLoadTesting; +namespace Microsoft.LoadTestService; +@@encodedName(Azure.Core.Foundations.ResourceBody.resource, + "application/json", + "body" +); +@@clientName(Azure.Core.Foundations.ResourceBody.resource, "body"); + +@tag("Test") interface LoadTestAdministration { - @summary("Create a new test or update an existing test.") - @doc("Create a new test or update an existing test.") - @route("/tests/{testId}") - @patch - CreateOrUpdateTest is Azure.Core.Foundations.Operation< - { - @header contentType: "application/merge-patch+json", - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; + @summary("Create a new test or update an existing test by providing the test Id.") + @doc("Create a new test or update an existing test by providing the test Id.") + createOrUpdateTest is StandardResourceOperations.ResourceCreateOrUpdate; - @doc("Load test model") - @body - body: Test; - }, - ResourceCreatedOrOkResponse - >; + @summary("Delete a test by its test Id.") + @doc("Delete a test by its test Id.") + deleteTest is StandardResourceOperations.ResourceDelete; - @summary("Delete a test by its name.") - @doc("Delete a test by its name.") - @route("/tests/{testId}") - @delete - DeleteTest is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - void - >; - - @summary("Get load test details by test name") - @doc("Get load test details by test name") - @route("/tests/{testId}") - @get - GetTest is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - Test - >; + @summary("Get load test details by test Id") + @doc("Get load test details by test Id") + getTest is StandardResourceOperations.ResourceRead; @summary(""" -Get all load tests by the fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. -""") + Get all load tests by the fully qualified resource Id e.g + subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. + """) @doc(""" -Get all load tests by the fully qualified resource Id e.g -subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. -""") - @route("/tests") - @get - ListTests is Azure.Core.Foundations.Operation< - { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: -lastModifiedDateTime asc. Supported fields - lastModifiedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - displayName, -createdBy. For example, to search for a test, with display name is Login Test, -the search parameter can be Login. -""") - @query - search?: string; - - @doc(""" -Start DateTime(ISO 8601 literal format) of the last updated time range to -filter tests. -""") - @query - lastModifiedStartTime?: offsetDateTime; - - @doc(""" -End DateTime(ISO 8601 literal format) of the last updated time range to filter -tests. -""") - @query - lastModifiedEndTime?: offsetDateTime; - - @doc("Number of results in response.") - @query - maxpagesize?: int32; - }, - TestsList + Get all load tests by the fully qualified resource Id e.g + subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. + """) + listTests is StandardResourceOperations.ResourceList< + Test, + ListQueryParametersTrait >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" "Our operation is not following the standard put behavior https://github.com/Azure/typespec-azure/issues/3743" + #suppress "@azure-tools/typespec-azure-core/byos" "It is limiting for users to have storage first before creating a load test also it will be breaking change for us." @summary(""" -Upload input file for a given test name. File size can't be more than 50 MB. -Existing file with same name for the given test will be overwritten. File -should be provided in the request body as application/octet-stream. -""") + Upload input file for a given test Id. File size can't be more than 50 MB. + Existing file with same name for the given test will be overwritten. File + should be provided in the request body as application/octet-stream. + """) @doc(""" -Upload input file for a given test name. File size can't be more than 50 MB. -Existing file with same name for the given test will be overwritten. File -should be provided in the request body as application/octet-stream. -""") + Upload input file for a given test Id. File size can't be more than 50 MB. + Existing file with same name for the given test will be overwritten. File + should be provided in the request body as application/octet-stream. + """) @route("/tests/{testId}/files/{fileName}") @put - UploadTestFile is Azure.Core.Foundations.Operation< + uploadTestFile is Azure.Core.Foundations.Operation< { - @header contentType: "application/octet-stream", + @header + @doc("Content type.") + contentType: "application/octet-stream"; + @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("Unique name for test file with file extension like : App.jmx") @@ -142,439 +88,424 @@ numeric, underscore or hyphen characters. fileType?: FileType; @doc("The file content as application/octet-stream.") - @body + @bodyRoot body: bytes; }, - ResourceCreatedResponse + ResourceCreatedResponse >; - @summary("Get test file by the file name.") - @doc("Get test file by the file name.") - @route("/tests/{testId}/files/{fileName}") - @get - GetTestFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - - @doc("File name with file extension like app.jmx") - @path - fileName: string; - }, - FileInfo - >; + @summary("Get all the files that are associated with a test.") + @doc("Get all the files that are associated with a test.") + getTestFile is StandardResourceOperations.ResourceRead; @summary("Delete file by the file name for a test") @doc("Delete file by the file name for a test") - @route("/tests/{testId}/files/{fileName}") - @delete - DeleteTestFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - - @doc("File name with file extension like app.jmx") - @path - fileName: string; - }, - void - >; + deleteTestFile is StandardResourceOperations.ResourceDelete; @summary("Get all test files.") @doc("Get all test files.") - @route("/tests/{testId}/files") - @get - ListTestFiles is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testId: string; - }, - FileInfoList - >; + listTestFiles is StandardResourceOperations.ResourceList; - @summary("Associate an app component (collection of azure resources) to a test") - @doc("Associate an app component (collection of azure resources) to a test") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Add an app component to a test.") + @doc("Add an app component to a test by providing the resource Id, name and type.") @route("/tests/{testId}/app-components") @patch - CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< + createOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("App Component model.") - @body + @bodyRoot body: TestAppComponents; }, ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Get associated app component (collection of azure resources) for the given test.") @doc("Get associated app component (collection of azure resources) for the given test.") @route("/tests/{testId}/app-components") @get - GetAppComponents is Azure.Core.Foundations.Operation< + getAppComponents is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; }, TestAppComponents >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test") @doc("Configure server metrics for a test") @route("/tests/{testId}/server-metrics-config") @patch - CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; @doc("Server metric configuration model.") - @body + @bodyRoot body: TestServerMetricConfig; }, ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List server metrics configuration for the given test.") @doc("List server metrics configuration for the given test.") @route("/tests/{testId}/server-metrics-config") @get - GetServerMetricsConfig is Azure.Core.Foundations.Operation< + getServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testId: string; }, TestServerMetricConfig >; } +@tag("TestRun") interface LoadTestRun { - @summary("Delete a test run by its name.") - @doc("Delete a test run by its name.") - @route("/test-runs/{testRunId}") - @delete - DeleteTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - void - >; - - @summary("Create and start a new test run with the given name.") - @doc("Create and start a new test run with the given name.") - // @pollingOperation(LoadTestRun.GetTestRun) - CreateOrUpdateTestRun is LongRunningResourceCreateOrUpdate< - TestRun, - QueryParametersTrait< - { - @doc(""" - Existing test run identifier that should be rerun, if this is provided, the - test will run with the JMX file, configuration and app components from the - existing test run. You can override the configuration values for new test run - in the request body. - """) - @query - oldTestRunId?: string; - } - > + @summary("Get test run details by test run Id.") + @doc("Get test run details by test run Id.") + getTestRun is StandardResourceOperations.ResourceRead; + + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Create and start a new test run with the given test run Id.") + @doc("Create and start a new test run with the given test run Id.") + createOrUpdateTestRun is StandardResourceOperations.ResourceCreateOrUpdate< + TestRun, + QueryParametersTrait >; + @summary("Delete an existing load test run.") + @doc("Delete an existing load test run by providing the testRunId.") + deleteTestRun is StandardResourceOperations.ResourceDelete; - @summary("Get test run details by name.") - @doc("Get test run details by name.") - @route("/test-runs/{testRunId}") - @get - GetTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - TestRun + @summary("Get all test runs for the given filters.") + @doc("Get all test runs for the given filters.") + listTestRuns is StandardResourceOperations.ResourceList< + TestRun, + ListQueryParametersTrait >; @summary("Get test run file by file name.") @doc("Get test run file by file name.") - @route("/test-runs/{testRunId}/files/{fileName}") - @get - GetTestRunFile is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - - @doc("Test run file name with file extension") - @path - fileName: string; - }, - FileInfo - >; - - @summary("Get all test runs with given filters") - @doc("Get all test runs with given filters") - @route("/test-runs") - @get - ListTestRuns is Azure.Core.Foundations.Operation< - { - @doc(""" -Sort on the supported fields in (field asc/desc) format. eg: executedDateTime -asc. Supported fields - executedDateTime -""") - @query - orderby?: string; - - @doc(""" -Prefix based, case sensitive search on searchable fields - description, -executedUser. For example, to search for a test run, with description 500 VUs, -the search parameter can be 500. -""") - @query - search?: string; - - @doc("Unique name of an existing load test.") - @query - testId?: string; - - @doc("Start DateTime(ISO 8601 literal format) of test-run execution time filter range.") - @query - executionFrom?: offsetDateTime; - - @doc("End DateTime(ISO 8601 literal format) of test-run execution time filter range.") - @query - executionTo?: offsetDateTime; - - @doc("Comma separated list of test run status.") - @query - status?: string; - - @doc("Number of results in response.") - @query - maxpagesize?: int32; - }, - TestRunsList - >; + getTestRunFile is StandardResourceOperations.ResourceRead; - @summary("Stop test run by name.") - @doc("Stop test run by name.") - @route("/test-runs/{testRunId}:stop") - @post - StopTestRun is Azure.Core.Foundations.Operation< - { - @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") - @path - testRunId: string; - }, - TestRun - >; + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + @summary("Stop test run by test run Id.") + @doc("Stop test run by test run Id.") + @operationId("LoadTestRun_StopTestRun") + stop is StandardResourceOperations.ResourceAction; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric namespaces for a load test run.") @doc("List the metric namespaces for a load test run.") @route("/test-runs/{testRunId}/metric-namespaces") @get - ListMetricNamespaces is Azure.Core.Foundations.Operation< + listMetricNamespaces is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, MetricNamespaceCollection >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric definitions for a load test run.") @doc("List the metric definitions for a load test run.") @route("/test-runs/{testRunId}/metric-definitions") @get - ListMetricDefinitions is Azure.Core.Foundations.Operation< + listMetricDefinitions is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Metric namespace to query metric definitions for.") @query - metricNamespace?: string; + metricNamespace: string; }, MetricDefinitionCollection >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the metric values for a load test run.") @doc("List the metric values for a load test run.") @route("/test-runs/{testRunId}/metrics") @post - ListMetrics is Azure.Core.Foundations.Operation< + listMetrics is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("The aggregation") @query aggregation?: string; - @doc("The interval (i.e. timegrain) of the query.") - @query - interval?: Interval; - - @doc("Metric name") - @query - metricName?: string; - - @doc("Metric namespace to query metric definitions for.") - @query - metricNamespace?: string; - - @doc(""" -The timespan of the query. It is a string with the following format -'startDateTime_ISO/endDateTime_ISO'. -""") - @query - timespan?: string; + ...MetricDimensionsRequest; @doc("Metric dimension filter ") - @body - body: MetricRequestPayload; + @bodyRoot + body?: MetricRequestPayload; }, Metrics >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("List the dimension values for the given metric dimension name.") @doc("List the dimension values for the given metric dimension name.") - ListMetricDimensionValues is Azure.Core.ResourceList< - DimensionValueList, QueryParametersTrait + @route("/test-runs/{testRunId}/metric-dimensions/{name}/values") + listMetricDimensionValues is Azure.Core.Foundations.Operation< + { + @doc(""" + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) + @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") + testRunId: string; + + @doc("Dimension name") + @path + name: string; + + ...MetricDimensionsRequest; + }, + DimensionValueList >; - @summary("Associate an app component (collection of azure resources) to a test run") - @doc("Associate an app component (collection of azure resources) to a test run") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Add an app component to a test run.") + @doc("Add an app component to a test run by providing the resource Id, name and type.") @route("/test-runs/{testRunId}/app-components") @patch - CreateOrUpdateAppComponents is Azure.Core.Foundations.Operation< + createOrUpdateAppComponents is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique Id for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("App Component model.") - @body + @bodyRoot body: TestRunAppComponents; }, ResourceCreatedOrOkResponse >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary(""" -Get associated app component (collection of azure resources) for the given test -run. -""") + Get associated app component (collection of azure resources) for the given test + run. + """) @doc(""" -Get associated app component (collection of azure resources) for the given test -run. -""") + Get associated app component (collection of azure resources) for the given test + run. + """) @route("/test-runs/{testRunId}/app-components") @get - GetAppComponents is Azure.Core.Foundations.Operation< + getAppComponents is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunAppComponents >; + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" @summary("Configure server metrics for a test run") @doc("Configure server metrics for a test run") @route("/test-runs/{testRunId}/server-metrics-config") @patch - CreateOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< + createOrUpdateServerMetricsConfig is Azure.Core.Foundations.Operation< { - @header contentType: "application/merge-patch+json", + @header + @doc("Content type.") + contentType: "application/merge-patch+json"; + @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique Id for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; @doc("Server metric configuration model.") - @body + @bodyRoot body: TestRunServerMetricConfig; }, ResourceCreatedOrOkResponse >; - @summary("List server metrics configuration for the given test run.") - @doc("List server metrics configuration for the given test run.") + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Get associated server metrics configuration for the given test run.") + @doc("Get associated server metrics configuration for the given test run.") @route("/test-runs/{testRunId}/server-metrics-config") @get - @encodedName("application/json", "TestRun_ListServerMetricsConfig") - GetServerMetricsConfig is Azure.Core.Foundations.Operation< + getServerMetricsConfig is Azure.Core.Foundations.Operation< { @doc(""" -Unique name for the load test run, must contain only lower-case alphabetic, -numeric, underscore or hyphen characters. -""") + Unique name for the load test run, must contain only lower-case alphabetic, + numeric, underscore or hyphen characters. + """) @path + @maxLength(50) + @minLength(2) + @pattern("^[a-z0-9_-]*$") testRunId: string; }, TestRunServerMetricConfig >; -}; +} + +// NOTE(mitsha): In clients.tsp, when we use `op is ` syntax, it removes all the decorators defined on the interface +// including the @added decorator and causes tsp compile client.tsp to fail. To handle this, @added is added at each operation level instead. +// Do the same whenever routes are added in a new API Version +@tag("TestProfile") +interface TestProfileAdministration { + @summary("Create a new test profile or update an existing test profile.") + @doc("Create a new test profile or update an existing test profile by providing the test profile Id.") + @added(APIVersions.v2024_05_01_preview) + createOrUpdateTestProfile is StandardResourceOperations.ResourceCreateOrUpdate; + + @summary("Delete a test profile.") + @doc("Delete a test profile by its test profile Id.") + @added(APIVersions.v2024_05_01_preview) + deleteTestProfile is StandardResourceOperations.ResourceDelete; + + @summary("Get load test profile details.") + @doc("Get load test profile details by test profile Id.") + @added(APIVersions.v2024_05_01_preview) + getTestProfile is StandardResourceOperations.ResourceRead; + + @summary("List test profiles.") + @doc(""" + Get all test profiles for the given filters. + """) + @added(APIVersions.v2024_05_01_preview) + listTestProfiles is StandardResourceOperations.ResourceList< + TestProfile, + ListQueryParametersTrait + >; +} + +@tag("TestProfileRun") +interface TestProfileRunAdministration { + @summary("Get test profile run details.") + @doc("Get test profile run details by test profile run Id.") + @added(APIVersions.v2024_05_01_preview) + getTestProfileRun is StandardResourceOperations.ResourceRead; + + #suppress "@azure-tools/typespec-azure-core/use-standard-operations" + @summary("Create and start a new test profile run.") + @doc("Create and start a new test profile run with the given test profile run Id.") + @added(APIVersions.v2024_05_01_preview) + createOrUpdateTestProfileRun is StandardResourceOperations.ResourceCreateOrUpdate; + + @summary("Delete an existing load test profile run.") + @doc("Delete an existing load test profile run by providing the test profile run Id.") + @added(APIVersions.v2024_05_01_preview) + deleteTestProfileRun is StandardResourceOperations.ResourceDelete; + + #suppress "@azure-tools/typespec-azure-core/no-operation-id" + @summary("Stop test profile run.") + @doc("Stop test profile run for the given test profile run Id.") + @operationId("TestProfileRunAdministration_StopTestProfileRun") + @added(APIVersions.v2024_05_01_preview) + stop is StandardResourceOperations.ResourceAction< + TestProfileRun, + {}, + TestProfileRun, + {} + >; + + @summary("List test profile runs.") + @doc("Get all test profile runs for the given filters.") + @added(APIVersions.v2024_05_01_preview) + listTestProfileRuns is StandardResourceOperations.ResourceList< + TestProfileRun, + ListQueryParametersTrait + >; +} From c9aab2f9c7ded921974b65804c0efe4b3bd67f6a Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 11:05:22 +0800 Subject: [PATCH 07/18] Update the loadtesting cases --- .../administrationOperationsClient.ts | 14 +- .../api/administrationOperationsContext.ts | 10 +- .../api/operations.ts | 243 +++++---- .../src/rest/loadTestServiceClient.ts | 2 +- .../src/testRunOperations/api/operations.ts | 465 +++++++++--------- .../api/testRunOperationsContext.ts | 10 +- .../testRunOperationsClient.ts | 10 +- .../test/public/utils/recordedClient.ts | 21 +- 8 files changed, 361 insertions(+), 414 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index 54ba15307b..aba71240a2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -56,15 +56,11 @@ export class AdministrationOperationsClient { credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, ) { - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-client` - : "azsdk-js-client"; - - this._client = createAdministrationOperations(endpointParam, credential, { - ...options, - userAgentOptions: { userAgentPrefix }, - }); + this._client = createAdministrationOperations( + endpointParam, + credential, + options, + ); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 8bc2c2a6ab..54a0bdef28 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -19,14 +19,6 @@ export function createAdministrationOperations( credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, ): LoadTestServiceContext { - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-api` - : "azsdk-js-api"; - - const clientContext = getClient(endpointParam, credential, { - ...options, - userAgentOptions: { userAgentPrefix }, - }); + const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index e8f3f36669..8143e00653 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -346,9 +346,8 @@ export async function _createOrUpdateTestDeserialize( additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { - return { - fileName: p["fileName"], + : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -356,9 +355,8 @@ export async function _createOrUpdateTestDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - }; - }), + validationFailureDetails: p["validationFailureDetails"], + })), }, testId: result.body["testId"], description: result.body["description"], @@ -863,9 +861,8 @@ export async function _getTestDeserialize( additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { - return { - fileName: p["fileName"], + : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -873,9 +870,8 @@ export async function _getTestDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - }; - }), + validationFailureDetails: p["validationFailureDetails"], + })), }, testId: result.body["testId"], description: result.body["description"], @@ -989,10 +985,8 @@ export async function _listTestFilesDeserialize( } return { - value: result.body["value"].map((p) => { - return { - url: p["url"], - fileName: p["fileName"], + value: result.body["value"].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -1000,9 +994,8 @@ export async function _listTestFilesDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - }; - }), + validationFailureDetails: p["validationFailureDetails"], + })), nextLink: result.body["nextLink"], }; } @@ -1052,11 +1045,10 @@ export async function _listTestsDeserialize( } return { - value: result.body["value"].map((p) => { - return { - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + value: result.body["value"].map((p) => ({ + passFailCriteria: !p.passFailCriteria + ? undefined + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !p.autoStopCriteria ? undefined : { @@ -1065,29 +1057,29 @@ export async function _listTestsDeserialize( errorRateTimeWindowInSeconds: p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], + secrets: p["secrets"], + certificate: !p.certificate + ? undefined + : { + value: p.certificate?.["value"], type: p.certificate?.["type"] as CertificateType, - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], + name: p.certificate?.["name"], + }, + environmentVariables: p["environmentVariables"], + loadTestConfiguration: !p.loadTestConfiguration + ? undefined + : { + engineInstances: p.loadTestConfiguration?.["engineInstances"], + splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], + quickStartTest: p.loadTestConfiguration?.["quickStartTest"], + optionalLoadTestConfig: !p.loadTestConfiguration + ?.optionalLoadTestConfig + ? undefined + : { + endpointUrl: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "endpointUrl" + ], requestsPerSecond: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "requestsPerSecond" @@ -1096,19 +1088,19 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "maxResponseTimeInMs" ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, + virtualUsers: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "virtualUsers" + ], + rampUpTime: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "rampUpTime" + ], + duration: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "duration" + ], + }, regionalLoadTestConfig: p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined ? p.loadTestConfiguration?.["regionalLoadTestConfig"] @@ -1118,20 +1110,20 @@ export async function _listTestsDeserialize( region: p["region"], }), ), - }, + }, baselineTestRunId: p["baselineTestRunId"], - inputArtifacts: !p.inputArtifacts - ? undefined - : { - configFileInfo: !p.inputArtifacts?.configFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.configFileInfo?.["fileName"], + inputArtifacts: !p.inputArtifacts + ? undefined + : { + configFileInfo: !p.inputArtifacts?.configFileInfo + ? undefined + : { + fileName: p.inputArtifacts?.configFileInfo?.["fileName"], url: p.inputArtifacts?.configFileInfo?.["url"], fileType: p.inputArtifacts?.configFileInfo?.[ "fileType" ] as FileType, - expireDateTime: + expireDateTime: p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== undefined ? new Date( @@ -1141,20 +1133,20 @@ export async function _listTestsDeserialize( validationStatus: p.inputArtifacts?.configFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo - ? undefined - : { - fileName: + validationFailureDetails: + p.inputArtifacts?.configFileInfo?.[ + "validationFailureDetails" + ], + }, + testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo + ? undefined + : { + fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileType: p.inputArtifacts?.testScriptFileInfo?.[ "fileType" ] as FileType, - expireDateTime: + expireDateTime: p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== undefined ? new Date( @@ -1166,20 +1158,20 @@ export async function _listTestsDeserialize( validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.inputArtifacts?.userPropFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], + validationFailureDetails: + p.inputArtifacts?.testScriptFileInfo?.[ + "validationFailureDetails" + ], + }, + userPropFileInfo: !p.inputArtifacts?.userPropFileInfo + ? undefined + : { + fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], url: p.inputArtifacts?.userPropFileInfo?.["url"], fileType: p.inputArtifacts?.userPropFileInfo?.[ "fileType" ] as FileType, - expireDateTime: + expireDateTime: p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== undefined ? new Date( @@ -1191,24 +1183,24 @@ export async function _listTestsDeserialize( validationStatus: p.inputArtifacts?.userPropFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !p.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], + validationFailureDetails: + p.inputArtifacts?.userPropFileInfo?.[ + "validationFailureDetails" + ], + }, + inputArtifactsZipFileInfo: !p.inputArtifacts + ?.inputArtifactsZipFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" ] as FileType, - expireDateTime: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" + expireDateTime: + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.inputArtifacts?.inputArtifactsZipFileInfo?.[ @@ -1220,11 +1212,11 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, + validationFailureDetails: + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationFailureDetails" + ], + }, urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo ? undefined : { @@ -1252,12 +1244,11 @@ export async function _listTestsDeserialize( "validationFailureDetails" ], }, - additionalFileInfo: - p.inputArtifacts?.["additionalFileInfo"] === undefined - ? p.inputArtifacts?.["additionalFileInfo"] - : p.inputArtifacts?.["additionalFileInfo"].map((p) => { - return { - fileName: p["fileName"], + additionalFileInfo: + p.inputArtifacts?.["additionalFileInfo"] === undefined + ? p.inputArtifacts?.["additionalFileInfo"] + : p.inputArtifacts?.["additionalFileInfo"].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -1265,30 +1256,28 @@ export async function _listTestsDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - }; - }), - }, - testId: p["testId"], - description: p["description"], - displayName: p["displayName"], - subnetId: p["subnetId"], + validationFailureDetails: p["validationFailureDetails"], + })), + }, + testId: p["testId"], + description: p["description"], + displayName: p["displayName"], + subnetId: p["subnetId"], kind: p["kind"] as TestKind, publicIPDisabled: p["publicIPDisabled"], - keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], + keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], createdDateTime: p["createdDateTime"] !== undefined ? new Date(p["createdDateTime"]) : undefined, - createdBy: p["createdBy"], + createdBy: p["createdBy"], lastModifiedDateTime: p["lastModifiedDateTime"] !== undefined ? new Date(p["lastModifiedDateTime"]) : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), + lastModifiedBy: p["lastModifiedBy"], + })), nextLink: result.body["nextLink"], }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts index 3c84987934..a47ec485da 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts @@ -28,7 +28,7 @@ export default function createClient( ): LoadTestServiceContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - const userAgentInfo = `azsdk-js-load-testing/1.0.1`; + const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 860f6bff94..57274f20b7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -171,9 +171,7 @@ export async function _createOrUpdateTestRunDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => { - return { message: p["message"] }; - }), + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration @@ -377,9 +375,8 @@ export async function _createOrUpdateTestRunDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => { - return { - fileName: p["fileName"], + ].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -387,6 +384,8 @@ export async function _createOrUpdateTestRunDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + })), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined @@ -863,9 +862,7 @@ export async function _getTestRunDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => { - return { message: p["message"] }; - }), + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration @@ -1069,9 +1066,8 @@ export async function _getTestRunDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => { - return { - fileName: p["fileName"], + ].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -1079,6 +1075,8 @@ export async function _getTestRunDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + })), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined @@ -1334,7 +1332,6 @@ export async function _listMetricDimensionValuesDeserialize( return { name: result.body["name"], value: result.body["value"], - }), nextLink: result.body["nextLink"], }; } @@ -1388,28 +1385,27 @@ export async function _listMetricDefinitionsDeserialize( } return { - value: result.body["value"].map((p) => { - return { - dimensions: - p["dimensions"] === undefined - ? p["dimensions"] - : p["dimensions"].map((p) => { - return { description: p["description"], name: p["name"] }; - }), - description: p["description"], - name: p["name"], - namespace: p["namespace"], + value: result.body["value"].map((p) => ({ + dimensions: + p["dimensions"] === undefined + ? p["dimensions"] + : p["dimensions"].map((p) => ({ + description: p["description"], + name: p["name"], + })), + description: p["description"], + name: p["name"], + namespace: p["namespace"], primaryAggregationType: p["primaryAggregationType"] as AggregationType, - supportedAggregationTypes: p["supportedAggregationTypes"], + supportedAggregationTypes: p["supportedAggregationTypes"], unit: p["unit"] as MetricUnit, - metricAvailabilities: - p["metricAvailabilities"] === undefined - ? p["metricAvailabilities"] - : p["metricAvailabilities"].map((p) => { + metricAvailabilities: + p["metricAvailabilities"] === undefined + ? p["metricAvailabilities"] + : p["metricAvailabilities"].map((p) => ({ timeGrain: p["timeGrain"] as TimeGrain, - }), - }; - }), + })), + })), }; } @@ -1452,9 +1448,10 @@ export async function _listMetricNamespacesDeserialize( } return { - value: result.body["value"].map((p) => { - return { description: p["description"], name: p["name"] }; - }), + value: result.body["value"].map((p) => ({ + description: p["description"], + name: p["name"], + })), }; } @@ -1512,24 +1509,25 @@ export async function _listMetricsDeserialize( } return { - value: result.body["value"].map((p) => { - return { - data: - p["data"] === undefined - ? p["data"] - : p["data"].map((p) => { + value: result.body["value"].map((p) => ({ + data: + p["data"] === undefined + ? p["data"] + : p["data"].map((p) => ({ timestamp: p["timestamp"] !== undefined ? new Date(p["timestamp"]) : undefined, - dimensionValues: - p["dimensionValues"] === undefined - ? p["dimensionValues"] - : p["dimensionValues"].map((p) => { - return { name: p["name"], value: p["value"] }; - }), - }; - }), + value: p["value"], + })), + dimensionValues: + p["dimensionValues"] === undefined + ? p["dimensionValues"] + : p["dimensionValues"].map((p) => ({ + name: p["name"], + value: p["value"], + })), + })), nextLink: result.body["nextLink"], }; } @@ -1593,12 +1591,11 @@ export async function _listTestRunsDeserialize( } return { - value: result.body["value"].map((p) => { - return { - testRunId: p["testRunId"], - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + value: result.body["value"].map((p) => ({ + testRunId: p["testRunId"], + passFailCriteria: !p.passFailCriteria + ? undefined + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !p.autoStopCriteria ? undefined : { @@ -1607,37 +1604,35 @@ export async function _listTestRunsDeserialize( errorRateTimeWindowInSeconds: p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], + secrets: p["secrets"], + certificate: !p.certificate + ? undefined + : { + value: p.certificate?.["value"], type: p.certificate?.["type"] as CertificateType, - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p) => { - return { message: p["message"] }; - }), - testRunStatistics: p["testRunStatistics"], + name: p.certificate?.["name"], + }, + environmentVariables: p["environmentVariables"], + errorDetails: + p["errorDetails"] === undefined + ? p["errorDetails"] + : p["errorDetails"].map((p) => ({ message: p["message"] })), + testRunStatistics: p["testRunStatistics"], regionalStatistics: p["regionalStatistics"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], + loadTestConfiguration: !p.loadTestConfiguration + ? undefined + : { + engineInstances: p.loadTestConfiguration?.["engineInstances"], + splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], + quickStartTest: p.loadTestConfiguration?.["quickStartTest"], + optionalLoadTestConfig: !p.loadTestConfiguration + ?.optionalLoadTestConfig + ? undefined + : { + endpointUrl: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "endpointUrl" + ], requestsPerSecond: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "requestsPerSecond" @@ -1646,19 +1641,19 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "maxResponseTimeInMs" ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, + virtualUsers: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "virtualUsers" + ], + rampUpTime: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "rampUpTime" + ], + duration: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "duration" + ], + }, regionalLoadTestConfig: p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined ? p.loadTestConfiguration?.["regionalLoadTestConfig"] @@ -1668,29 +1663,29 @@ export async function _listTestRunsDeserialize( region: p["region"], }), ), - }, - testArtifacts: !p.testArtifacts - ? undefined - : { - inputArtifacts: !p.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !p.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "fileName" - ], + }, + testArtifacts: !p.testArtifacts + ? undefined + : { + inputArtifacts: !p.testArtifacts?.inputArtifacts + ? undefined + : { + configFileInfo: !p.testArtifacts?.inputArtifacts + ?.configFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "fileName" + ], url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "url" ], fileType: p.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "expireDateTime" + expireDateTime: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.testArtifacts?.inputArtifacts @@ -1699,25 +1694,26 @@ export async function _listTestRunsDeserialize( : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileName"], + validationFailureDetails: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "validationFailureDetails" + ], + }, + testScriptFileInfo: !p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "fileName" + ], url: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + expireDateTime: + p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.testArtifacts?.inputArtifacts @@ -1728,27 +1724,26 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "fileName" - ], + validationFailureDetails: + p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ + "validationFailureDetails" + ], + }, + userPropFileInfo: !p.testArtifacts?.inputArtifacts + ?.userPropFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "fileName" + ], url: p.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" + expireDateTime: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.testArtifacts?.inputArtifacts @@ -1759,24 +1754,24 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], + validationFailureDetails: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "validationFailureDetails" + ], + }, + inputArtifactsZipFileInfo: !p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileName"], url: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts + expireDateTime: + p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== undefined ? new Date( @@ -1790,12 +1785,12 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo?.[ "validationStatus" ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationFailureDetails" + ], + }, urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo ? undefined @@ -1826,18 +1821,14 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, - additionalFileInfo: - p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] === undefined - ? p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ] - : p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p) => { - return { - fileName: p["fileName"], + additionalFileInfo: + p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] === + undefined + ? p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] + : p.testArtifacts?.inputArtifacts?.[ + "additionalFileInfo" + ].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -1845,30 +1836,29 @@ export async function _listTestRunsDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: - p["validationFailureDetails"], - }; - }), - }, - outputArtifacts: !p.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !p.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "fileName" - ], + validationFailureDetails: + p["validationFailureDetails"], + })), + }, + outputArtifacts: !p.testArtifacts?.outputArtifacts + ? undefined + : { + resultFileInfo: !p.testArtifacts?.outputArtifacts + ?.resultFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "fileName" + ], url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "url" ], fileType: p.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "expireDateTime" + expireDateTime: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.testArtifacts?.outputArtifacts @@ -1877,27 +1867,26 @@ export async function _listTestRunsDeserialize( : undefined, validationStatus: p.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "validationFailureDetails" - ], - }, - logsFileInfo: !p.testArtifacts?.outputArtifacts - ?.logsFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "fileName" - ], + validationFailureDetails: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "validationFailureDetails" + ], + }, + logsFileInfo: !p.testArtifacts?.outputArtifacts?.logsFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "fileName" + ], url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "url" ], fileType: p.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "expireDateTime" + expireDateTime: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" ] !== undefined ? new Date( p.testArtifacts?.outputArtifacts @@ -1907,9 +1896,9 @@ export async function _listTestRunsDeserialize( validationStatus: p.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"] as FileStatus, validationFailureDetails: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationFailureDetails" - ], + ], }, artifactsContainerInfo: !p.testArtifacts?.outputArtifacts ?.artifactsContainerInfo @@ -1951,18 +1940,18 @@ export async function _listTestRunsDeserialize( : undefined, validationStatus: p.testArtifacts?.outputArtifacts ?.reportFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: + validationFailureDetails: p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationFailureDetails" - ], - }, - }, - }, + "validationFailureDetails" + ], + }, + }, + }, testResult: p["testResult"] as PFTestResult, - virtualUsers: p["virtualUsers"], - displayName: p["displayName"], - testId: p["testId"], - description: p["description"], + virtualUsers: p["virtualUsers"], + displayName: p["displayName"], + testId: p["testId"], + description: p["description"], status: p["status"] as Status, startDateTime: p["startDateTime"] !== undefined @@ -1974,9 +1963,9 @@ export async function _listTestRunsDeserialize( p["executedDateTime"] !== undefined ? new Date(p["executedDateTime"]) : undefined, - portalUrl: p["portalUrl"], - duration: p["duration"], - subnetId: p["subnetId"], + portalUrl: p["portalUrl"], + duration: p["duration"], + subnetId: p["subnetId"], kind: p["kind"] as TestKind, requestDataLevel: p["requestDataLevel"] as RequestDataLevel, debugLogsEnabled: p["debugLogsEnabled"], @@ -1985,14 +1974,13 @@ export async function _listTestRunsDeserialize( p["createdDateTime"] !== undefined ? new Date(p["createdDateTime"]) : undefined, - createdBy: p["createdBy"], + createdBy: p["createdBy"], lastModifiedDateTime: p["lastModifiedDateTime"] !== undefined ? new Date(p["lastModifiedDateTime"]) : undefined, - lastModifiedBy: p["lastModifiedBy"], - }; - }), + lastModifiedBy: p["lastModifiedBy"], + })), nextLink: result.body["nextLink"], }; } @@ -2054,9 +2042,7 @@ export async function _stopDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => { - return { message: p["message"] }; - }), + : result.body["errorDetails"].map((p) => ({ message: p["message"] })), testRunStatistics: result.body["testRunStatistics"], regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration @@ -2260,9 +2246,8 @@ export async function _stopDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => { - return { - fileName: p["fileName"], + ].map((p) => ({ + fileName: p["fileName"], url: p["url"], fileType: p["fileType"] as FileType, expireDateTime: @@ -2270,6 +2255,8 @@ export async function _stopDeserialize( ? new Date(p["expireDateTime"]) : undefined, validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + })), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index 7e596e790f..cff7cc0f3f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -19,14 +19,6 @@ export function createTestRunOperations( credential: TokenCredential, options: TestRunOperationsClientOptions = {}, ): LoadTestServiceContext { - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-api` - : "azsdk-js-api"; - - const clientContext = getClient(endpointParam, credential, { - ...options, - userAgentOptions: { userAgentPrefix }, - }); + const clientContext = getClient(endpointParam, credential, options); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index ebfe8870c3..3ee7201db9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -64,15 +64,7 @@ export class TestRunOperationsClient { credential: TokenCredential, options: TestRunOperationsClientOptions = {}, ) { - const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; - const userAgentPrefix = prefixFromOptions - ? `${prefixFromOptions} azsdk-js-client` - : "azsdk-js-client"; - - this._client = createTestRunOperations(endpointParam, credential, { - ...options, - userAgentOptions: { userAgentPrefix }, - }); + this._client = createTestRunOperations(endpointParam, credential, options); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index a4d8acf862..231e0b7c22 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,18 +1,19 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - Recorder, - RecorderStartOptions, - VitestTestContext, -} from "@azure-tools/test-recorder"; +import { Context } from "mocha"; +import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; -const replaceableVariables: Record = { +const envSetupForPlayback: Record = { + ENDPOINT: "https://endpoint", + AZURE_CLIENT_ID: "azure_client_id", + AZURE_CLIENT_SECRET: "azure_client_secret", + AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback: replaceableVariables, + envSetupForPlayback, }; /** @@ -20,10 +21,8 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder( - context: VitestTestContext, -): Promise { - const recorder = new Recorder(context); +export async function createRecorder(context: Context): Promise { + const recorder = new Recorder(context.currentTest); await recorder.start(recorderEnvSetup); return recorder; } From c7f5ad4e9b1e3aa92c31200092e807523ca1cae4 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 11:36:57 +0800 Subject: [PATCH 08/18] Update the LoadTesting cases --- .../typespec-ts/review/load-testing.api.md | 1729 +++++++++++++++-- .../administrationOperationsClient.ts | 14 +- .../api/administrationOperationsContext.ts | 10 +- .../api/operations.ts | 593 +++--- .../src/rest/loadTestServiceClient.ts | 2 +- .../api/operations.ts | 42 +- ...tProfileAdministrationOperationsContext.ts | 10 +- ...stProfileAdministrationOperationsClient.ts | 7 +- .../api/operations.ts | 136 +- .../api/testProfileRunOperationsContext.ts | 10 +- .../testProfileRunOperationsClient.ts | 14 +- .../src/testRunOperations/api/operations.ts | 1049 +++++----- .../api/testRunOperationsContext.ts | 10 +- .../testRunOperationsClient.ts | 10 +- .../test/public/utils/recordedClient.ts | 21 +- .../src/modular/helpers/operationHelpers.ts | 3 + 16 files changed, 2575 insertions(+), 1085 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index 28a417d96c..c967e7cbb2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -4,13 +4,9 @@ ```ts -import { AbortSignalLike } from '@azure/abort-controller'; import { ClientOptions } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; -import { OperationState } from '@azure/core-lro'; -import { PathUncheckedResponse } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; -import { PollerLike } from '@azure/core-lro'; import { TokenCredential } from '@azure/core-auth'; // @public (undocumented) @@ -24,11 +20,23 @@ export class AdministrationOperationsClient { getAppComponents(testId: string, options?: GetAppComponentsOptionalParams): Promise; getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptionalParams): Promise; getTest(testId: string, options?: GetTestOptionalParams): Promise; - getTestFile(testId: string, fileName: string, options?: GetTestFileOptionalParams): Promise; - listTestFiles(testId: string, options?: ListTestFilesOptionalParams): PagedAsyncIterableIterator; + getTestFile(testId: string, fileName: string, options?: GetTestFileOptionalParams): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }>; + listTestFiles(testId: string, options?: ListTestFilesOptionalParams): PagedAsyncIterableIterator; listTests(options?: ListTestsOptionalParams): PagedAsyncIterableIterator; readonly pipeline: Pipeline; - uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptionalParams): Promise; + uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptionalParams): Promise<{ + url?: string; + fileType?: FileType; + expireDateTime?: Date; + validationStatus?: FileStatus; + validationFailureDetails?: string; + }>; } // @public @@ -37,22 +45,35 @@ export interface AdministrationOperationsClientOptions extends ClientOptions { } // @public -export type AggregationType = "Average" | "Count" | "None" | "Total" | "Percentile90" | "Percentile95" | "Percentile99"; +export type AggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; // @public -export type APIVersions = "2022-11-01"; +export type APIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; // @public export interface AppComponent { displayName?: string; kind?: string; readonly resourceGroup?: string; - readonly resourceId?: string; - resourceName?: string; - resourceType?: string; + readonly resourceId: string; + resourceName: string; + resourceType: string; readonly subscriptionId?: string; } +// @public +export interface ArtifactsContainerInfo { + expireDateTime?: Date; + url?: string; +} + +// @public +export interface AutoStopCriteria { + autoStopDisabled?: boolean; + errorRate?: number; + errorRateTimeWindowInSeconds?: number; +} + // @public export interface CertificateMetadata { name?: string; @@ -70,22 +91,35 @@ export type ContinuablePage = TPage & { // @public export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; } // @public export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; } // @public export interface CreateOrUpdateTestOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; } +// @public +export interface CreateOrUpdateTestProfileOptionalParams extends OperationOptions { + contentType?: string; +} + +// @public +export interface CreateOrUpdateTestProfileRunOptionalParams extends OperationOptions { + contentType?: string; +} + +// @public +export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { + contentType?: string; + oldTestRunId?: string; +} + // @public export interface DeleteTestFileOptionalParams extends OperationOptions { } @@ -94,6 +128,14 @@ export interface DeleteTestFileOptionalParams extends OperationOptions { export interface DeleteTestOptionalParams extends OperationOptions { } +// @public +export interface DeleteTestProfileOptionalParams extends OperationOptions { +} + +// @public +export interface DeleteTestProfileRunOptionalParams extends OperationOptions { +} + // @public export interface DeleteTestRunOptionalParams extends OperationOptions { } @@ -110,10 +152,11 @@ export interface DimensionValue { value?: string; } -// @public (undocumented) +// @public export interface DimensionValueList { - // (undocumented) - value: string[]; + readonly name?: string; + nextLink?: string; + value?: string[]; } // @public @@ -122,20 +165,22 @@ export interface ErrorDetails { } // @public -export interface FileInfo { - expireDateTime?: string; - fileName?: string; - fileType?: FileType; - url?: string; - validationFailureDetails?: string; - validationStatus?: FileStatus; -} +export type FileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; // @public -export type FileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; + +// @public +export interface FunctionFlexConsumptionResourceConfiguration { + httpConcurrency: number; + instanceMemoryMB: number; +} // @public -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +export interface FunctionFlexConsumptionTargetResourceConfigurations extends TargetResourceConfigurations { + configurations?: Record; + kind: "FunctionsFlexConsumption"; +} // @public export interface GetAppComponentsOptionalParams extends OperationOptions { @@ -154,26 +199,28 @@ export interface GetTestOptionalParams extends OperationOptions { } // @public -export interface GetTestRunFileOptionalParams extends OperationOptions { +export interface GetTestProfileOptionalParams extends OperationOptions { } // @public -export interface GetTestRunOptionalParams extends OperationOptions { +export interface GetTestProfileRunOptionalParams extends OperationOptions { } // @public -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export interface GetTestRunFileOptionalParams extends OperationOptions { +} + +// @public +export interface GetTestRunOptionalParams extends OperationOptions { +} // @public export interface ListMetricDefinitionsOptionalParams extends OperationOptions { - metricNamespace?: string; } // @public export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { - interval?: TestRunOperationsClientInterval; - metricName?: string; - timespan?: string; + interval?: TestRunOperationsClientTimeGrain; } // @public @@ -183,20 +230,40 @@ export interface ListMetricNamespacesOptionalParams extends OperationOptions { // @public export interface ListMetricsOptionalParams extends OperationOptions { aggregation?: string; - interval?: TestRunOperationsClientInterval; - metricName?: string; - metricNamespace?: string; - timespan?: string; + interval?: TestRunOperationsClientTimeGrain; } // @public export interface ListTestFilesOptionalParams extends OperationOptions { } +// @public +export interface ListTestProfileRunsOptionalParams extends OperationOptions { + createdDateEndTime?: Date; + createdDateStartTime?: Date; + maxEndDateTime?: Date; + maxpagesize?: number; + maxStartDateTime?: Date; + minEndDateTime?: Date; + minStartDateTime?: Date; + statuses?: string; + testProfileIds?: string; + testProfileRunIds?: string; +} + +// @public +export interface ListTestProfilesOptionalParams extends OperationOptions { + lastModifiedEndTime?: Date; + lastModifiedStartTime?: Date; + maxpagesize?: number; + testIds?: string; + testProfileIds?: string; +} + // @public export interface ListTestRunsOptionalParams extends OperationOptions { - executionFrom?: string; - executionTo?: string; + executionFrom?: Date; + executionTo?: Date; maxpagesize?: number; orderby?: string; search?: string; @@ -205,129 +272,1014 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } // @public -export interface ListTestsOptionalParams extends OperationOptions { - lastModifiedEndTime?: string; - lastModifiedStartTime?: string; - maxpagesize?: number; - orderby?: string; - search?: string; +export interface ListTestsOptionalParams extends OperationOptions { + lastModifiedEndTime?: Date; + lastModifiedStartTime?: Date; + maxpagesize?: number; + orderby?: string; + search?: string; +} + +// @public +export interface LoadTestConfiguration { + engineInstances?: number; + optionalLoadTestConfig?: OptionalLoadTestConfig; + quickStartTest?: boolean; + regionalLoadTestConfig?: RegionalConfiguration[]; + splitAllCSVs?: boolean; +} + +// @public +export interface MetricAvailability { + timeGrain?: TimeGrain; +} + +// @public +export interface MetricDefinition { + description?: string; + dimensions?: NameAndDesc[]; + metricAvailabilities?: MetricAvailability[]; + name?: string; + namespace?: string; + primaryAggregationType?: AggregationType; + supportedAggregationTypes?: string[]; + unit?: MetricUnit; +} + +// @public +export interface MetricDefinitionCollection { + value: MetricDefinition[]; +} + +// @public +export interface MetricNamespace { + description?: string; + name?: string; +} + +// @public +export interface MetricNamespaceCollection { + value: MetricNamespace[]; +} + +// @public +export interface MetricRequestPayload { + filters?: DimensionFilter[]; +} + +// @public +export type MetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; + +// @public +export interface MetricValue { + timestamp?: Date; + value?: number; +} + +// @public +export interface NameAndDesc { + description?: string; + name?: string; +} + +// @public +export interface OptionalLoadTestConfig { + duration?: number; + endpointUrl?: string; + maxResponseTimeInMs?: number; + rampUpTime?: number; + requestsPerSecond?: number; + virtualUsers?: number; +} + +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} + +// @public +export interface PassFailCriteria { + passFailMetrics?: Record; +} + +// @public +export interface PassFailMetric { + action?: PFAction; + readonly actualValue?: number; + aggregate?: PFAgFunc; + clientMetric?: PFMetrics; + condition?: string; + requestName?: string; + readonly result?: PFResult; + value?: number; +} + +// @public +export type PFAction = "continue" | "stop"; + +// @public +export type PFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; + +// @public +export type PFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; + +// @public +export type PFResult = "passed" | "undetermined" | "failed"; + +// @public +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; + +// @public +export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +// @public +export interface RegionalConfiguration { + engineInstances: number; + region: string; +} + +// @public +export type RequestDataLevel = "NONE" | "ERRORS"; + +// @public +export type ResourceKind = "FunctionsFlexConsumption"; + +// @public +export interface ResourceMetric { + aggregation: string; + displayDescription?: string; + readonly id?: string; + metricNamespace: string; + name: string; + resourceId: string; + resourceType: string; + unit?: string; +} + +// @public +export interface Secret { + type?: SecretType; + value?: string; +} + +// @public +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; + +// @public +export type Status = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; + +// @public +export interface StopOptionalParams extends OperationOptions { +} + +// @public +export interface TargetResourceConfigurations { + kind: ResourceKind; +} + +// @public +export type TargetResourceConfigurationsUnion = FunctionFlexConsumptionTargetResourceConfigurations | TargetResourceConfigurations; + +// @public +export interface Test { + autoStopCriteria?: AutoStopCriteria; + baselineTestRunId?: string; + certificate?: CertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + environmentVariables?: Record; + readonly inputArtifacts?: TestInputArtifacts; + keyvaultReferenceIdentityId?: string; + keyvaultReferenceIdentityType?: string; + kind?: TestKind; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestConfiguration; + passFailCriteria?: PassFailCriteria; + publicIPDisabled?: boolean; + secrets?: Record; + subnetId?: string; + readonly testId: string; +} + +// @public +export interface TestAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly testId?: string; +} + +// @public +export interface TestFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: FileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: FileStatus; +} + +// @public +export interface TestInputArtifacts { + readonly additionalFileInfo?: TestFileInfo[]; + configFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + testScriptFileInfo?: TestFileInfo; + urlTestConfigFileInfo?: TestFileInfo; + userPropFileInfo?: TestFileInfo; +} + +// @public +export type TestKind = "URL" | "JMX" | "Locust"; + +// @public +export interface TestProfile { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + targetResourceId?: string; + testId?: string; + readonly testProfileId: string; +} + +// @public (undocumented) +export class TestProfileAdministrationOperationsClient { + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileAdministrationOperationsClientOptions); + createOrUpdateTestProfile(testProfileId: string, body: TestProfileAdministrationOperationsClientTestProfile, options?: CreateOrUpdateTestProfileOptionalParams): Promise; + deleteTestProfile(testProfileId: string, options?: DeleteTestProfileOptionalParams): Promise; + getTestProfile(testProfileId: string, options?: GetTestProfileOptionalParams): Promise; + listTestProfiles(options?: ListTestProfilesOptionalParams): TestProfileAdministrationOperationsClientPagedAsyncIterableIterator; + readonly pipeline: Pipeline; +} + +// @public +export type TestProfileAdministrationOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; + +// @public +export type TestProfileAdministrationOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; + +// @public +export interface TestProfileAdministrationOperationsClientAppComponent { + displayName?: string; + kind?: string; + readonly resourceGroup?: string; + readonly resourceId: string; + resourceName: string; + resourceType: string; + readonly subscriptionId?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientArtifactsContainerInfo { + expireDateTime?: Date; + url?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientAutoStopCriteria { + autoStopDisabled?: boolean; + errorRate?: number; + errorRateTimeWindowInSeconds?: number; +} + +// @public +export interface TestProfileAdministrationOperationsClientCertificateMetadata { + name?: string; + type?: TestProfileAdministrationOperationsClientCertificateType; + value?: string; +} + +// @public +export type TestProfileAdministrationOperationsClientCertificateType = "AKV_CERT_URI"; + +// @public +export type TestProfileAdministrationOperationsClientContinuablePage = TPage & { + continuationToken?: string; +}; + +// @public +export interface TestProfileAdministrationOperationsClientDimensionFilter { + name?: string; + values?: string[]; +} + +// @public +export interface TestProfileAdministrationOperationsClientDimensionValue { + name?: string; + value?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientDimensionValueList { + readonly name?: string; + nextLink?: string; + value?: string[]; +} + +// @public +export interface TestProfileAdministrationOperationsClientErrorDetails { + readonly message?: string; +} + +// @public +export type TestProfileAdministrationOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; + +// @public +export type TestProfileAdministrationOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; + +// @public +export interface TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration { + httpConcurrency: number; + instanceMemoryMB: number; +} + +// @public +export interface TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations extends TestProfileAdministrationOperationsClientTargetResourceConfigurations { + configurations?: Record; + kind: "FunctionsFlexConsumption"; +} + +// @public +export interface TestProfileAdministrationOperationsClientLoadTestConfiguration { + engineInstances?: number; + optionalLoadTestConfig?: TestProfileAdministrationOperationsClientOptionalLoadTestConfig; + quickStartTest?: boolean; + regionalLoadTestConfig?: TestProfileAdministrationOperationsClientRegionalConfiguration[]; + splitAllCSVs?: boolean; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricAvailability { + timeGrain?: TestProfileAdministrationOperationsClientTimeGrain; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricDefinition { + description?: string; + dimensions?: TestProfileAdministrationOperationsClientNameAndDesc[]; + metricAvailabilities?: TestProfileAdministrationOperationsClientMetricAvailability[]; + name?: string; + namespace?: string; + primaryAggregationType?: TestProfileAdministrationOperationsClientAggregationType; + supportedAggregationTypes?: string[]; + unit?: TestProfileAdministrationOperationsClientMetricUnit; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricDefinitionCollection { + value: TestProfileAdministrationOperationsClientMetricDefinition[]; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricNamespace { + description?: string; + name?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricNamespaceCollection { + value: TestProfileAdministrationOperationsClientMetricNamespace[]; +} + +// @public +export interface TestProfileAdministrationOperationsClientMetricRequestPayload { + filters?: TestProfileAdministrationOperationsClientDimensionFilter[]; +} + +// @public +export type TestProfileAdministrationOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; + +// @public +export interface TestProfileAdministrationOperationsClientMetricValue { + timestamp?: Date; + value?: number; +} + +// @public +export interface TestProfileAdministrationOperationsClientNameAndDesc { + description?: string; + name?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientOptionalLoadTestConfig { + duration?: number; + endpointUrl?: string; + maxResponseTimeInMs?: number; + rampUpTime?: number; + requestsPerSecond?: number; + virtualUsers?: number; +} + +// @public +export interface TestProfileAdministrationOperationsClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientPagedAsyncIterableIterator { + [Symbol.asyncIterator](): TestProfileAdministrationOperationsClientPagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; +} + +// @public +export interface TestProfileAdministrationOperationsClientPageSettings { + continuationToken?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientPassFailCriteria { + passFailMetrics?: Record; +} + +// @public +export interface TestProfileAdministrationOperationsClientPassFailMetric { + action?: TestProfileAdministrationOperationsClientPFAction; + readonly actualValue?: number; + aggregate?: TestProfileAdministrationOperationsClientPFAgFunc; + clientMetric?: TestProfileAdministrationOperationsClientPFMetrics; + condition?: string; + requestName?: string; + readonly result?: TestProfileAdministrationOperationsClientPFResult; + value?: number; +} + +// @public +export type TestProfileAdministrationOperationsClientPFAction = "continue" | "stop"; + +// @public +export type TestProfileAdministrationOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; + +// @public +export type TestProfileAdministrationOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; + +// @public +export type TestProfileAdministrationOperationsClientPFResult = "passed" | "undetermined" | "failed"; + +// @public +export type TestProfileAdministrationOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; + +// @public +export type TestProfileAdministrationOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +// @public +export interface TestProfileAdministrationOperationsClientRegionalConfiguration { + engineInstances: number; + region: string; +} + +// @public +export type TestProfileAdministrationOperationsClientRequestDataLevel = "NONE" | "ERRORS"; + +// @public +export type TestProfileAdministrationOperationsClientResourceKind = "FunctionsFlexConsumption"; + +// @public +export interface TestProfileAdministrationOperationsClientResourceMetric { + aggregation: string; + displayDescription?: string; + readonly id?: string; + metricNamespace: string; + name: string; + resourceId: string; + resourceType: string; + unit?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientSecret { + type?: TestProfileAdministrationOperationsClientSecretType; + value?: string; +} + +// @public +export type TestProfileAdministrationOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; + +// @public +export type TestProfileAdministrationOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; + +// @public +export interface TestProfileAdministrationOperationsClientTargetResourceConfigurations { + kind: TestProfileAdministrationOperationsClientResourceKind; +} + +// @public +export type TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion = TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations | TestProfileAdministrationOperationsClientTargetResourceConfigurations; + +// @public +export interface TestProfileAdministrationOperationsClientTest { + autoStopCriteria?: TestProfileAdministrationOperationsClientAutoStopCriteria; + baselineTestRunId?: string; + certificate?: TestProfileAdministrationOperationsClientCertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + environmentVariables?: Record; + readonly inputArtifacts?: TestProfileAdministrationOperationsClientTestInputArtifacts; + keyvaultReferenceIdentityId?: string; + keyvaultReferenceIdentityType?: string; + kind?: TestProfileAdministrationOperationsClientTestKind; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: TestProfileAdministrationOperationsClientLoadTestConfiguration; + passFailCriteria?: TestProfileAdministrationOperationsClientPassFailCriteria; + publicIPDisabled?: boolean; + secrets?: Record; + subnetId?: string; + readonly testId: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly testId?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestProfileAdministrationOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestProfileAdministrationOperationsClientFileStatus; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestInputArtifacts { + readonly additionalFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo[]; + configFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo; + inputArtifactsZipFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo; + testScriptFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo; + urlTestConfigFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo; + userPropFileInfo?: TestProfileAdministrationOperationsClientTestFileInfo; +} + +// @public +export type TestProfileAdministrationOperationsClientTestKind = "URL" | "JMX" | "Locust"; + +// @public +export interface TestProfileAdministrationOperationsClientTestProfile { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + targetResourceConfigurations?: TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion; + targetResourceId?: string; + testId?: string; + readonly testProfileId: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestProfileRun { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly durationInSeconds?: number; + readonly endDateTime?: Date; + readonly errorDetails?: TestProfileAdministrationOperationsClientErrorDetails[]; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly recommendations?: TestProfileAdministrationOperationsClientTestProfileRunRecommendation[]; + readonly startDateTime?: Date; + readonly status?: TestProfileAdministrationOperationsClientTestProfileRunStatus; + readonly targetResourceConfigurations?: TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion; + readonly targetResourceId?: string; + testProfileId?: string; + readonly testProfileRunId: string; + readonly testRunDetails?: Record; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestProfileRunRecommendation { + category: TestProfileAdministrationOperationsClientRecommendationCategory; + configurations?: string[]; +} + +// @public +export type TestProfileAdministrationOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; + +// @public +export interface TestProfileAdministrationOperationsClientTestRun { + autoStopCriteria?: TestProfileAdministrationOperationsClientAutoStopCriteria; + certificate?: TestProfileAdministrationOperationsClientCertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + debugLogsEnabled?: boolean; + description?: string; + displayName?: string; + readonly duration?: number; + readonly endDateTime?: Date; + environmentVariables?: Record; + readonly errorDetails?: TestProfileAdministrationOperationsClientErrorDetails[]; + readonly executedDateTime?: Date; + readonly kind?: TestProfileAdministrationOperationsClientTestKind; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: TestProfileAdministrationOperationsClientLoadTestConfiguration; + passFailCriteria?: TestProfileAdministrationOperationsClientPassFailCriteria; + readonly portalUrl?: string; + readonly publicIPDisabled?: boolean; + readonly regionalStatistics?: Record; + requestDataLevel?: TestProfileAdministrationOperationsClientRequestDataLevel; + secrets?: Record; + readonly startDateTime?: Date; + readonly status?: TestProfileAdministrationOperationsClientStatus; + readonly subnetId?: string; + readonly testArtifacts?: TestProfileAdministrationOperationsClientTestRunArtifacts; + testId?: string; + readonly testResult?: TestProfileAdministrationOperationsClientPFTestResult; + readonly testRunId: string; + readonly testRunStatistics?: Record; + readonly virtualUsers?: number; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly testRunId?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunArtifacts { + readonly inputArtifacts?: TestProfileAdministrationOperationsClientTestRunInputArtifacts; + outputArtifacts?: TestProfileAdministrationOperationsClientTestRunOutputArtifacts; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunDetail { + configurationId: string; + properties: Record; + status: TestProfileAdministrationOperationsClientStatus; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestProfileAdministrationOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestProfileAdministrationOperationsClientFileStatus; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunInputArtifacts { + readonly additionalFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo[]; + configFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + inputArtifactsZipFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + testScriptFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + urlTestConfigFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + userPropFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunOutputArtifacts { + artifactsContainerInfo?: TestProfileAdministrationOperationsClientArtifactsContainerInfo; + logsFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + reportFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; + resultFileInfo?: TestProfileAdministrationOperationsClientTestRunFileInfo; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunServerMetricConfig { + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + metrics?: Record; + readonly testRunId?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestRunStatistics { + readonly errorCount?: number; + readonly errorPct?: number; + readonly maxResTime?: number; + readonly meanResTime?: number; + readonly medianResTime?: number; + readonly minResTime?: number; + readonly pct1ResTime?: number; + readonly pct2ResTime?: number; + readonly pct3ResTime?: number; + readonly pct75ResTime?: number; + readonly pct96ResTime?: number; + readonly pct97ResTime?: number; + readonly pct98ResTime?: number; + readonly pct9999ResTime?: number; + readonly pct999ResTime?: number; + readonly receivedKBytesPerSec?: number; + readonly sampleCount?: number; + readonly sentKBytesPerSec?: number; + readonly throughput?: number; + readonly transaction?: string; +} + +// @public +export interface TestProfileAdministrationOperationsClientTestServerMetricConfig { + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + metrics: Record; + readonly testId?: string; +} + +// @public +export type TestProfileAdministrationOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + +// @public +export interface TestProfileAdministrationOperationsClientTimeSeriesElement { + data?: TestProfileAdministrationOperationsClientMetricValue[]; + dimensionValues?: TestProfileAdministrationOperationsClientDimensionValue[]; +} + +// @public +export interface TestProfileRun { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly durationInSeconds?: number; + readonly endDateTime?: Date; + readonly errorDetails?: ErrorDetails[]; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly recommendations?: TestProfileRunRecommendation[]; + readonly startDateTime?: Date; + readonly status?: TestProfileRunStatus; + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + readonly targetResourceId?: string; + testProfileId?: string; + readonly testProfileRunId: string; + readonly testRunDetails?: Record; +} + +// @public (undocumented) +export class TestProfileRunOperationsClient { + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileRunOperationsClientOptions); + createOrUpdateTestProfileRun(testProfileRunId: string, body: TestProfileRunOperationsClientTestProfileRun, options?: CreateOrUpdateTestProfileRunOptionalParams): Promise; + deleteTestProfileRun(testProfileRunId: string, options?: DeleteTestProfileRunOptionalParams): Promise; + getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; + listTestProfileRuns(options?: ListTestProfileRunsOptionalParams): TestProfileRunOperationsClientPagedAsyncIterableIterator; + readonly pipeline: Pipeline; + stop(testProfileRunId: string, options?: TestProfileRunOperationsClientStopOptionalParams): Promise; +} + +// @public +export type TestProfileRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; + +// @public +export type TestProfileRunOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; + +// @public +export interface TestProfileRunOperationsClientAppComponent { + displayName?: string; + kind?: string; + readonly resourceGroup?: string; + readonly resourceId: string; + resourceName: string; + resourceType: string; + readonly subscriptionId?: string; +} + +// @public +export interface TestProfileRunOperationsClientArtifactsContainerInfo { + expireDateTime?: Date; + url?: string; +} + +// @public +export interface TestProfileRunOperationsClientAutoStopCriteria { + autoStopDisabled?: boolean; + errorRate?: number; + errorRateTimeWindowInSeconds?: number; +} + +// @public +export interface TestProfileRunOperationsClientCertificateMetadata { + name?: string; + type?: TestProfileRunOperationsClientCertificateType; + value?: string; +} + +// @public +export type TestProfileRunOperationsClientCertificateType = "AKV_CERT_URI"; + +// @public +export type TestProfileRunOperationsClientContinuablePage = TPage & { + continuationToken?: string; +}; + +// @public +export interface TestProfileRunOperationsClientDimensionFilter { + name?: string; + values?: string[]; +} + +// @public +export interface TestProfileRunOperationsClientDimensionValue { + name?: string; + value?: string; +} + +// @public +export interface TestProfileRunOperationsClientDimensionValueList { + readonly name?: string; + nextLink?: string; + value?: string[]; +} + +// @public +export interface TestProfileRunOperationsClientErrorDetails { + readonly message?: string; +} + +// @public +export type TestProfileRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; + +// @public +export type TestProfileRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; + +// @public +export interface TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration { + httpConcurrency: number; + instanceMemoryMB: number; +} + +// @public +export interface TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations extends TestProfileRunOperationsClientTargetResourceConfigurations { + configurations?: Record; + kind: "FunctionsFlexConsumption"; } // @public -export interface LoadTestConfiguration { +export interface TestProfileRunOperationsClientLoadTestConfiguration { engineInstances?: number; - optionalLoadTestConfig?: OptionalLoadTestConfig; + optionalLoadTestConfig?: TestProfileRunOperationsClientOptionalLoadTestConfig; quickStartTest?: boolean; + regionalLoadTestConfig?: TestProfileRunOperationsClientRegionalConfiguration[]; splitAllCSVs?: boolean; } // @public -export interface MetricAvailability { - timeGrain?: TimeGrain; +export interface TestProfileRunOperationsClientMetricAvailability { + timeGrain?: TestProfileRunOperationsClientTimeGrain; } // @public -export interface MetricDefinition { +export interface TestProfileRunOperationsClientMetricDefinition { description?: string; - dimensions?: NameAndDesc[]; - metricAvailabilities?: MetricAvailability[]; + dimensions?: TestProfileRunOperationsClientNameAndDesc[]; + metricAvailabilities?: TestProfileRunOperationsClientMetricAvailability[]; name?: string; namespace?: string; - primaryAggregationType?: AggregationType; + primaryAggregationType?: TestProfileRunOperationsClientAggregationType; supportedAggregationTypes?: string[]; - unit?: MetricUnit; + unit?: TestProfileRunOperationsClientMetricUnit; } // @public -export interface MetricDefinitionCollection { - value: MetricDefinition[]; +export interface TestProfileRunOperationsClientMetricDefinitionCollection { + value: TestProfileRunOperationsClientMetricDefinition[]; } // @public -export interface MetricNamespace { +export interface TestProfileRunOperationsClientMetricNamespace { description?: string; name?: string; } // @public -export interface MetricNamespaceCollection { - value: MetricNamespace[]; +export interface TestProfileRunOperationsClientMetricNamespaceCollection { + value: TestProfileRunOperationsClientMetricNamespace[]; } // @public -export interface MetricRequestPayload { - filters?: DimensionFilter[]; +export interface TestProfileRunOperationsClientMetricRequestPayload { + filters?: TestProfileRunOperationsClientDimensionFilter[]; } // @public -export type MetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; +export type TestProfileRunOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; // @public -export interface MetricValue { - timestamp?: string; +export interface TestProfileRunOperationsClientMetricValue { + timestamp?: Date; value?: number; } // @public -export interface NameAndDesc { +export interface TestProfileRunOperationsClientNameAndDesc { description?: string; name?: string; } // @public -export interface OptionalLoadTestConfig { +export interface TestProfileRunOperationsClientOptionalLoadTestConfig { duration?: number; endpointUrl?: string; + maxResponseTimeInMs?: number; rampUpTime?: number; + requestsPerSecond?: number; virtualUsers?: number; } // @public -export interface PagedAsyncIterableIterator { - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator>; +export interface TestProfileRunOperationsClientOptions extends ClientOptions { + apiVersion?: string; +} + +// @public +export interface TestProfileRunOperationsClientPagedAsyncIterableIterator { + [Symbol.asyncIterator](): TestProfileRunOperationsClientPagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; } // @public -export interface PageSettings { +export interface TestProfileRunOperationsClientPageSettings { continuationToken?: string; } // @public -export interface PassFailCriteria { - passFailMetrics?: Record; +export interface TestProfileRunOperationsClientPassFailCriteria { + passFailMetrics?: Record; } // @public -export interface PassFailMetric { - action?: PFAction; +export interface TestProfileRunOperationsClientPassFailMetric { + action?: TestProfileRunOperationsClientPFAction; readonly actualValue?: number; - aggregate?: PFAgFunc; - clientMetric?: PFMetrics; + aggregate?: TestProfileRunOperationsClientPFAgFunc; + clientMetric?: TestProfileRunOperationsClientPFMetrics; condition?: string; requestName?: string; - readonly result?: PFResult; + readonly result?: TestProfileRunOperationsClientPFResult; value?: number; } // @public -export type PFAction = "continue" | "stop"; +export type TestProfileRunOperationsClientPFAction = "continue" | "stop"; // @public -export type PFAgFunc = "count" | "percentage" | "avg" | "p50" | "p90" | "p95" | "p99" | "min" | "max"; +export type TestProfileRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; // @public -export type PFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; +export type TestProfileRunOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; // @public -export type PFResult = "passed" | "undetermined" | "failed"; +export type TestProfileRunOperationsClientPFResult = "passed" | "undetermined" | "failed"; // @public -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type TestProfileRunOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; // @public -export interface ResourceMetric { +export type TestProfileRunOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +// @public +export interface TestProfileRunOperationsClientRegionalConfiguration { + engineInstances: number; + region: string; +} + +// @public +export type TestProfileRunOperationsClientRequestDataLevel = "NONE" | "ERRORS"; + +// @public +export type TestProfileRunOperationsClientResourceKind = "FunctionsFlexConsumption"; + +// @public +export interface TestProfileRunOperationsClientResourceMetric { aggregation: string; displayDescription?: string; readonly id?: string; @@ -339,89 +1291,303 @@ export interface ResourceMetric { } // @public -export function restorePoller(client: TestRunOperationsClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; - -// @public (undocumented) -export interface RestorePollerOptions extends OperationOptions { - abortSignal?: AbortSignalLike; - processResponseBody?: (result: TResponse) => Promise; - updateIntervalInMs?: number; +export interface TestProfileRunOperationsClientSecret { + type?: TestProfileRunOperationsClientSecretType; + value?: string; } // @public -export interface Secret { - type?: SecretType; - value?: string; -} +export type TestProfileRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; // @public -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type TestProfileRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; // @public -export type Status = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +export interface TestProfileRunOperationsClientStopOptionalParams extends OperationOptions { +} // @public -export interface StopTestRunOptionalParams extends OperationOptions { +export interface TestProfileRunOperationsClientTargetResourceConfigurations { + kind: TestProfileRunOperationsClientResourceKind; } // @public -export interface Test { - certificate?: CertificateMetadata; +export type TestProfileRunOperationsClientTargetResourceConfigurationsUnion = TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations | TestProfileRunOperationsClientTargetResourceConfigurations; + +// @public +export interface TestProfileRunOperationsClientTest { + autoStopCriteria?: TestProfileRunOperationsClientAutoStopCriteria; + baselineTestRunId?: string; + certificate?: TestProfileRunOperationsClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; - readonly inputArtifacts?: TestInputArtifacts; + readonly inputArtifacts?: TestProfileRunOperationsClientTestInputArtifacts; keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; + kind?: TestProfileRunOperationsClientTestKind; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; - loadTestConfiguration?: LoadTestConfiguration; - passFailCriteria?: PassFailCriteria; - secrets?: Record; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: TestProfileRunOperationsClientLoadTestConfiguration; + passFailCriteria?: TestProfileRunOperationsClientPassFailCriteria; + publicIPDisabled?: boolean; + secrets?: Record; subnetId?: string; + readonly testId: string; +} + +// @public +export interface TestProfileRunOperationsClientTestAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; readonly testId?: string; } // @public -export interface TestAppComponents { - components: Record; +export interface TestProfileRunOperationsClientTestFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestProfileRunOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestProfileRunOperationsClientFileStatus; +} + +// @public +export interface TestProfileRunOperationsClientTestInputArtifacts { + readonly additionalFileInfo?: TestProfileRunOperationsClientTestFileInfo[]; + configFileInfo?: TestProfileRunOperationsClientTestFileInfo; + inputArtifactsZipFileInfo?: TestProfileRunOperationsClientTestFileInfo; + testScriptFileInfo?: TestProfileRunOperationsClientTestFileInfo; + urlTestConfigFileInfo?: TestProfileRunOperationsClientTestFileInfo; + userPropFileInfo?: TestProfileRunOperationsClientTestFileInfo; +} + +// @public +export type TestProfileRunOperationsClientTestKind = "URL" | "JMX" | "Locust"; + +// @public +export interface TestProfileRunOperationsClientTestProfile { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + targetResourceConfigurations?: TestProfileRunOperationsClientTargetResourceConfigurationsUnion; + targetResourceId?: string; + testId?: string; + readonly testProfileId: string; +} + +// @public +export interface TestProfileRunOperationsClientTestProfileRun { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly durationInSeconds?: number; + readonly endDateTime?: Date; + readonly errorDetails?: TestProfileRunOperationsClientErrorDetails[]; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly recommendations?: TestProfileRunOperationsClientTestProfileRunRecommendation[]; + readonly startDateTime?: Date; + readonly status?: TestProfileRunOperationsClientTestProfileRunStatus; + readonly targetResourceConfigurations?: TestProfileRunOperationsClientTargetResourceConfigurationsUnion; + readonly targetResourceId?: string; + testProfileId?: string; + readonly testProfileRunId: string; + readonly testRunDetails?: Record; +} + +// @public +export interface TestProfileRunOperationsClientTestProfileRunRecommendation { + category: TestProfileRunOperationsClientRecommendationCategory; + configurations?: string[]; +} + +// @public +export type TestProfileRunOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; + +// @public +export interface TestProfileRunOperationsClientTestRun { + autoStopCriteria?: TestProfileRunOperationsClientAutoStopCriteria; + certificate?: TestProfileRunOperationsClientCertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + debugLogsEnabled?: boolean; + description?: string; + displayName?: string; + readonly duration?: number; + readonly endDateTime?: Date; + environmentVariables?: Record; + readonly errorDetails?: TestProfileRunOperationsClientErrorDetails[]; + readonly executedDateTime?: Date; + readonly kind?: TestProfileRunOperationsClientTestKind; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: TestProfileRunOperationsClientLoadTestConfiguration; + passFailCriteria?: TestProfileRunOperationsClientPassFailCriteria; + readonly portalUrl?: string; + readonly publicIPDisabled?: boolean; + readonly regionalStatistics?: Record; + requestDataLevel?: TestProfileRunOperationsClientRequestDataLevel; + secrets?: Record; + readonly startDateTime?: Date; + readonly status?: TestProfileRunOperationsClientStatus; + readonly subnetId?: string; + readonly testArtifacts?: TestProfileRunOperationsClientTestRunArtifacts; + testId?: string; + readonly testResult?: TestProfileRunOperationsClientPFTestResult; + readonly testRunId: string; + readonly testRunStatistics?: Record; + readonly virtualUsers?: number; +} + +// @public +export interface TestProfileRunOperationsClientTestRunAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly testRunId?: string; +} + +// @public +export interface TestProfileRunOperationsClientTestRunArtifacts { + readonly inputArtifacts?: TestProfileRunOperationsClientTestRunInputArtifacts; + outputArtifacts?: TestProfileRunOperationsClientTestRunOutputArtifacts; +} + +// @public +export interface TestProfileRunOperationsClientTestRunDetail { + configurationId: string; + properties: Record; + status: TestProfileRunOperationsClientStatus; +} + +// @public +export interface TestProfileRunOperationsClientTestRunFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestProfileRunOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestProfileRunOperationsClientFileStatus; +} + +// @public +export interface TestProfileRunOperationsClientTestRunInputArtifacts { + readonly additionalFileInfo?: TestProfileRunOperationsClientTestRunFileInfo[]; + configFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + inputArtifactsZipFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + testScriptFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + urlTestConfigFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + userPropFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; +} + +// @public +export interface TestProfileRunOperationsClientTestRunOutputArtifacts { + artifactsContainerInfo?: TestProfileRunOperationsClientArtifactsContainerInfo; + logsFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + reportFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; + resultFileInfo?: TestProfileRunOperationsClientTestRunFileInfo; +} + +// @public +export interface TestProfileRunOperationsClientTestRunServerMetricConfig { + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + metrics?: Record; + readonly testRunId?: string; +} + +// @public +export interface TestProfileRunOperationsClientTestRunStatistics { + readonly errorCount?: number; + readonly errorPct?: number; + readonly maxResTime?: number; + readonly meanResTime?: number; + readonly medianResTime?: number; + readonly minResTime?: number; + readonly pct1ResTime?: number; + readonly pct2ResTime?: number; + readonly pct3ResTime?: number; + readonly pct75ResTime?: number; + readonly pct96ResTime?: number; + readonly pct97ResTime?: number; + readonly pct98ResTime?: number; + readonly pct9999ResTime?: number; + readonly pct999ResTime?: number; + readonly receivedKBytesPerSec?: number; + readonly sampleCount?: number; + readonly sentKBytesPerSec?: number; + readonly throughput?: number; + readonly transaction?: string; +} + +// @public +export interface TestProfileRunOperationsClientTestServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; + metrics: Record; readonly testId?: string; } // @public -export interface TestInputArtifacts { - readonly additionalFileInfo?: FileInfo[]; - configFileInfo?: FileInfo; - inputArtifactsZipFileInfo?: FileInfo; - testScriptFileInfo?: FileInfo; - userPropFileInfo?: FileInfo; +export type TestProfileRunOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + +// @public +export interface TestProfileRunOperationsClientTimeSeriesElement { + data?: TestProfileRunOperationsClientMetricValue[]; + dimensionValues?: TestProfileRunOperationsClientDimensionValue[]; +} + +// @public +export interface TestProfileRunRecommendation { + category: RecommendationCategory; + configurations?: string[]; } +// @public +export type TestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; + // @public export interface TestRun { + autoStopCriteria?: AutoStopCriteria; certificate?: CertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; + debugLogsEnabled?: boolean; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: string; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: ErrorDetails[]; - readonly executedDateTime?: string; + readonly executedDateTime?: Date; + readonly kind?: TestKind; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: LoadTestConfiguration; passFailCriteria?: PassFailCriteria; readonly portalUrl?: string; + readonly publicIPDisabled?: boolean; + readonly regionalStatistics?: Record; + requestDataLevel?: RequestDataLevel; secrets?: Record; - readonly startDateTime?: string; + readonly startDateTime?: Date; readonly status?: Status; readonly subnetId?: string; readonly testArtifacts?: TestRunArtifacts; @@ -436,9 +1602,9 @@ export interface TestRun { export interface TestRunAppComponents { components: Record; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; readonly testRunId?: string; } @@ -448,13 +1614,31 @@ export interface TestRunArtifacts { outputArtifacts?: TestRunOutputArtifacts; } +// @public +export interface TestRunDetail { + configurationId: string; + properties: Record; + status: Status; +} + +// @public +export interface TestRunFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: FileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: FileStatus; +} + // @public export interface TestRunInputArtifacts { - readonly additionalFileInfo?: FileInfo[]; - configFileInfo?: FileInfo; - inputArtifactsZipFileInfo?: FileInfo; - testScriptFileInfo?: FileInfo; - userPropFileInfo?: FileInfo; + readonly additionalFileInfo?: TestRunFileInfo[]; + configFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + testScriptFileInfo?: TestRunFileInfo; + urlTestConfigFileInfo?: TestRunFileInfo; + userPropFileInfo?: TestRunFileInfo; } // @public (undocumented) @@ -462,38 +1646,57 @@ export class TestRunOperationsClient { constructor(endpointParam: string, credential: TokenCredential, options?: TestRunOperationsClientOptions); createOrUpdateAppComponents(testRunId: string, body: TestRunOperationsClientTestRunAppComponents, options?: TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams): Promise; createOrUpdateServerMetricsConfig(testRunId: string, body: TestRunOperationsClientTestRunServerMetricConfig, options?: TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams): Promise; + createOrUpdateTestRun(testRunId: string, body: TestRunOperationsClientTestRun, options?: CreateOrUpdateTestRunOptionalParams): Promise; deleteTestRun(testRunId: string, options?: DeleteTestRunOptionalParams): Promise; getAppComponents(testRunId: string, options?: TestRunOperationsClientGetAppComponentsOptionalParams): Promise; getServerMetricsConfig(testRunId: string, options?: TestRunOperationsClientGetServerMetricsConfigOptionalParams): Promise; getTestRun(testRunId: string, options?: GetTestRunOptionalParams): Promise; - getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise; - listMetricDefinitions(testRunId: string, options?: ListMetricDefinitionsOptionalParams): Promise; - listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; + getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise<{ + url?: string; + fileType?: TestRunOperationsClientFileType; + expireDateTime?: Date; + validationStatus?: TestRunOperationsClientFileStatus; + validationFailureDetails?: string; + }>; + listMetricDefinitions(testRunId: string, metricNamespace: string, options?: ListMetricDefinitionsOptionalParams): Promise; + listMetricDimensionValues(testRunId: string, name: string, metricname: string, metricNamespace: string, timespan: string, options?: ListMetricDimensionValuesOptionalParams): Promise; listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptionalParams): Promise; - listMetrics(testRunId: string, body: TestRunOperationsClientMetricRequestPayload, options?: ListMetricsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; + listMetrics(testRunId: string, metricname: string, metricNamespace: string, timespan: string, body?: TestRunOperationsClientMetricRequestPayload, options?: ListMetricsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; listTestRuns(options?: ListTestRunsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; - stopTestRun(testRunId: string, options?: StopTestRunOptionalParams): Promise; - testRun(testRunId: string, resource: TestRunOperationsClientTestRun, options?: TestRunOptionalParams): PollerLike, TestRunOperationsClientTestRun>; + stop(testRunId: string, options?: StopOptionalParams): Promise; } // @public -export type TestRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile90" | "Percentile95" | "Percentile99"; +export type TestRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; // @public -export type TestRunOperationsClientAPIVersions = "2022-11-01"; +export type TestRunOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; // @public export interface TestRunOperationsClientAppComponent { displayName?: string; kind?: string; readonly resourceGroup?: string; - readonly resourceId?: string; - resourceName?: string; - resourceType?: string; + readonly resourceId: string; + resourceName: string; + resourceType: string; readonly subscriptionId?: string; } +// @public +export interface TestRunOperationsClientArtifactsContainerInfo { + expireDateTime?: Date; + url?: string; +} + +// @public +export interface TestRunOperationsClientAutoStopCriteria { + autoStopDisabled?: boolean; + errorRate?: number; + errorRateTimeWindowInSeconds?: number; +} + // @public export interface TestRunOperationsClientCertificateMetadata { name?: string; @@ -511,13 +1714,11 @@ export type TestRunOperationsClientContinuablePage // @public export interface TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; } // @public export interface TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; } @@ -533,10 +1734,11 @@ export interface TestRunOperationsClientDimensionValue { value?: string; } -// @public (undocumented) +// @public export interface TestRunOperationsClientDimensionValueList { - // (undocumented) - value: string[]; + readonly name?: string; + nextLink?: string; + value?: string[]; } // @public @@ -545,37 +1747,37 @@ export interface TestRunOperationsClientErrorDetails { } // @public -export interface TestRunOperationsClientFileInfo { - expireDateTime?: string; - fileName?: string; - fileType?: TestRunOperationsClientFileType; - url?: string; - validationFailureDetails?: string; - validationStatus?: TestRunOperationsClientFileStatus; -} +export type TestRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; // @public -export type TestRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type TestRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; // @public -export type TestRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +export interface TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration { + httpConcurrency: number; + instanceMemoryMB: number; +} // @public -export interface TestRunOperationsClientGetAppComponentsOptionalParams extends OperationOptions { +export interface TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations extends TestRunOperationsClientTargetResourceConfigurations { + configurations?: Record; + kind: "FunctionsFlexConsumption"; } // @public -export interface TestRunOperationsClientGetServerMetricsConfigOptionalParams extends OperationOptions { +export interface TestRunOperationsClientGetAppComponentsOptionalParams extends OperationOptions { } // @public -export type TestRunOperationsClientInterval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export interface TestRunOperationsClientGetServerMetricsConfigOptionalParams extends OperationOptions { +} // @public export interface TestRunOperationsClientLoadTestConfiguration { engineInstances?: number; optionalLoadTestConfig?: TestRunOperationsClientOptionalLoadTestConfig; quickStartTest?: boolean; + regionalLoadTestConfig?: TestRunOperationsClientRegionalConfiguration[]; splitAllCSVs?: boolean; } @@ -622,7 +1824,7 @@ export type TestRunOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Co // @public export interface TestRunOperationsClientMetricValue { - timestamp?: string; + timestamp?: Date; value?: number; } @@ -636,7 +1838,9 @@ export interface TestRunOperationsClientNameAndDesc { export interface TestRunOperationsClientOptionalLoadTestConfig { duration?: number; endpointUrl?: string; + maxResponseTimeInMs?: number; rampUpTime?: number; + requestsPerSecond?: number; virtualUsers?: number; } @@ -678,7 +1882,7 @@ export interface TestRunOperationsClientPassFailMetric { export type TestRunOperationsClientPFAction = "continue" | "stop"; // @public -export type TestRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p90" | "p95" | "p99" | "min" | "max"; +export type TestRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; // @public export type TestRunOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; @@ -689,6 +1893,21 @@ export type TestRunOperationsClientPFResult = "passed" | "undetermined" | "faile // @public export type TestRunOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +// @public +export type TestRunOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; + +// @public +export interface TestRunOperationsClientRegionalConfiguration { + engineInstances: number; + region: string; +} + +// @public +export type TestRunOperationsClientRequestDataLevel = "NONE" | "ERRORS"; + +// @public +export type TestRunOperationsClientResourceKind = "FunctionsFlexConsumption"; + // @public export interface TestRunOperationsClientResourceMetric { aggregation: string; @@ -713,64 +1932,140 @@ export type TestRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE // @public export type TestRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +// @public +export interface TestRunOperationsClientTargetResourceConfigurations { + kind: TestRunOperationsClientResourceKind; +} + +// @public +export type TestRunOperationsClientTargetResourceConfigurationsUnion = TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations | TestRunOperationsClientTargetResourceConfigurations; + // @public export interface TestRunOperationsClientTest { + autoStopCriteria?: TestRunOperationsClientAutoStopCriteria; + baselineTestRunId?: string; certificate?: TestRunOperationsClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; description?: string; displayName?: string; environmentVariables?: Record; readonly inputArtifacts?: TestRunOperationsClientTestInputArtifacts; keyvaultReferenceIdentityId?: string; keyvaultReferenceIdentityType?: string; + kind?: TestRunOperationsClientTestKind; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: TestRunOperationsClientLoadTestConfiguration; passFailCriteria?: TestRunOperationsClientPassFailCriteria; + publicIPDisabled?: boolean; secrets?: Record; subnetId?: string; - readonly testId?: string; + readonly testId: string; } // @public export interface TestRunOperationsClientTestAppComponents { components: Record; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; readonly testId?: string; } +// @public +export interface TestRunOperationsClientTestFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestRunOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestRunOperationsClientFileStatus; +} + // @public export interface TestRunOperationsClientTestInputArtifacts { - readonly additionalFileInfo?: TestRunOperationsClientFileInfo[]; - configFileInfo?: TestRunOperationsClientFileInfo; - inputArtifactsZipFileInfo?: TestRunOperationsClientFileInfo; - testScriptFileInfo?: TestRunOperationsClientFileInfo; - userPropFileInfo?: TestRunOperationsClientFileInfo; + readonly additionalFileInfo?: TestRunOperationsClientTestFileInfo[]; + configFileInfo?: TestRunOperationsClientTestFileInfo; + inputArtifactsZipFileInfo?: TestRunOperationsClientTestFileInfo; + testScriptFileInfo?: TestRunOperationsClientTestFileInfo; + urlTestConfigFileInfo?: TestRunOperationsClientTestFileInfo; + userPropFileInfo?: TestRunOperationsClientTestFileInfo; +} + +// @public +export type TestRunOperationsClientTestKind = "URL" | "JMX" | "Locust"; + +// @public +export interface TestRunOperationsClientTestProfile { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + targetResourceConfigurations?: TestRunOperationsClientTargetResourceConfigurationsUnion; + targetResourceId?: string; + testId?: string; + readonly testProfileId: string; +} + +// @public +export interface TestRunOperationsClientTestProfileRun { + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly durationInSeconds?: number; + readonly endDateTime?: Date; + readonly errorDetails?: TestRunOperationsClientErrorDetails[]; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly recommendations?: TestRunOperationsClientTestProfileRunRecommendation[]; + readonly startDateTime?: Date; + readonly status?: TestRunOperationsClientTestProfileRunStatus; + readonly targetResourceConfigurations?: TestRunOperationsClientTargetResourceConfigurationsUnion; + readonly targetResourceId?: string; + testProfileId?: string; + readonly testProfileRunId: string; + readonly testRunDetails?: Record; +} + +// @public +export interface TestRunOperationsClientTestProfileRunRecommendation { + category: TestRunOperationsClientRecommendationCategory; + configurations?: string[]; } +// @public +export type TestRunOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; + // @public export interface TestRunOperationsClientTestRun { + autoStopCriteria?: TestRunOperationsClientAutoStopCriteria; certificate?: TestRunOperationsClientCertificateMetadata; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; + debugLogsEnabled?: boolean; description?: string; displayName?: string; readonly duration?: number; - readonly endDateTime?: string; + readonly endDateTime?: Date; environmentVariables?: Record; readonly errorDetails?: TestRunOperationsClientErrorDetails[]; - readonly executedDateTime?: string; + readonly executedDateTime?: Date; + readonly kind?: TestRunOperationsClientTestKind; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; loadTestConfiguration?: TestRunOperationsClientLoadTestConfiguration; passFailCriteria?: TestRunOperationsClientPassFailCriteria; readonly portalUrl?: string; + readonly publicIPDisabled?: boolean; + readonly regionalStatistics?: Record; + requestDataLevel?: TestRunOperationsClientRequestDataLevel; secrets?: Record; - readonly startDateTime?: string; + readonly startDateTime?: Date; readonly status?: TestRunOperationsClientStatus; readonly subnetId?: string; readonly testArtifacts?: TestRunOperationsClientTestRunArtifacts; @@ -785,9 +2080,9 @@ export interface TestRunOperationsClientTestRun { export interface TestRunOperationsClientTestRunAppComponents { components: Record; readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; readonly testRunId?: string; } @@ -797,27 +2092,47 @@ export interface TestRunOperationsClientTestRunArtifacts { outputArtifacts?: TestRunOperationsClientTestRunOutputArtifacts; } +// @public +export interface TestRunOperationsClientTestRunDetail { + configurationId: string; + properties: Record; + status: TestRunOperationsClientStatus; +} + +// @public +export interface TestRunOperationsClientTestRunFileInfo { + readonly expireDateTime?: Date; + fileName: string; + readonly fileType?: TestRunOperationsClientFileType; + readonly url?: string; + readonly validationFailureDetails?: string; + readonly validationStatus?: TestRunOperationsClientFileStatus; +} + // @public export interface TestRunOperationsClientTestRunInputArtifacts { - readonly additionalFileInfo?: TestRunOperationsClientFileInfo[]; - configFileInfo?: TestRunOperationsClientFileInfo; - inputArtifactsZipFileInfo?: TestRunOperationsClientFileInfo; - testScriptFileInfo?: TestRunOperationsClientFileInfo; - userPropFileInfo?: TestRunOperationsClientFileInfo; + readonly additionalFileInfo?: TestRunOperationsClientTestRunFileInfo[]; + configFileInfo?: TestRunOperationsClientTestRunFileInfo; + inputArtifactsZipFileInfo?: TestRunOperationsClientTestRunFileInfo; + testScriptFileInfo?: TestRunOperationsClientTestRunFileInfo; + urlTestConfigFileInfo?: TestRunOperationsClientTestRunFileInfo; + userPropFileInfo?: TestRunOperationsClientTestRunFileInfo; } // @public export interface TestRunOperationsClientTestRunOutputArtifacts { - logsFileInfo?: TestRunOperationsClientFileInfo; - resultFileInfo?: TestRunOperationsClientFileInfo; + artifactsContainerInfo?: TestRunOperationsClientArtifactsContainerInfo; + logsFileInfo?: TestRunOperationsClientTestRunFileInfo; + reportFileInfo?: TestRunOperationsClientTestRunFileInfo; + resultFileInfo?: TestRunOperationsClientTestRunFileInfo; } // @public export interface TestRunOperationsClientTestRunServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; metrics?: Record; readonly testRunId?: string; } @@ -833,6 +2148,12 @@ export interface TestRunOperationsClientTestRunStatistics { readonly pct1ResTime?: number; readonly pct2ResTime?: number; readonly pct3ResTime?: number; + readonly pct75ResTime?: number; + readonly pct96ResTime?: number; + readonly pct97ResTime?: number; + readonly pct98ResTime?: number; + readonly pct9999ResTime?: number; + readonly pct999ResTime?: number; readonly receivedKBytesPerSec?: number; readonly sampleCount?: number; readonly sentKBytesPerSec?: number; @@ -843,10 +2164,10 @@ export interface TestRunOperationsClientTestRunStatistics { // @public export interface TestRunOperationsClientTestServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; - metrics?: Record; + readonly lastModifiedDateTime?: Date; + metrics: Record; readonly testId?: string; } @@ -859,25 +2180,20 @@ export interface TestRunOperationsClientTimeSeriesElement { dimensionValues?: TestRunOperationsClientDimensionValue[]; } -// @public -export interface TestRunOptionalParams extends OperationOptions { - contentType?: string; - oldTestRunId?: string; - updateIntervalInMs?: number; -} - // @public export interface TestRunOutputArtifacts { - logsFileInfo?: FileInfo; - resultFileInfo?: FileInfo; + artifactsContainerInfo?: ArtifactsContainerInfo; + logsFileInfo?: TestRunFileInfo; + reportFileInfo?: TestRunFileInfo; + resultFileInfo?: TestRunFileInfo; } // @public export interface TestRunServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; + readonly lastModifiedDateTime?: Date; metrics?: Record; readonly testRunId?: string; } @@ -893,6 +2209,12 @@ export interface TestRunStatistics { readonly pct1ResTime?: number; readonly pct2ResTime?: number; readonly pct3ResTime?: number; + readonly pct75ResTime?: number; + readonly pct96ResTime?: number; + readonly pct97ResTime?: number; + readonly pct98ResTime?: number; + readonly pct9999ResTime?: number; + readonly pct999ResTime?: number; readonly receivedKBytesPerSec?: number; readonly sampleCount?: number; readonly sentKBytesPerSec?: number; @@ -903,10 +2225,10 @@ export interface TestRunStatistics { // @public export interface TestServerMetricConfig { readonly createdBy?: string; - readonly createdDateTime?: string; + readonly createdDateTime?: Date; readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: string; - metrics?: Record; + readonly lastModifiedDateTime?: Date; + metrics: Record; readonly testId?: string; } @@ -921,7 +2243,6 @@ export interface TimeSeriesElement { // @public export interface UploadTestFileOptionalParams extends OperationOptions { - // (undocumented) contentType?: string; fileType?: FileType; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index aba71240a2..54ba15307b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -56,11 +56,15 @@ export class AdministrationOperationsClient { credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, ) { - this._client = createAdministrationOperations( - endpointParam, - credential, - options, - ); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : "azsdk-js-client"; + + this._client = createAdministrationOperations(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 54a0bdef28..8bc2c2a6ab 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -19,6 +19,14 @@ export function createAdministrationOperations( credential: TokenCredential, options: AdministrationOperationsClientOptions = {}, ): LoadTestServiceContext { - const clientContext = getClient(endpointParam, credential, options); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api` + : "azsdk-js-api"; + + const clientContext = getClient(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index 8143e00653..b006f380b8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -134,7 +134,11 @@ export async function _createOrUpdateTestDeserialize( return { passFailCriteria: !result.body.passFailCriteria ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + : { + passFailMetrics: result.body.passFailCriteria?.[ + "passFailMetrics" + ] as any, + }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -143,7 +147,7 @@ export async function _createOrUpdateTestDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"], + secrets: result.body["secrets"] as any, certificate: !result.body.certificate ? undefined : { @@ -151,7 +155,7 @@ export async function _createOrUpdateTestDeserialize( type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"], + environmentVariables: result.body["environmentVariables"] as any, loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -194,10 +198,12 @@ export async function _createOrUpdateTestDeserialize( ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] : result.body.loadTestConfiguration?.[ "regionalLoadTestConfig" - ].map((p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - })), + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts @@ -346,17 +352,19 @@ export async function _createOrUpdateTestDeserialize( additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + }; + }), }, testId: result.body["testId"], description: result.body["description"], @@ -426,7 +434,7 @@ export async function _createOrUpdateAppComponentsDeserialize( } return { - components: result.body["components"], + components: result.body["components"] as any, testId: result.body["testId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -496,7 +504,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], - metrics: result.body["metrics"], + metrics: result.body["metrics"] as any, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -551,7 +559,7 @@ export async function _getAppComponentsDeserialize( } return { - components: result.body["components"], + components: result.body["components"] as any, testId: result.body["testId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -600,7 +608,7 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], - metrics: result.body["metrics"], + metrics: result.body["metrics"] as any, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -649,7 +657,11 @@ export async function _getTestDeserialize( return { passFailCriteria: !result.body.passFailCriteria ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + : { + passFailMetrics: result.body.passFailCriteria?.[ + "passFailMetrics" + ] as any, + }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -658,7 +670,7 @@ export async function _getTestDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"], + secrets: result.body["secrets"] as any, certificate: !result.body.certificate ? undefined : { @@ -666,7 +678,7 @@ export async function _getTestDeserialize( type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"], + environmentVariables: result.body["environmentVariables"] as any, loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -709,10 +721,12 @@ export async function _getTestDeserialize( ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] : result.body.loadTestConfiguration?.[ "regionalLoadTestConfig" - ].map((p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - })), + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts @@ -861,17 +875,19 @@ export async function _getTestDeserialize( additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] - : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + }; + }), }, testId: result.body["testId"], description: result.body["description"], @@ -985,17 +1001,19 @@ export async function _listTestFilesDeserialize( } return { - value: result.body["value"].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + value: result.body["value"].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + }; + }), nextLink: result.body["nextLink"], }; } @@ -1045,239 +1063,250 @@ export async function _listTestsDeserialize( } return { - value: result.body["value"].map((p) => ({ - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], - type: p.certificate?.["type"] as CertificateType, - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - }), - ), - }, - baselineTestRunId: p["baselineTestRunId"], - inputArtifacts: !p.inputArtifacts - ? undefined - : { - configFileInfo: !p.inputArtifacts?.configFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.configFileInfo?.["fileName"], - url: p.inputArtifacts?.configFileInfo?.["url"], - fileType: p.inputArtifacts?.configFileInfo?.[ - "fileType" - ] as FileType, - expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: p.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: p.inputArtifacts?.testScriptFileInfo?.[ - "fileType" - ] as FileType, - expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.inputArtifacts?.userPropFileInfo - ? undefined - : { - fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], - url: p.inputArtifacts?.userPropFileInfo?.["url"], - fileType: p.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ] as FileType, - expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: p.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], - }, - inputArtifactsZipFileInfo: !p.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], - fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ] as FileType, - expireDateTime: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: p.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], - url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: p.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ] as FileType, - expireDateTime: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - p.inputArtifacts?.["additionalFileInfo"] === undefined - ? p.inputArtifacts?.["additionalFileInfo"] - : p.inputArtifacts?.["additionalFileInfo"].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, + value: result.body["value"].map((p) => { + return { + passFailCriteria: !p.passFailCriteria + ? undefined + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] as any }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, + secrets: p["secrets"] as any, + certificate: !p.certificate + ? undefined + : { + value: p.certificate?.["value"], + type: p.certificate?.["type"] as CertificateType, + name: p.certificate?.["name"], + }, + environmentVariables: p["environmentVariables"] as any, + loadTestConfiguration: !p.loadTestConfiguration + ? undefined + : { + engineInstances: p.loadTestConfiguration?.["engineInstances"], + splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], + quickStartTest: p.loadTestConfiguration?.["quickStartTest"], + optionalLoadTestConfig: !p.loadTestConfiguration + ?.optionalLoadTestConfig + ? undefined + : { + endpointUrl: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "endpointUrl" + ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], + virtualUsers: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "virtualUsers" + ], + rampUpTime: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "rampUpTime" + ], + duration: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "duration" + ], + }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }, + ), + }, + baselineTestRunId: p["baselineTestRunId"], + inputArtifacts: !p.inputArtifacts + ? undefined + : { + configFileInfo: !p.inputArtifacts?.configFileInfo + ? undefined + : { + fileName: p.inputArtifacts?.configFileInfo?.["fileName"], + url: p.inputArtifacts?.configFileInfo?.["url"], + fileType: p.inputArtifacts?.configFileInfo?.[ + "fileType" + ] as FileType, expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), - }, - testId: p["testId"], - description: p["description"], - displayName: p["displayName"], - subnetId: p["subnetId"], - kind: p["kind"] as TestKind, - publicIPDisabled: p["publicIPDisabled"], - keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], - keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - })), + validationStatus: p.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.inputArtifacts?.configFileInfo?.[ + "validationFailureDetails" + ], + }, + testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: p.inputArtifacts?.testScriptFileInfo?.["url"], + fileType: p.inputArtifacts?.testScriptFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.inputArtifacts?.testScriptFileInfo?.[ + "validationFailureDetails" + ], + }, + userPropFileInfo: !p.inputArtifacts?.userPropFileInfo + ? undefined + : { + fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], + url: p.inputArtifacts?.userPropFileInfo?.["url"], + fileType: p.inputArtifacts?.userPropFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.inputArtifacts?.userPropFileInfo?.[ + "validationFailureDetails" + ], + }, + inputArtifactsZipFileInfo: !p.inputArtifacts + ?.inputArtifactsZipFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], + fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationFailureDetails" + ], + }, + urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], + url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: p.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ] as FileType, + expireDateTime: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, + additionalFileInfo: + p.inputArtifacts?.["additionalFileInfo"] === undefined + ? p.inputArtifacts?.["additionalFileInfo"] + : p.inputArtifacts?.["additionalFileInfo"].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: p["validationFailureDetails"], + }; + }), + }, + testId: p["testId"], + description: p["description"], + displayName: p["displayName"], + subnetId: p["subnetId"], + kind: p["kind"] as TestKind, + publicIPDisabled: p["publicIPDisabled"], + keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], + keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + }; + }), nextLink: result.body["nextLink"], }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts index a47ec485da..3c84987934 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/loadTestServiceClient.ts @@ -28,7 +28,7 @@ export default function createClient( ): LoadTestServiceContext { const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - const userAgentInfo = `azsdk-js-load-testing-rest/1.0.1`; + const userAgentInfo = `azsdk-js-load-testing/1.0.1`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts index 521d111758..7a3cc43547 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts @@ -240,26 +240,28 @@ export async function _listTestProfilesDeserialize( } return { - value: result.body["value"].map((p) => ({ - testProfileId: p["testProfileId"], - displayName: p["displayName"], - description: p["description"], - testId: p["testId"], - targetResourceId: p["targetResourceId"], - targetResourceConfigurations: !p.targetResourceConfigurations - ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - })), + value: result.body["value"].map((p) => { + return { + testProfileId: p["testProfileId"], + displayName: p["displayName"], + description: p["description"], + testId: p["testId"], + targetResourceId: p["targetResourceId"], + targetResourceConfigurations: !p.targetResourceConfigurations + ? undefined + : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + }; + }), nextLink: result.body["nextLink"], }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts index b386495817..2f72fd93a3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts @@ -20,6 +20,14 @@ export function createTestProfileAdministrationOperations( credential: TokenCredential, options: TestProfileAdministrationOperationsClientOptions = {}, ): LoadTestServiceContext { - const clientContext = getClient(endpointParam, credential, options); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api` + : "azsdk-js-api"; + + const clientContext = getClient(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts index f77231f925..031cfd6334 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts @@ -33,10 +33,15 @@ export class TestProfileAdministrationOperationsClient { credential: TokenCredential, options: TestProfileAdministrationOperationsClientOptions = {}, ) { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : "azsdk-js-client"; + this._client = createTestProfileAdministrationOperations( endpointParam, credential, - options, + { ...options, userAgentOptions: { userAgentPrefix } }, ); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts index 2fccd67a52..847d3fb291 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts @@ -89,7 +89,9 @@ export async function _createOrUpdateTestProfileRunDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -99,14 +101,16 @@ export async function _createOrUpdateTestProfileRunDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], + testRunDetails: result.body["testRunDetails"] as any, recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] - : result.body["recommendations"].map((p) => ({ - category: p["category"] as RecommendationCategory, - configurations: p["configurations"], - })), + : result.body["recommendations"].map((p) => { + return { + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + }; + }), createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -214,7 +218,9 @@ export async function _getTestProfileRunDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -224,14 +230,16 @@ export async function _getTestProfileRunDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], + testRunDetails: result.body["testRunDetails"] as any, recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] - : result.body["recommendations"].map((p) => ({ - category: p["category"] as RecommendationCategory, - configurations: p["configurations"], - })), + : result.body["recommendations"].map((p) => { + return { + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + }; + }), createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -295,46 +303,54 @@ export async function _listTestProfileRunsDeserialize( } return { - value: result.body["value"].map((p) => ({ - testProfileRunId: p["testProfileRunId"], - displayName: p["displayName"], - description: p["description"], - testProfileId: p["testProfileId"], - targetResourceId: p["targetResourceId"], - targetResourceConfigurations: !p.targetResourceConfigurations - ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, - status: p["status"] as TestProfileRunStatus, - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p) => ({ message: p["message"] })), - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, - durationInSeconds: p["durationInSeconds"], - testRunDetails: p["testRunDetails"], - recommendations: - p["recommendations"] === undefined - ? p["recommendations"] - : p["recommendations"].map((p) => ({ - category: p["category"] as RecommendationCategory, - configurations: p["configurations"], - })), - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - })), + value: result.body["value"].map((p) => { + return { + testProfileRunId: p["testProfileRunId"], + displayName: p["displayName"], + description: p["description"], + testProfileId: p["testProfileId"], + targetResourceId: p["targetResourceId"], + targetResourceConfigurations: !p.targetResourceConfigurations + ? undefined + : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, + status: p["status"] as TestProfileRunStatus, + errorDetails: + p["errorDetails"] === undefined + ? p["errorDetails"] + : p["errorDetails"].map((p) => { + return { message: p["message"] }; + }), + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined + ? new Date(p["endDateTime"]) + : undefined, + durationInSeconds: p["durationInSeconds"], + testRunDetails: p["testRunDetails"] as any, + recommendations: + p["recommendations"] === undefined + ? p["recommendations"] + : p["recommendations"].map((p) => { + return { + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + }; + }), + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + }; + }), nextLink: result.body["nextLink"], }; } @@ -391,7 +407,9 @@ export async function _stopDeserialize( errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -401,14 +419,16 @@ export async function _stopDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"], + testRunDetails: result.body["testRunDetails"] as any, recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] - : result.body["recommendations"].map((p) => ({ - category: p["category"] as RecommendationCategory, - configurations: p["configurations"], - })), + : result.body["recommendations"].map((p) => { + return { + category: p["category"] as RecommendationCategory, + configurations: p["configurations"], + }; + }), createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts index 40b15e8933..ae4e5f3036 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts @@ -19,6 +19,14 @@ export function createTestProfileRunOperations( credential: TokenCredential, options: TestProfileRunOperationsClientOptions = {}, ): LoadTestServiceContext { - const clientContext = getClient(endpointParam, credential, options); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api` + : "azsdk-js-api"; + + const clientContext = getClient(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts index 686d77063c..21bd8823dd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts @@ -35,11 +35,15 @@ export class TestProfileRunOperationsClient { credential: TokenCredential, options: TestProfileRunOperationsClientOptions = {}, ) { - this._client = createTestProfileRunOperations( - endpointParam, - credential, - options, - ); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : "azsdk-js-client"; + + this._client = createTestProfileRunOperations(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 57274f20b7..3d56b66ec8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -150,7 +150,11 @@ export async function _createOrUpdateTestRunDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + : { + passFailMetrics: result.body.passFailCriteria?.[ + "passFailMetrics" + ] as any, + }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -159,7 +163,7 @@ export async function _createOrUpdateTestRunDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"], + secrets: result.body["secrets"] as any, certificate: !result.body.certificate ? undefined : { @@ -167,13 +171,15 @@ export async function _createOrUpdateTestRunDeserialize( type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"], + environmentVariables: result.body["environmentVariables"] as any, errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), + testRunStatistics: result.body["testRunStatistics"] as any, + regionalStatistics: result.body["regionalStatistics"] as any, loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -216,10 +222,12 @@ export async function _createOrUpdateTestRunDeserialize( ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] : result.body.loadTestConfiguration?.[ "regionalLoadTestConfig" - ].map((p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - })), + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -375,17 +383,20 @@ export async function _createOrUpdateTestRunDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + ].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: + p["validationFailureDetails"], + }; + }), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined @@ -579,7 +590,7 @@ export async function _createOrUpdateAppComponentsDeserialize( } return { - components: result.body["components"], + components: result.body["components"] as any, testRunId: result.body["testRunId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -651,7 +662,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], - metrics: result.body["metrics"], + metrics: result.body["metrics"] as any, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -740,7 +751,7 @@ export async function _getAppComponentsDeserialize( } return { - components: result.body["components"], + components: result.body["components"] as any, testRunId: result.body["testRunId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -792,7 +803,7 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], - metrics: result.body["metrics"], + metrics: result.body["metrics"] as any, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -841,7 +852,11 @@ export async function _getTestRunDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + : { + passFailMetrics: result.body.passFailCriteria?.[ + "passFailMetrics" + ] as any, + }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -850,7 +865,7 @@ export async function _getTestRunDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"], + secrets: result.body["secrets"] as any, certificate: !result.body.certificate ? undefined : { @@ -858,13 +873,15 @@ export async function _getTestRunDeserialize( type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"], + environmentVariables: result.body["environmentVariables"] as any, errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), + testRunStatistics: result.body["testRunStatistics"] as any, + regionalStatistics: result.body["regionalStatistics"] as any, loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -907,10 +924,12 @@ export async function _getTestRunDeserialize( ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] : result.body.loadTestConfiguration?.[ "regionalLoadTestConfig" - ].map((p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - })), + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -1066,17 +1085,20 @@ export async function _getTestRunDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + ].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: + p["validationFailureDetails"], + }; + }), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined @@ -1385,27 +1407,28 @@ export async function _listMetricDefinitionsDeserialize( } return { - value: result.body["value"].map((p) => ({ - dimensions: - p["dimensions"] === undefined - ? p["dimensions"] - : p["dimensions"].map((p) => ({ - description: p["description"], - name: p["name"], - })), - description: p["description"], - name: p["name"], - namespace: p["namespace"], - primaryAggregationType: p["primaryAggregationType"] as AggregationType, - supportedAggregationTypes: p["supportedAggregationTypes"], - unit: p["unit"] as MetricUnit, - metricAvailabilities: - p["metricAvailabilities"] === undefined - ? p["metricAvailabilities"] - : p["metricAvailabilities"].map((p) => ({ - timeGrain: p["timeGrain"] as TimeGrain, - })), - })), + value: result.body["value"].map((p) => { + return { + dimensions: + p["dimensions"] === undefined + ? p["dimensions"] + : p["dimensions"].map((p) => { + return { description: p["description"], name: p["name"] }; + }), + description: p["description"], + name: p["name"], + namespace: p["namespace"], + primaryAggregationType: p["primaryAggregationType"] as AggregationType, + supportedAggregationTypes: p["supportedAggregationTypes"], + unit: p["unit"] as MetricUnit, + metricAvailabilities: + p["metricAvailabilities"] === undefined + ? p["metricAvailabilities"] + : p["metricAvailabilities"].map((p) => { + return { timeGrain: p["timeGrain"] as TimeGrain }; + }), + }; + }), }; } @@ -1448,10 +1471,9 @@ export async function _listMetricNamespacesDeserialize( } return { - value: result.body["value"].map((p) => ({ - description: p["description"], - name: p["name"], - })), + value: result.body["value"].map((p) => { + return { description: p["description"], name: p["name"] }; + }), }; } @@ -1509,25 +1531,28 @@ export async function _listMetricsDeserialize( } return { - value: result.body["value"].map((p) => ({ - data: - p["data"] === undefined - ? p["data"] - : p["data"].map((p) => ({ - timestamp: - p["timestamp"] !== undefined - ? new Date(p["timestamp"]) - : undefined, - value: p["value"], - })), - dimensionValues: - p["dimensionValues"] === undefined - ? p["dimensionValues"] - : p["dimensionValues"].map((p) => ({ - name: p["name"], - value: p["value"], - })), - })), + value: result.body["value"].map((p) => { + return { + data: + p["data"] === undefined + ? p["data"] + : p["data"].map((p) => { + return { + timestamp: + p["timestamp"] !== undefined + ? new Date(p["timestamp"]) + : undefined, + value: p["value"], + }; + }), + dimensionValues: + p["dimensionValues"] === undefined + ? p["dimensionValues"] + : p["dimensionValues"].map((p) => { + return { name: p["name"], value: p["value"] }; + }), + }; + }), nextLink: result.body["nextLink"], }; } @@ -1591,396 +1616,421 @@ export async function _listTestRunsDeserialize( } return { - value: result.body["value"].map((p) => ({ - testRunId: p["testRunId"], - passFailCriteria: !p.passFailCriteria - ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, - secrets: p["secrets"], - certificate: !p.certificate - ? undefined - : { - value: p.certificate?.["value"], - type: p.certificate?.["type"] as CertificateType, - name: p.certificate?.["name"], - }, - environmentVariables: p["environmentVariables"], - errorDetails: - p["errorDetails"] === undefined - ? p["errorDetails"] - : p["errorDetails"].map((p) => ({ message: p["message"] })), - testRunStatistics: p["testRunStatistics"], - regionalStatistics: p["regionalStatistics"], - loadTestConfiguration: !p.loadTestConfiguration - ? undefined - : { - engineInstances: p.loadTestConfiguration?.["engineInstances"], - splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], - quickStartTest: p.loadTestConfiguration?.["quickStartTest"], - optionalLoadTestConfig: !p.loadTestConfiguration - ?.optionalLoadTestConfig - ? undefined - : { - endpointUrl: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "endpointUrl" - ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], - virtualUsers: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "virtualUsers" - ], - rampUpTime: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "rampUpTime" - ], - duration: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "duration" - ], - }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - }), - ), - }, - testArtifacts: !p.testArtifacts - ? undefined - : { - inputArtifacts: !p.testArtifacts?.inputArtifacts - ? undefined - : { - configFileInfo: !p.testArtifacts?.inputArtifacts - ?.configFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "url" - ], - fileType: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.configFileInfo?.[ - "validationFailureDetails" - ], - }, - testScriptFileInfo: !p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.testScriptFileInfo?.[ - "validationFailureDetails" - ], - }, - userPropFileInfo: !p.testArtifacts?.inputArtifacts - ?.userPropFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ - "validationFailureDetails" - ], + value: result.body["value"].map((p) => { + return { + testRunId: p["testRunId"], + passFailCriteria: !p.passFailCriteria + ? undefined + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] as any }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, + secrets: p["secrets"] as any, + certificate: !p.certificate + ? undefined + : { + value: p.certificate?.["value"], + type: p.certificate?.["type"] as CertificateType, + name: p.certificate?.["name"], + }, + environmentVariables: p["environmentVariables"] as any, + errorDetails: + p["errorDetails"] === undefined + ? p["errorDetails"] + : p["errorDetails"].map((p) => { + return { message: p["message"] }; + }), + testRunStatistics: p["testRunStatistics"] as any, + regionalStatistics: p["regionalStatistics"] as any, + loadTestConfiguration: !p.loadTestConfiguration + ? undefined + : { + engineInstances: p.loadTestConfiguration?.["engineInstances"], + splitAllCSVs: p.loadTestConfiguration?.["splitAllCSVs"], + quickStartTest: p.loadTestConfiguration?.["quickStartTest"], + optionalLoadTestConfig: !p.loadTestConfiguration + ?.optionalLoadTestConfig + ? undefined + : { + endpointUrl: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "endpointUrl" + ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], + virtualUsers: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "virtualUsers" + ], + rampUpTime: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "rampUpTime" + ], + duration: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "duration" + ], + }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; }, - inputArtifactsZipFileInfo: !p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts + ), + }, + testArtifacts: !p.testArtifacts + ? undefined + : { + inputArtifacts: !p.testArtifacts?.inputArtifacts + ? undefined + : { + configFileInfo: !p.testArtifacts?.inputArtifacts + ?.configFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "validationFailureDetails" + ], + }, + testScriptFileInfo: !p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.[ + "validationFailureDetails" + ], + }, + userPropFileInfo: !p.testArtifacts?.inputArtifacts + ?.userPropFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "validationFailureDetails" + ], + }, + inputArtifactsZipFileInfo: !p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ - "validationFailureDetails" - ], - }, - urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, - validationFailureDetails: - p.testArtifacts?.inputArtifacts + "fileType" + ] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "validationFailureDetails" + ], + }, + urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, - additionalFileInfo: - p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] === - undefined - ? p.testArtifacts?.inputArtifacts?.["additionalFileInfo"] - : p.testArtifacts?.inputArtifacts?.[ - "additionalFileInfo" - ].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, + additionalFileInfo: + p.testArtifacts?.inputArtifacts?.[ + "additionalFileInfo" + ] === undefined + ? p.testArtifacts?.inputArtifacts?.[ + "additionalFileInfo" + ] + : p.testArtifacts?.inputArtifacts?.[ + "additionalFileInfo" + ].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p["validationFailureDetails"], + }; + }), + }, + outputArtifacts: !p.testArtifacts?.outputArtifacts + ? undefined + : { + resultFileInfo: !p.testArtifacts?.outputArtifacts + ?.resultFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], + fileType: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"] as FileType, expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.[ + "validationStatus" + ] as FileStatus, validationFailureDetails: - p["validationFailureDetails"], - })), - }, - outputArtifacts: !p.testArtifacts?.outputArtifacts - ? undefined - : { - resultFileInfo: !p.testArtifacts?.outputArtifacts - ?.resultFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "url" - ], - fileType: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ - "validationFailureDetails" + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "validationFailureDetails" + ], + }, + logsFileInfo: !p.testArtifacts?.outputArtifacts + ?.logsFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" ], - }, - logsFileInfo: !p.testArtifacts?.outputArtifacts?.logsFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], - fileType: p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "validationFailureDetails" - ], - }, - artifactsContainerInfo: !p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo - ? undefined - : { - url: p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !p.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "url" - ], - fileType: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"] as FileType, - expireDateTime: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"] as FileStatus, - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationFailureDetails" - ], - }, - }, - }, - testResult: p["testResult"] as PFTestResult, - virtualUsers: p["virtualUsers"], - displayName: p["displayName"], - testId: p["testId"], - description: p["description"], - status: p["status"] as Status, - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined ? new Date(p["endDateTime"]) : undefined, - executedDateTime: - p["executedDateTime"] !== undefined - ? new Date(p["executedDateTime"]) - : undefined, - portalUrl: p["portalUrl"], - duration: p["duration"], - subnetId: p["subnetId"], - kind: p["kind"] as TestKind, - requestDataLevel: p["requestDataLevel"] as RequestDataLevel, - debugLogsEnabled: p["debugLogsEnabled"], - publicIPDisabled: p["publicIPDisabled"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, - createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, - lastModifiedBy: p["lastModifiedBy"], - })), + fileType: p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationStatus"] as FileStatus, + validationFailureDetails: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "validationFailureDetails" + ], + }, + artifactsContainerInfo: !p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo + ? undefined + : { + url: p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.[ + "expireDateTime" + ], + ) + : undefined, + }, + reportFileInfo: !p.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"] as FileType, + expireDateTime: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.[ + "validationStatus" + ] as FileStatus, + validationFailureDetails: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "validationFailureDetails" + ], + }, + }, + }, + testResult: p["testResult"] as PFTestResult, + virtualUsers: p["virtualUsers"], + displayName: p["displayName"], + testId: p["testId"], + description: p["description"], + status: p["status"] as Status, + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined + ? new Date(p["endDateTime"]) + : undefined, + executedDateTime: + p["executedDateTime"] !== undefined + ? new Date(p["executedDateTime"]) + : undefined, + portalUrl: p["portalUrl"], + duration: p["duration"], + subnetId: p["subnetId"], + kind: p["kind"] as TestKind, + requestDataLevel: p["requestDataLevel"] as RequestDataLevel, + debugLogsEnabled: p["debugLogsEnabled"], + publicIPDisabled: p["publicIPDisabled"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, + createdBy: p["createdBy"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, + lastModifiedBy: p["lastModifiedBy"], + }; + }), nextLink: result.body["nextLink"], }; } @@ -2021,7 +2071,11 @@ export async function _stopDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + : { + passFailMetrics: result.body.passFailCriteria?.[ + "passFailMetrics" + ] as any, + }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -2030,7 +2084,7 @@ export async function _stopDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"], + secrets: result.body["secrets"] as any, certificate: !result.body.certificate ? undefined : { @@ -2038,13 +2092,15 @@ export async function _stopDeserialize( type: result.body.certificate?.["type"] as CertificateType, name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"], + environmentVariables: result.body["environmentVariables"] as any, errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] - : result.body["errorDetails"].map((p) => ({ message: p["message"] })), - testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], + : result.body["errorDetails"].map((p) => { + return { message: p["message"] }; + }), + testRunStatistics: result.body["testRunStatistics"] as any, + regionalStatistics: result.body["regionalStatistics"] as any, loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -2087,10 +2143,12 @@ export async function _stopDeserialize( ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] : result.body.loadTestConfiguration?.[ "regionalLoadTestConfig" - ].map((p) => ({ - engineInstances: p["engineInstances"], - region: p["region"], - })), + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -2246,17 +2304,20 @@ export async function _stopDeserialize( ] : result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" - ].map((p) => ({ - fileName: p["fileName"], - url: p["url"], - fileType: p["fileType"] as FileType, - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, - validationStatus: p["validationStatus"] as FileStatus, - validationFailureDetails: p["validationFailureDetails"], - })), + ].map((p) => { + return { + fileName: p["fileName"], + url: p["url"], + fileType: p["fileType"] as FileType, + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, + validationStatus: p["validationStatus"] as FileStatus, + validationFailureDetails: + p["validationFailureDetails"], + }; + }), }, outputArtifacts: !result.body.testArtifacts?.outputArtifacts ? undefined diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index cff7cc0f3f..7e596e790f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -19,6 +19,14 @@ export function createTestRunOperations( credential: TokenCredential, options: TestRunOperationsClientOptions = {}, ): LoadTestServiceContext { - const clientContext = getClient(endpointParam, credential, options); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api` + : "azsdk-js-api"; + + const clientContext = getClient(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); return clientContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index 3ee7201db9..ebfe8870c3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -64,7 +64,15 @@ export class TestRunOperationsClient { credential: TokenCredential, options: TestRunOperationsClientOptions = {}, ) { - this._client = createTestRunOperations(endpointParam, credential, options); + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : "azsdk-js-client"; + + this._client = createTestRunOperations(endpointParam, credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); this.pipeline = this._client.pipeline; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts index 231e0b7c22..a4d8acf862 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/test/public/utils/recordedClient.ts @@ -1,19 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { Context } from "mocha"; -import { Recorder, RecorderStartOptions } from "@azure-tools/test-recorder"; +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; -const envSetupForPlayback: Record = { - ENDPOINT: "https://endpoint", - AZURE_CLIENT_ID: "azure_client_id", - AZURE_CLIENT_SECRET: "azure_client_secret", - AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888", +const replaceableVariables: Record = { SUBSCRIPTION_ID: "azure_subscription_id", }; const recorderEnvSetup: RecorderStartOptions = { - envSetupForPlayback, + envSetupForPlayback: replaceableVariables, }; /** @@ -21,8 +20,10 @@ const recorderEnvSetup: RecorderStartOptions = { * Should be called first in the test suite to make sure environment variables are * read before they are being used. */ -export async function createRecorder(context: Context): Promise { - const recorder = new Recorder(context.currentTest); +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); await recorder.start(recorderEnvSetup); return recorder; } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 1c186dd9c4..e2a2a1e13f 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -1283,6 +1283,9 @@ export function deserializeResponseValue( } } return restValue; + case "dict": + // TODO: Need to handle the dictionary cases + return `${restValue} as any`; default: return restValue; } From fa95b142568b39ef71798e5328b29e6df23d394a Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 11:59:29 +0800 Subject: [PATCH 09/18] Update the tsp file --- .../test/loadtesting_modular/spec/client.tsp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp index 021393f03c..cd11aa13d1 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp @@ -1,7 +1,9 @@ import "./main.tsp"; import "@azure-tools/typespec-client-generator-core"; +import "@typespec/rest"; using TypeSpec.Versioning; +using TypeSpec.Rest; using Azure.ClientGenerator.Core; using Microsoft.LoadTestService; @@ -57,8 +59,8 @@ interface TestRunOperations { listMetrics is LoadTestRun.listMetrics; listTestRuns is LoadTestRun.listTestRuns; #suppress "@azure-tools/typespec-azure-core/no-operation-id" - @clientName("stopTestRun", "javascript,python,java,csharp,go") - stop is LoadTestRun.stop; + @action("stop") + stopTestRun is LoadTestRun.stop; } @client({ @@ -82,6 +84,6 @@ interface TestProfileRunOperations { getTestProfileRun is TestProfileRunAdministration.getTestProfileRun; listTestProfileRuns is TestProfileRunAdministration.listTestProfileRuns; #suppress "@azure-tools/typespec-azure-core/no-operation-id" - @clientName("stopTestProfileRun", "javascript,python,java,csharp,go") - stop is TestProfileRunAdministration.stop; + @action("stop") + stopTestProfileRun is TestProfileRunAdministration.stop; } From cd32c3d06da0e825eaa215913905efac5751ee88 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 12:05:25 +0800 Subject: [PATCH 10/18] Update the loadtesting files --- .../typespec-ts/review/load-testing.api.md | 14 ++++++------- .../generated/typespec-ts/src/index.ts | 4 ++-- .../src/testProfileRunOperations/api/index.ts | 2 +- .../api/operations.ts | 20 +++++++++++-------- .../src/testProfileRunOperations/index.ts | 2 +- .../testProfileRunOperations/models/index.ts | 2 +- .../models/options.ts | 2 +- .../testProfileRunOperationsClient.ts | 10 +++++----- .../src/testRunOperations/api/index.ts | 2 +- .../src/testRunOperations/api/operations.ts | 16 +++++++-------- .../src/testRunOperations/index.ts | 2 +- .../src/testRunOperations/models/index.ts | 2 +- .../src/testRunOperations/models/options.ts | 2 +- .../testRunOperationsClient.ts | 10 +++++----- 14 files changed, 47 insertions(+), 43 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index c967e7cbb2..477322e839 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -436,7 +436,11 @@ export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; export type Status = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; // @public -export interface StopOptionalParams extends OperationOptions { +export interface StopTestProfileRunOptionalParams extends OperationOptions { +} + +// @public +export interface StopTestRunOptionalParams extends OperationOptions { } // @public @@ -1052,7 +1056,7 @@ export class TestProfileRunOperationsClient { getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; listTestProfileRuns(options?: ListTestProfileRunsOptionalParams): TestProfileRunOperationsClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; - stop(testProfileRunId: string, options?: TestProfileRunOperationsClientStopOptionalParams): Promise; + stopTestProfileRun(testProfileRunId: string, options?: StopTestProfileRunOptionalParams): Promise; } // @public @@ -1302,10 +1306,6 @@ export type TestProfileRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRE // @public export type TestProfileRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; -// @public -export interface TestProfileRunOperationsClientStopOptionalParams extends OperationOptions { -} - // @public export interface TestProfileRunOperationsClientTargetResourceConfigurations { kind: TestProfileRunOperationsClientResourceKind; @@ -1664,7 +1664,7 @@ export class TestRunOperationsClient { listMetrics(testRunId: string, metricname: string, metricNamespace: string, timespan: string, body?: TestRunOperationsClientMetricRequestPayload, options?: ListMetricsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; listTestRuns(options?: ListTestRunsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; - stop(testRunId: string, options?: StopOptionalParams): Promise; + stopTestRun(testRunId: string, options?: StopTestRunOptionalParams): Promise; } // @public diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 9bfd8e72fc..6458b009a9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -168,7 +168,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, PageSettings as TestRunOperationsClientPageSettings, ContinuablePage as TestRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestRunOperationsClientPagedAsyncIterableIterator, @@ -323,7 +323,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopOptionalParams as TestProfileRunOperationsClientStopOptionalParams, + StopTestProfileRunOptionalParams, PageSettings as TestProfileRunOperationsClientPageSettings, ContinuablePage as TestProfileRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestProfileRunOperationsClientPagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts index 5acd70fe5d..2d642b00d5 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts @@ -6,7 +6,7 @@ export { deleteTestProfileRun, getTestProfileRun, listTestProfileRuns, - stop, + stopTestProfileRun, } from "./operations.js"; export { createTestProfileRunOperations, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts index 847d3fb291..8ba9e3522c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts @@ -35,7 +35,7 @@ import { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopOptionalParams, + StopTestProfileRunOptionalParams, } from "../models/options.js"; export function _createOrUpdateTestProfileRunSend( @@ -368,10 +368,10 @@ export function listTestProfileRuns( ); } -export function _stopSend( +export function _stopTestProfileRunSend( context: Client, testProfileRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | TestProfileRunAdministrationStop200Response | TestProfileRunAdministrationStopDefaultResponse @@ -381,7 +381,7 @@ export function _stopSend( .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopDeserialize( +export async function _stopTestProfileRunDeserialize( result: | TestProfileRunAdministrationStop200Response | TestProfileRunAdministrationStopDefaultResponse, @@ -443,11 +443,15 @@ export async function _stopDeserialize( } /** Stop test profile run for the given test profile run Id. */ -export async function stop( +export async function stopTestProfileRun( context: Client, testProfileRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopSend(context, testProfileRunId, options); - return _stopDeserialize(result); + const result = await _stopTestProfileRunSend( + context, + testProfileRunId, + options, + ); + return _stopTestProfileRunDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts index 1e4d04259a..65b6e576e2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts @@ -74,7 +74,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopOptionalParams, + StopTestProfileRunOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts index 9b0e075fff..7c846c70ef 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts @@ -72,7 +72,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopOptionalParams, + StopTestProfileRunOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts index 998363629b..f4a3642273 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts @@ -41,4 +41,4 @@ export interface ListTestProfileRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopOptionalParams extends OperationOptions {} +export interface StopTestProfileRunOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts index 21bd8823dd..7714d981c6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts @@ -9,7 +9,7 @@ import { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopOptionalParams, + StopTestProfileRunOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { @@ -17,7 +17,7 @@ import { deleteTestProfileRun, getTestProfileRun, listTestProfileRuns, - stop, + stopTestProfileRun, createTestProfileRunOperations, TestProfileRunOperationsClientOptions, LoadTestServiceContext, @@ -87,10 +87,10 @@ export class TestProfileRunOperationsClient { } /** Stop test profile run for the given test profile run Id. */ - stop( + stopTestProfileRun( testProfileRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): Promise { - return stop(this._client, testProfileRunId, options); + return stopTestProfileRun(this._client, testProfileRunId, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index 8e35dc0cd3..de60e781ee 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -15,7 +15,7 @@ export { listMetricNamespaces, listMetrics, listTestRuns, - stop, + stopTestRun, } from "./operations.js"; export { createTestRunOperations, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 3d56b66ec8..d9a15328bc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -88,7 +88,7 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "../models/options.js"; export function _createOrUpdateTestRunSend( @@ -2048,10 +2048,10 @@ export function listTestRuns( ); } -export function _stopSend( +export function _stopTestRunSend( context: Client, testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunStop200Response | LoadTestRunStopDefaultResponse > { @@ -2060,7 +2060,7 @@ export function _stopSend( .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopDeserialize( +export async function _stopTestRunDeserialize( result: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, ): Promise { if (isUnexpected(result)) { @@ -2460,11 +2460,11 @@ export async function _stopDeserialize( } /** Stop test run by test run Id. */ -export async function stop( +export async function stopTestRun( context: Client, testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopSend(context, testRunId, options); - return _stopDeserialize(result); + const result = await _stopTestRunSend(context, testRunId, options); + return _stopTestRunDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index a975e76b1e..7c2e7c297e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -83,7 +83,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index cda684bcff..06b876ffed 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -81,7 +81,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index b7d2fc2c49..170b68325d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -94,4 +94,4 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopOptionalParams extends OperationOptions {} +export interface StopTestRunOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index ebfe8870c3..d320d25083 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -29,7 +29,7 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { @@ -46,7 +46,7 @@ import { listMetricNamespaces, listMetrics, listTestRuns, - stop, + stopTestRun, createTestRunOperations, TestRunOperationsClientOptions, LoadTestServiceContext, @@ -230,10 +230,10 @@ export class TestRunOperationsClient { } /** Stop test run by test run Id. */ - stop( + stopTestRun( testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - return stop(this._client, testRunId, options); + return stopTestRun(this._client, testRunId, options); } } From 79036e99fe0888d3c81b681006d153a659719c29 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 14:46:44 +0800 Subject: [PATCH 11/18] Update the load testing cases --- .../typespec-ts/review/load-testing.api.md | 828 ++++++++++++++++-- .../api/operations.ts | 249 +++--- .../src/administrationOperations/index.ts | 18 + .../administrationOperations/models/index.ts | 18 + .../administrationOperations/models/models.ts | 614 ++++++++++--- .../generated/typespec-ts/src/index.ts | 72 ++ .../api/operations.ts | 15 +- .../index.ts | 18 + .../models/index.ts | 18 + .../models/models.ts | 614 ++++++++++--- .../api/operations.ts | 52 +- .../src/testProfileRunOperations/index.ts | 18 + .../testProfileRunOperations/models/index.ts | 18 + .../testProfileRunOperations/models/models.ts | 614 ++++++++++--- .../src/testRunOperations/api/operations.ts | 530 ++++++----- .../src/testRunOperations/index.ts | 18 + .../src/testRunOperations/models/index.ts | 18 + .../src/testRunOperations/models/models.ts | 614 ++++++++++--- .../test/loadtesting_modular/tspconfig.yaml | 1 + .../src/modular/helpers/operationHelpers.ts | 3 - 20 files changed, 3387 insertions(+), 963 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index 477322e839..34fe75a159 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -45,7 +45,7 @@ export interface AdministrationOperationsClientOptions extends ClientOptions { } // @public -export type AggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; +export type AggregationType = string; // @public export type APIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; @@ -82,7 +82,7 @@ export interface CertificateMetadata { } // @public -export type CertificateType = "AKV_CERT_URI"; +export type CertificateType = string; // @public export type ContinuablePage = TPage & { @@ -165,10 +165,10 @@ export interface ErrorDetails { } // @public -export type FileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type FileStatus = string; // @public -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; +export type FileType = string; // @public export interface FunctionFlexConsumptionResourceConfiguration { @@ -214,6 +214,177 @@ export interface GetTestRunFileOptionalParams extends OperationOptions { export interface GetTestRunOptionalParams extends OperationOptions { } +// @public +export enum KnownAggregationType { + Average = "Average", + Count = "Count", + None = "None", + Percentile75 = "Percentile75", + Percentile90 = "Percentile90", + Percentile95 = "Percentile95", + Percentile96 = "Percentile96", + Percentile97 = "Percentile97", + Percentile98 = "Percentile98", + Percentile99 = "Percentile99", + Percentile999 = "Percentile999", + Percentile9999 = "Percentile9999", + Total = "Total" +} + +// @public +export enum KnownCertificateType { + AKV_CERT_URI = "AKV_CERT_URI" +} + +// @public +export enum KnownFileStatus { + NOT_VALIDATED = "NOT_VALIDATED", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_INITIATED = "VALIDATION_INITIATED", + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum KnownFileType { + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + JMX_FILE = "JMX_FILE", + TEST_SCRIPT = "TEST_SCRIPT", + URL_TEST_CONFIG = "URL_TEST_CONFIG", + USER_PROPERTIES = "USER_PROPERTIES", + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" +} + +// @public +export enum KnownMetricUnit { + Bytes = "Bytes", + BytesPerSecond = "BytesPerSecond", + Count = "Count", + CountPerSecond = "CountPerSecond", + Milliseconds = "Milliseconds", + NotSpecified = "NotSpecified", + Percent = "Percent", + Seconds = "Seconds" +} + +// @public +export enum KnownPFAction { + "continue" = "continue", + stop = "stop" +} + +// @public +export enum KnownPFAgFunc { + "p99.9" = "p99.9", + "p99.99" = "p99.99", + avg = "avg", + count = "count", + max = "max", + min = "min", + p50 = "p50", + p75 = "p75", + p90 = "p90", + p95 = "p95", + p96 = "p96", + p97 = "p97", + p98 = "p98", + p99 = "p99", + percentage = "percentage" +} + +// @public +export enum KnownPFMetrics { + error = "error", + latency = "latency", + requests = "requests", + requests_per_sec = "requests_per_sec", + response_time_ms = "response_time_ms" +} + +// @public +export enum KnownPFResult { + failed = "failed", + passed = "passed", + undetermined = "undetermined" +} + +// @public +export enum KnownPFTestResult { + FAILED = "FAILED", + NOT_APPLICABLE = "NOT_APPLICABLE", + PASSED = "PASSED" +} + +// @public +export enum KnownRecommendationCategory { + CostOptimized = "CostOptimized", + ThroughputOptimized = "ThroughputOptimized" +} + +// @public +export enum KnownRequestDataLevel { + ERRORS = "ERRORS", + NONE = "NONE" +} + +// @public +export enum KnownResourceKind { + FunctionsFlexConsumption = "FunctionsFlexConsumption" +} + +// @public +export enum KnownSecretType { + AKV_SECRET_URI = "AKV_SECRET_URI", + SECRET_VALUE = "SECRET_VALUE" +} + +// @public +export enum KnownStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + CONFIGURED = "CONFIGURED", + CONFIGURING = "CONFIGURING", + DEPROVISIONED = "DEPROVISIONED", + DEPROVISIONING = "DEPROVISIONING", + DONE = "DONE", + EXECUTED = "EXECUTED", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED", + PROVISIONED = "PROVISIONED", + PROVISIONING = "PROVISIONING", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum KnownTestKind { + JMX = "JMX", + Locust = "Locust", + URL = "URL" +} + +// @public +export enum KnownTestProfileRunStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + DONE = "DONE", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED" +} + +// @public +export enum KnownTimeGrain { + PT10S = "PT10S", + PT1H = "PT1H", + PT1M = "PT1M", + PT5M = "PT5M", + PT5S = "PT5S" +} + // @public export interface ListMetricDefinitionsOptionalParams extends OperationOptions { } @@ -328,7 +499,7 @@ export interface MetricRequestPayload { } // @public -export type MetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; +export type MetricUnit = string; // @public export interface MetricValue { @@ -382,22 +553,22 @@ export interface PassFailMetric { } // @public -export type PFAction = "continue" | "stop"; +export type PFAction = string; // @public -export type PFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; +export type PFAgFunc = string; // @public -export type PFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; +export type PFMetrics = string; // @public -export type PFResult = "passed" | "undetermined" | "failed"; +export type PFResult = string; // @public -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResult = string; // @public -export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +export type RecommendationCategory = string; // @public export interface RegionalConfiguration { @@ -406,10 +577,10 @@ export interface RegionalConfiguration { } // @public -export type RequestDataLevel = "NONE" | "ERRORS"; +export type RequestDataLevel = string; // @public -export type ResourceKind = "FunctionsFlexConsumption"; +export type ResourceKind = string; // @public export interface ResourceMetric { @@ -430,10 +601,10 @@ export interface Secret { } // @public -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretType = string; // @public -export type Status = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +export type Status = string; // @public export interface StopTestProfileRunOptionalParams extends OperationOptions { @@ -506,7 +677,7 @@ export interface TestInputArtifacts { } // @public -export type TestKind = "URL" | "JMX" | "Locust"; +export type TestKind = string; // @public export interface TestProfile { @@ -533,7 +704,7 @@ export class TestProfileAdministrationOperationsClient { } // @public -export type TestProfileAdministrationOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; +export type TestProfileAdministrationOperationsClientAggregationType = string; // @public export type TestProfileAdministrationOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; @@ -570,7 +741,7 @@ export interface TestProfileAdministrationOperationsClientCertificateMetadata { } // @public -export type TestProfileAdministrationOperationsClientCertificateType = "AKV_CERT_URI"; +export type TestProfileAdministrationOperationsClientCertificateType = string; // @public export type TestProfileAdministrationOperationsClientContinuablePage = TPage & { @@ -602,10 +773,10 @@ export interface TestProfileAdministrationOperationsClientErrorDetails { } // @public -export type TestProfileAdministrationOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type TestProfileAdministrationOperationsClientFileStatus = string; // @public -export type TestProfileAdministrationOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; +export type TestProfileAdministrationOperationsClientFileType = string; // @public export interface TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration { @@ -619,6 +790,177 @@ export interface TestProfileAdministrationOperationsClientFunctionFlexConsumptio kind: "FunctionsFlexConsumption"; } +// @public +export enum TestProfileAdministrationOperationsClientKnownAggregationType { + Average = "Average", + Count = "Count", + None = "None", + Percentile75 = "Percentile75", + Percentile90 = "Percentile90", + Percentile95 = "Percentile95", + Percentile96 = "Percentile96", + Percentile97 = "Percentile97", + Percentile98 = "Percentile98", + Percentile99 = "Percentile99", + Percentile999 = "Percentile999", + Percentile9999 = "Percentile9999", + Total = "Total" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownCertificateType { + AKV_CERT_URI = "AKV_CERT_URI" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownFileStatus { + NOT_VALIDATED = "NOT_VALIDATED", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_INITIATED = "VALIDATION_INITIATED", + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownFileType { + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + JMX_FILE = "JMX_FILE", + TEST_SCRIPT = "TEST_SCRIPT", + URL_TEST_CONFIG = "URL_TEST_CONFIG", + USER_PROPERTIES = "USER_PROPERTIES", + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownMetricUnit { + Bytes = "Bytes", + BytesPerSecond = "BytesPerSecond", + Count = "Count", + CountPerSecond = "CountPerSecond", + Milliseconds = "Milliseconds", + NotSpecified = "NotSpecified", + Percent = "Percent", + Seconds = "Seconds" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownPFAction { + "continue" = "continue", + stop = "stop" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownPFAgFunc { + "p99.9" = "p99.9", + "p99.99" = "p99.99", + avg = "avg", + count = "count", + max = "max", + min = "min", + p50 = "p50", + p75 = "p75", + p90 = "p90", + p95 = "p95", + p96 = "p96", + p97 = "p97", + p98 = "p98", + p99 = "p99", + percentage = "percentage" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownPFMetrics { + error = "error", + latency = "latency", + requests = "requests", + requests_per_sec = "requests_per_sec", + response_time_ms = "response_time_ms" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownPFResult { + failed = "failed", + passed = "passed", + undetermined = "undetermined" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownPFTestResult { + FAILED = "FAILED", + NOT_APPLICABLE = "NOT_APPLICABLE", + PASSED = "PASSED" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownRecommendationCategory { + CostOptimized = "CostOptimized", + ThroughputOptimized = "ThroughputOptimized" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownRequestDataLevel { + ERRORS = "ERRORS", + NONE = "NONE" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownResourceKind { + FunctionsFlexConsumption = "FunctionsFlexConsumption" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownSecretType { + AKV_SECRET_URI = "AKV_SECRET_URI", + SECRET_VALUE = "SECRET_VALUE" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + CONFIGURED = "CONFIGURED", + CONFIGURING = "CONFIGURING", + DEPROVISIONED = "DEPROVISIONED", + DEPROVISIONING = "DEPROVISIONING", + DONE = "DONE", + EXECUTED = "EXECUTED", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED", + PROVISIONED = "PROVISIONED", + PROVISIONING = "PROVISIONING", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownTestKind { + JMX = "JMX", + Locust = "Locust", + URL = "URL" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownTestProfileRunStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + DONE = "DONE", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED" +} + +// @public +export enum TestProfileAdministrationOperationsClientKnownTimeGrain { + PT10S = "PT10S", + PT1H = "PT1H", + PT1M = "PT1M", + PT5M = "PT5M", + PT5S = "PT5S" +} + // @public export interface TestProfileAdministrationOperationsClientLoadTestConfiguration { engineInstances?: number; @@ -667,7 +1009,7 @@ export interface TestProfileAdministrationOperationsClientMetricRequestPayload { } // @public -export type TestProfileAdministrationOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; +export type TestProfileAdministrationOperationsClientMetricUnit = string; // @public export interface TestProfileAdministrationOperationsClientMetricValue { @@ -726,22 +1068,22 @@ export interface TestProfileAdministrationOperationsClientPassFailMetric { } // @public -export type TestProfileAdministrationOperationsClientPFAction = "continue" | "stop"; +export type TestProfileAdministrationOperationsClientPFAction = string; // @public -export type TestProfileAdministrationOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; +export type TestProfileAdministrationOperationsClientPFAgFunc = string; // @public -export type TestProfileAdministrationOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; +export type TestProfileAdministrationOperationsClientPFMetrics = string; // @public -export type TestProfileAdministrationOperationsClientPFResult = "passed" | "undetermined" | "failed"; +export type TestProfileAdministrationOperationsClientPFResult = string; // @public -export type TestProfileAdministrationOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type TestProfileAdministrationOperationsClientPFTestResult = string; // @public -export type TestProfileAdministrationOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +export type TestProfileAdministrationOperationsClientRecommendationCategory = string; // @public export interface TestProfileAdministrationOperationsClientRegionalConfiguration { @@ -750,10 +1092,10 @@ export interface TestProfileAdministrationOperationsClientRegionalConfiguration } // @public -export type TestProfileAdministrationOperationsClientRequestDataLevel = "NONE" | "ERRORS"; +export type TestProfileAdministrationOperationsClientRequestDataLevel = string; // @public -export type TestProfileAdministrationOperationsClientResourceKind = "FunctionsFlexConsumption"; +export type TestProfileAdministrationOperationsClientResourceKind = string; // @public export interface TestProfileAdministrationOperationsClientResourceMetric { @@ -774,10 +1116,10 @@ export interface TestProfileAdministrationOperationsClientSecret { } // @public -export type TestProfileAdministrationOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type TestProfileAdministrationOperationsClientSecretType = string; // @public -export type TestProfileAdministrationOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +export type TestProfileAdministrationOperationsClientStatus = string; // @public export interface TestProfileAdministrationOperationsClientTargetResourceConfigurations { @@ -842,7 +1184,7 @@ export interface TestProfileAdministrationOperationsClientTestInputArtifacts { } // @public -export type TestProfileAdministrationOperationsClientTestKind = "URL" | "JMX" | "Locust"; +export type TestProfileAdministrationOperationsClientTestKind = string; // @public export interface TestProfileAdministrationOperationsClientTestProfile { @@ -886,7 +1228,7 @@ export interface TestProfileAdministrationOperationsClientTestProfileRunRecommen } // @public -export type TestProfileAdministrationOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; +export type TestProfileAdministrationOperationsClientTestProfileRunStatus = string; // @public export interface TestProfileAdministrationOperationsClientTestRun { @@ -1019,7 +1361,7 @@ export interface TestProfileAdministrationOperationsClientTestServerMetricConfig } // @public -export type TestProfileAdministrationOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TestProfileAdministrationOperationsClientTimeGrain = string; // @public export interface TestProfileAdministrationOperationsClientTimeSeriesElement { @@ -1060,7 +1402,7 @@ export class TestProfileRunOperationsClient { } // @public -export type TestProfileRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; +export type TestProfileRunOperationsClientAggregationType = string; // @public export type TestProfileRunOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; @@ -1097,7 +1439,7 @@ export interface TestProfileRunOperationsClientCertificateMetadata { } // @public -export type TestProfileRunOperationsClientCertificateType = "AKV_CERT_URI"; +export type TestProfileRunOperationsClientCertificateType = string; // @public export type TestProfileRunOperationsClientContinuablePage = TPage & { @@ -1129,10 +1471,10 @@ export interface TestProfileRunOperationsClientErrorDetails { } // @public -export type TestProfileRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type TestProfileRunOperationsClientFileStatus = string; // @public -export type TestProfileRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; +export type TestProfileRunOperationsClientFileType = string; // @public export interface TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration { @@ -1146,6 +1488,177 @@ export interface TestProfileRunOperationsClientFunctionFlexConsumptionTargetReso kind: "FunctionsFlexConsumption"; } +// @public +export enum TestProfileRunOperationsClientKnownAggregationType { + Average = "Average", + Count = "Count", + None = "None", + Percentile75 = "Percentile75", + Percentile90 = "Percentile90", + Percentile95 = "Percentile95", + Percentile96 = "Percentile96", + Percentile97 = "Percentile97", + Percentile98 = "Percentile98", + Percentile99 = "Percentile99", + Percentile999 = "Percentile999", + Percentile9999 = "Percentile9999", + Total = "Total" +} + +// @public +export enum TestProfileRunOperationsClientKnownCertificateType { + AKV_CERT_URI = "AKV_CERT_URI" +} + +// @public +export enum TestProfileRunOperationsClientKnownFileStatus { + NOT_VALIDATED = "NOT_VALIDATED", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_INITIATED = "VALIDATION_INITIATED", + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestProfileRunOperationsClientKnownFileType { + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + JMX_FILE = "JMX_FILE", + TEST_SCRIPT = "TEST_SCRIPT", + URL_TEST_CONFIG = "URL_TEST_CONFIG", + USER_PROPERTIES = "USER_PROPERTIES", + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" +} + +// @public +export enum TestProfileRunOperationsClientKnownMetricUnit { + Bytes = "Bytes", + BytesPerSecond = "BytesPerSecond", + Count = "Count", + CountPerSecond = "CountPerSecond", + Milliseconds = "Milliseconds", + NotSpecified = "NotSpecified", + Percent = "Percent", + Seconds = "Seconds" +} + +// @public +export enum TestProfileRunOperationsClientKnownPFAction { + "continue" = "continue", + stop = "stop" +} + +// @public +export enum TestProfileRunOperationsClientKnownPFAgFunc { + "p99.9" = "p99.9", + "p99.99" = "p99.99", + avg = "avg", + count = "count", + max = "max", + min = "min", + p50 = "p50", + p75 = "p75", + p90 = "p90", + p95 = "p95", + p96 = "p96", + p97 = "p97", + p98 = "p98", + p99 = "p99", + percentage = "percentage" +} + +// @public +export enum TestProfileRunOperationsClientKnownPFMetrics { + error = "error", + latency = "latency", + requests = "requests", + requests_per_sec = "requests_per_sec", + response_time_ms = "response_time_ms" +} + +// @public +export enum TestProfileRunOperationsClientKnownPFResult { + failed = "failed", + passed = "passed", + undetermined = "undetermined" +} + +// @public +export enum TestProfileRunOperationsClientKnownPFTestResult { + FAILED = "FAILED", + NOT_APPLICABLE = "NOT_APPLICABLE", + PASSED = "PASSED" +} + +// @public +export enum TestProfileRunOperationsClientKnownRecommendationCategory { + CostOptimized = "CostOptimized", + ThroughputOptimized = "ThroughputOptimized" +} + +// @public +export enum TestProfileRunOperationsClientKnownRequestDataLevel { + ERRORS = "ERRORS", + NONE = "NONE" +} + +// @public +export enum TestProfileRunOperationsClientKnownResourceKind { + FunctionsFlexConsumption = "FunctionsFlexConsumption" +} + +// @public +export enum TestProfileRunOperationsClientKnownSecretType { + AKV_SECRET_URI = "AKV_SECRET_URI", + SECRET_VALUE = "SECRET_VALUE" +} + +// @public +export enum TestProfileRunOperationsClientKnownStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + CONFIGURED = "CONFIGURED", + CONFIGURING = "CONFIGURING", + DEPROVISIONED = "DEPROVISIONED", + DEPROVISIONING = "DEPROVISIONING", + DONE = "DONE", + EXECUTED = "EXECUTED", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED", + PROVISIONED = "PROVISIONED", + PROVISIONING = "PROVISIONING", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestProfileRunOperationsClientKnownTestKind { + JMX = "JMX", + Locust = "Locust", + URL = "URL" +} + +// @public +export enum TestProfileRunOperationsClientKnownTestProfileRunStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + DONE = "DONE", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED" +} + +// @public +export enum TestProfileRunOperationsClientKnownTimeGrain { + PT10S = "PT10S", + PT1H = "PT1H", + PT1M = "PT1M", + PT5M = "PT5M", + PT5S = "PT5S" +} + // @public export interface TestProfileRunOperationsClientLoadTestConfiguration { engineInstances?: number; @@ -1194,7 +1707,7 @@ export interface TestProfileRunOperationsClientMetricRequestPayload { } // @public -export type TestProfileRunOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; +export type TestProfileRunOperationsClientMetricUnit = string; // @public export interface TestProfileRunOperationsClientMetricValue { @@ -1253,22 +1766,22 @@ export interface TestProfileRunOperationsClientPassFailMetric { } // @public -export type TestProfileRunOperationsClientPFAction = "continue" | "stop"; +export type TestProfileRunOperationsClientPFAction = string; // @public -export type TestProfileRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; +export type TestProfileRunOperationsClientPFAgFunc = string; // @public -export type TestProfileRunOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; +export type TestProfileRunOperationsClientPFMetrics = string; // @public -export type TestProfileRunOperationsClientPFResult = "passed" | "undetermined" | "failed"; +export type TestProfileRunOperationsClientPFResult = string; // @public -export type TestProfileRunOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type TestProfileRunOperationsClientPFTestResult = string; // @public -export type TestProfileRunOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +export type TestProfileRunOperationsClientRecommendationCategory = string; // @public export interface TestProfileRunOperationsClientRegionalConfiguration { @@ -1277,10 +1790,10 @@ export interface TestProfileRunOperationsClientRegionalConfiguration { } // @public -export type TestProfileRunOperationsClientRequestDataLevel = "NONE" | "ERRORS"; +export type TestProfileRunOperationsClientRequestDataLevel = string; // @public -export type TestProfileRunOperationsClientResourceKind = "FunctionsFlexConsumption"; +export type TestProfileRunOperationsClientResourceKind = string; // @public export interface TestProfileRunOperationsClientResourceMetric { @@ -1301,10 +1814,10 @@ export interface TestProfileRunOperationsClientSecret { } // @public -export type TestProfileRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type TestProfileRunOperationsClientSecretType = string; // @public -export type TestProfileRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +export type TestProfileRunOperationsClientStatus = string; // @public export interface TestProfileRunOperationsClientTargetResourceConfigurations { @@ -1369,7 +1882,7 @@ export interface TestProfileRunOperationsClientTestInputArtifacts { } // @public -export type TestProfileRunOperationsClientTestKind = "URL" | "JMX" | "Locust"; +export type TestProfileRunOperationsClientTestKind = string; // @public export interface TestProfileRunOperationsClientTestProfile { @@ -1413,7 +1926,7 @@ export interface TestProfileRunOperationsClientTestProfileRunRecommendation { } // @public -export type TestProfileRunOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; +export type TestProfileRunOperationsClientTestProfileRunStatus = string; // @public export interface TestProfileRunOperationsClientTestRun { @@ -1546,7 +2059,7 @@ export interface TestProfileRunOperationsClientTestServerMetricConfig { } // @public -export type TestProfileRunOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TestProfileRunOperationsClientTimeGrain = string; // @public export interface TestProfileRunOperationsClientTimeSeriesElement { @@ -1561,7 +2074,7 @@ export interface TestProfileRunRecommendation { } // @public -export type TestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; +export type TestProfileRunStatus = string; // @public export interface TestRun { @@ -1668,7 +2181,7 @@ export class TestRunOperationsClient { } // @public -export type TestRunOperationsClientAggregationType = "Average" | "Count" | "None" | "Total" | "Percentile75" | "Percentile90" | "Percentile95" | "Percentile96" | "Percentile97" | "Percentile98" | "Percentile99" | "Percentile999" | "Percentile9999"; +export type TestRunOperationsClientAggregationType = string; // @public export type TestRunOperationsClientAPIVersions = "2022-11-01" | "2023-04-01-preview" | "2024-03-01-preview" | "2024-05-01-preview"; @@ -1705,7 +2218,7 @@ export interface TestRunOperationsClientCertificateMetadata { } // @public -export type TestRunOperationsClientCertificateType = "AKV_CERT_URI"; +export type TestRunOperationsClientCertificateType = string; // @public export type TestRunOperationsClientContinuablePage = TPage & { @@ -1747,10 +2260,10 @@ export interface TestRunOperationsClientErrorDetails { } // @public -export type TestRunOperationsClientFileStatus = "NOT_VALIDATED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE" | "VALIDATION_INITIATED" | "VALIDATION_NOT_REQUIRED"; +export type TestRunOperationsClientFileStatus = string; // @public -export type TestRunOperationsClientFileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS" | "ZIPPED_ARTIFACTS" | "URL_TEST_CONFIG" | "TEST_SCRIPT"; +export type TestRunOperationsClientFileType = string; // @public export interface TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration { @@ -1772,6 +2285,177 @@ export interface TestRunOperationsClientGetAppComponentsOptionalParams extends O export interface TestRunOperationsClientGetServerMetricsConfigOptionalParams extends OperationOptions { } +// @public +export enum TestRunOperationsClientKnownAggregationType { + Average = "Average", + Count = "Count", + None = "None", + Percentile75 = "Percentile75", + Percentile90 = "Percentile90", + Percentile95 = "Percentile95", + Percentile96 = "Percentile96", + Percentile97 = "Percentile97", + Percentile98 = "Percentile98", + Percentile99 = "Percentile99", + Percentile999 = "Percentile999", + Percentile9999 = "Percentile9999", + Total = "Total" +} + +// @public +export enum TestRunOperationsClientKnownCertificateType { + AKV_CERT_URI = "AKV_CERT_URI" +} + +// @public +export enum TestRunOperationsClientKnownFileStatus { + NOT_VALIDATED = "NOT_VALIDATED", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_INITIATED = "VALIDATION_INITIATED", + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestRunOperationsClientKnownFileType { + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + JMX_FILE = "JMX_FILE", + TEST_SCRIPT = "TEST_SCRIPT", + URL_TEST_CONFIG = "URL_TEST_CONFIG", + USER_PROPERTIES = "USER_PROPERTIES", + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS" +} + +// @public +export enum TestRunOperationsClientKnownMetricUnit { + Bytes = "Bytes", + BytesPerSecond = "BytesPerSecond", + Count = "Count", + CountPerSecond = "CountPerSecond", + Milliseconds = "Milliseconds", + NotSpecified = "NotSpecified", + Percent = "Percent", + Seconds = "Seconds" +} + +// @public +export enum TestRunOperationsClientKnownPFAction { + "continue" = "continue", + stop = "stop" +} + +// @public +export enum TestRunOperationsClientKnownPFAgFunc { + "p99.9" = "p99.9", + "p99.99" = "p99.99", + avg = "avg", + count = "count", + max = "max", + min = "min", + p50 = "p50", + p75 = "p75", + p90 = "p90", + p95 = "p95", + p96 = "p96", + p97 = "p97", + p98 = "p98", + p99 = "p99", + percentage = "percentage" +} + +// @public +export enum TestRunOperationsClientKnownPFMetrics { + error = "error", + latency = "latency", + requests = "requests", + requests_per_sec = "requests_per_sec", + response_time_ms = "response_time_ms" +} + +// @public +export enum TestRunOperationsClientKnownPFResult { + failed = "failed", + passed = "passed", + undetermined = "undetermined" +} + +// @public +export enum TestRunOperationsClientKnownPFTestResult { + FAILED = "FAILED", + NOT_APPLICABLE = "NOT_APPLICABLE", + PASSED = "PASSED" +} + +// @public +export enum TestRunOperationsClientKnownRecommendationCategory { + CostOptimized = "CostOptimized", + ThroughputOptimized = "ThroughputOptimized" +} + +// @public +export enum TestRunOperationsClientKnownRequestDataLevel { + ERRORS = "ERRORS", + NONE = "NONE" +} + +// @public +export enum TestRunOperationsClientKnownResourceKind { + FunctionsFlexConsumption = "FunctionsFlexConsumption" +} + +// @public +export enum TestRunOperationsClientKnownSecretType { + AKV_SECRET_URI = "AKV_SECRET_URI", + SECRET_VALUE = "SECRET_VALUE" +} + +// @public +export enum TestRunOperationsClientKnownStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + CONFIGURED = "CONFIGURED", + CONFIGURING = "CONFIGURING", + DEPROVISIONED = "DEPROVISIONED", + DEPROVISIONING = "DEPROVISIONING", + DONE = "DONE", + EXECUTED = "EXECUTED", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED", + PROVISIONED = "PROVISIONED", + PROVISIONING = "PROVISIONING", + VALIDATION_FAILURE = "VALIDATION_FAILURE", + VALIDATION_SUCCESS = "VALIDATION_SUCCESS" +} + +// @public +export enum TestRunOperationsClientKnownTestKind { + JMX = "JMX", + Locust = "Locust", + URL = "URL" +} + +// @public +export enum TestRunOperationsClientKnownTestProfileRunStatus { + ACCEPTED = "ACCEPTED", + CANCELLED = "CANCELLED", + CANCELLING = "CANCELLING", + DONE = "DONE", + EXECUTING = "EXECUTING", + FAILED = "FAILED", + NOTSTARTED = "NOTSTARTED" +} + +// @public +export enum TestRunOperationsClientKnownTimeGrain { + PT10S = "PT10S", + PT1H = "PT1H", + PT1M = "PT1M", + PT5M = "PT5M", + PT5S = "PT5S" +} + // @public export interface TestRunOperationsClientLoadTestConfiguration { engineInstances?: number; @@ -1820,7 +2504,7 @@ export interface TestRunOperationsClientMetricRequestPayload { } // @public -export type TestRunOperationsClientMetricUnit = "NotSpecified" | "Percent" | "Count" | "Seconds" | "Milliseconds" | "Bytes" | "BytesPerSecond" | "CountPerSecond"; +export type TestRunOperationsClientMetricUnit = string; // @public export interface TestRunOperationsClientMetricValue { @@ -1879,22 +2563,22 @@ export interface TestRunOperationsClientPassFailMetric { } // @public -export type TestRunOperationsClientPFAction = "continue" | "stop"; +export type TestRunOperationsClientPFAction = string; // @public -export type TestRunOperationsClientPFAgFunc = "count" | "percentage" | "avg" | "p50" | "p75" | "p90" | "p95" | "p96" | "p97" | "p98" | "p99" | "p99.9" | "p99.99" | "min" | "max"; +export type TestRunOperationsClientPFAgFunc = string; // @public -export type TestRunOperationsClientPFMetrics = "response_time_ms" | "latency" | "error" | "requests" | "requests_per_sec"; +export type TestRunOperationsClientPFMetrics = string; // @public -export type TestRunOperationsClientPFResult = "passed" | "undetermined" | "failed"; +export type TestRunOperationsClientPFResult = string; // @public -export type TestRunOperationsClientPFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type TestRunOperationsClientPFTestResult = string; // @public -export type TestRunOperationsClientRecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +export type TestRunOperationsClientRecommendationCategory = string; // @public export interface TestRunOperationsClientRegionalConfiguration { @@ -1903,10 +2587,10 @@ export interface TestRunOperationsClientRegionalConfiguration { } // @public -export type TestRunOperationsClientRequestDataLevel = "NONE" | "ERRORS"; +export type TestRunOperationsClientRequestDataLevel = string; // @public -export type TestRunOperationsClientResourceKind = "FunctionsFlexConsumption"; +export type TestRunOperationsClientResourceKind = string; // @public export interface TestRunOperationsClientResourceMetric { @@ -1927,10 +2611,10 @@ export interface TestRunOperationsClientSecret { } // @public -export type TestRunOperationsClientSecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type TestRunOperationsClientSecretType = string; // @public -export type TestRunOperationsClientStatus = "ACCEPTED" | "NOTSTARTED" | "PROVISIONING" | "PROVISIONED" | "CONFIGURING" | "CONFIGURED" | "EXECUTING" | "EXECUTED" | "DEPROVISIONING" | "DEPROVISIONED" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED" | "VALIDATION_SUCCESS" | "VALIDATION_FAILURE"; +export type TestRunOperationsClientStatus = string; // @public export interface TestRunOperationsClientTargetResourceConfigurations { @@ -1995,7 +2679,7 @@ export interface TestRunOperationsClientTestInputArtifacts { } // @public -export type TestRunOperationsClientTestKind = "URL" | "JMX" | "Locust"; +export type TestRunOperationsClientTestKind = string; // @public export interface TestRunOperationsClientTestProfile { @@ -2039,7 +2723,7 @@ export interface TestRunOperationsClientTestProfileRunRecommendation { } // @public -export type TestRunOperationsClientTestProfileRunStatus = "ACCEPTED" | "NOTSTARTED" | "EXECUTING" | "DONE" | "CANCELLING" | "CANCELLED" | "FAILED"; +export type TestRunOperationsClientTestProfileRunStatus = string; // @public export interface TestRunOperationsClientTestRun { @@ -2172,7 +2856,7 @@ export interface TestRunOperationsClientTestServerMetricConfig { } // @public -export type TestRunOperationsClientTimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TestRunOperationsClientTimeGrain = string; // @public export interface TestRunOperationsClientTimeSeriesElement { @@ -2233,7 +2917,7 @@ export interface TestServerMetricConfig { } // @public -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TimeGrain = string; // @public export interface TimeSeriesElement { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index b006f380b8..a45606d756 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -10,11 +10,9 @@ import { appComponentSerializer, resourceMetricSerializer, Test, - CertificateType, TestFileInfo, FileType, FileStatus, - TestKind, TestAppComponents, TestServerMetricConfig, _PagedTest, @@ -134,11 +132,7 @@ export async function _createOrUpdateTestDeserialize( return { passFailCriteria: !result.body.passFailCriteria ? undefined - : { - passFailMetrics: result.body.passFailCriteria?.[ - "passFailMetrics" - ] as any, - }, + : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -147,15 +141,15 @@ export async function _createOrUpdateTestDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"] as any, + secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"] as CertificateType, + type: result.body.certificate?.["type"], name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"] as any, + environmentVariables: result.body["environmentVariables"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -215,9 +209,8 @@ export async function _createOrUpdateTestDeserialize( fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], url: result.body.inputArtifacts?.configFileInfo?.["url"], - fileType: result.body.inputArtifacts?.configFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" @@ -228,9 +221,10 @@ export async function _createOrUpdateTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -242,9 +236,8 @@ export async function _createOrUpdateTestDeserialize( fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: result.body.inputArtifacts?.testScriptFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" @@ -255,8 +248,10 @@ export async function _createOrUpdateTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -268,9 +263,8 @@ export async function _createOrUpdateTestDeserialize( fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], url: result.body.inputArtifacts?.userPropFileInfo?.["url"], - fileType: result.body.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" @@ -281,8 +275,10 @@ export async function _createOrUpdateTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.userPropFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -299,8 +295,10 @@ export async function _createOrUpdateTestDeserialize( url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "url" ], - fileType: result.body.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, + fileType: + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "fileType" + ], expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" @@ -311,10 +309,10 @@ export async function _createOrUpdateTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" @@ -329,9 +327,10 @@ export async function _createOrUpdateTestDeserialize( "fileName" ], url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], expireDateTime: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "expireDateTime" @@ -342,8 +341,10 @@ export async function _createOrUpdateTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" @@ -356,12 +357,12 @@ export async function _createOrUpdateTestDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; }), @@ -370,7 +371,7 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"] as TestKind, + kind: result.body["kind"], publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], @@ -434,7 +435,7 @@ export async function _createOrUpdateAppComponentsDeserialize( } return { - components: result.body["components"] as any, + components: result.body["components"], testId: result.body["testId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -504,7 +505,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], - metrics: result.body["metrics"] as any, + metrics: result.body["metrics"], createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -559,7 +560,7 @@ export async function _getAppComponentsDeserialize( } return { - components: result.body["components"] as any, + components: result.body["components"], testId: result.body["testId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -608,7 +609,7 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], - metrics: result.body["metrics"] as any, + metrics: result.body["metrics"], createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -657,11 +658,7 @@ export async function _getTestDeserialize( return { passFailCriteria: !result.body.passFailCriteria ? undefined - : { - passFailMetrics: result.body.passFailCriteria?.[ - "passFailMetrics" - ] as any, - }, + : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -670,15 +667,15 @@ export async function _getTestDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"] as any, + secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"] as CertificateType, + type: result.body.certificate?.["type"], name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"] as any, + environmentVariables: result.body["environmentVariables"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -738,9 +735,8 @@ export async function _getTestDeserialize( fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], url: result.body.inputArtifacts?.configFileInfo?.["url"], - fileType: result.body.inputArtifacts?.configFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" @@ -751,9 +747,10 @@ export async function _getTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -765,9 +762,8 @@ export async function _getTestDeserialize( fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: result.body.inputArtifacts?.testScriptFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" @@ -778,8 +774,10 @@ export async function _getTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.testScriptFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -791,9 +789,8 @@ export async function _getTestDeserialize( fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], url: result.body.inputArtifacts?.userPropFileInfo?.["url"], - fileType: result.body.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" @@ -804,8 +801,10 @@ export async function _getTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.userPropFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -822,8 +821,10 @@ export async function _getTestDeserialize( url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "url" ], - fileType: result.body.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, + fileType: + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "fileType" + ], expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" @@ -834,10 +835,10 @@ export async function _getTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" @@ -852,9 +853,10 @@ export async function _getTestDeserialize( "fileName" ], url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ] as FileType, + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], expireDateTime: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "expireDateTime" @@ -865,8 +867,10 @@ export async function _getTestDeserialize( ], ) : undefined, - validationStatus: result.body.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], validationFailureDetails: result.body.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" @@ -879,12 +883,12 @@ export async function _getTestDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; }), @@ -893,7 +897,7 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"] as TestKind, + kind: result.body["kind"], publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], @@ -951,12 +955,12 @@ export async function _getTestFileDeserialize( return { url: result.body["url"], - fileType: result.body["fileType"] as FileType, + fileType: result.body["fileType"], expireDateTime: result.body["expireDateTime"] !== undefined ? new Date(result.body["expireDateTime"]) : undefined, - validationStatus: result.body["validationStatus"] as FileStatus, + validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } @@ -1005,12 +1009,12 @@ export async function _listTestFilesDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; }), @@ -1067,7 +1071,7 @@ export async function _listTestsDeserialize( return { passFailCriteria: !p.passFailCriteria ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] as any }, + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !p.autoStopCriteria ? undefined : { @@ -1076,15 +1080,15 @@ export async function _listTestsDeserialize( errorRateTimeWindowInSeconds: p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: p["secrets"] as any, + secrets: p["secrets"], certificate: !p.certificate ? undefined : { value: p.certificate?.["value"], - type: p.certificate?.["type"] as CertificateType, + type: p.certificate?.["type"], name: p.certificate?.["name"], }, - environmentVariables: p["environmentVariables"] as any, + environmentVariables: p["environmentVariables"], loadTestConfiguration: !p.loadTestConfiguration ? undefined : { @@ -1142,9 +1146,7 @@ export async function _listTestsDeserialize( : { fileName: p.inputArtifacts?.configFileInfo?.["fileName"], url: p.inputArtifacts?.configFileInfo?.["url"], - fileType: p.inputArtifacts?.configFileInfo?.[ - "fileType" - ] as FileType, + fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== undefined @@ -1154,9 +1156,8 @@ export async function _listTestsDeserialize( ], ) : undefined, - validationStatus: p.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: p.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -1168,9 +1169,8 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], url: p.inputArtifacts?.testScriptFileInfo?.["url"], - fileType: p.inputArtifacts?.testScriptFileInfo?.[ - "fileType" - ] as FileType, + fileType: + p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" @@ -1181,9 +1181,10 @@ export async function _listTestsDeserialize( ], ) : undefined, - validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.inputArtifacts?.testScriptFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.inputArtifacts?.testScriptFileInfo?.[ "validationFailureDetails" @@ -1194,9 +1195,7 @@ export async function _listTestsDeserialize( : { fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], url: p.inputArtifacts?.userPropFileInfo?.["url"], - fileType: p.inputArtifacts?.userPropFileInfo?.[ - "fileType" - ] as FileType, + fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== undefined @@ -1206,9 +1205,8 @@ export async function _listTestsDeserialize( ], ) : undefined, - validationStatus: p.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: p.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -1221,9 +1219,8 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], - fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "fileType" - ] as FileType, + fileType: + p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" @@ -1234,10 +1231,10 @@ export async function _listTestsDeserialize( ], ) : undefined, - validationStatus: p.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationFailureDetails" @@ -1249,9 +1246,8 @@ export async function _listTestsDeserialize( fileName: p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: p.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ] as FileType, + fileType: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.urlTestConfigFileInfo?.[ "expireDateTime" @@ -1262,9 +1258,10 @@ export async function _listTestsDeserialize( ], ) : undefined, - validationStatus: p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.inputArtifacts?.urlTestConfigFileInfo?.[ "validationFailureDetails" @@ -1277,12 +1274,12 @@ export async function _listTestsDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; }), @@ -1291,7 +1288,7 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], - kind: p["kind"] as TestKind, + kind: p["kind"], publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], @@ -1364,12 +1361,12 @@ export async function _uploadTestFileDeserialize( return { url: result.body["url"], - fileType: result.body["fileType"] as FileType, + fileType: result.body["fileType"], expireDateTime: result.body["expireDateTime"] !== undefined ? new Date(result.body["expireDateTime"]) : undefined, - validationStatus: result.body["validationStatus"] as FileStatus, + validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index 6cab3ad382..e861e89c88 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -9,22 +9,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -39,17 +48,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -63,11 +78,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index e8845351c8..5968849e35 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -5,22 +5,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -35,17 +44,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -59,11 +74,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, } from "./models.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index 31dd6af57e..8d3521d6b3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -169,34 +169,128 @@ export function passFailMetricSerializer( }; } -/** Metrics for pass/fail criteria. */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Aggregation functions for pass/fail criteria. */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p75" - | "p90" - | "p95" - | "p96" - | "p97" - | "p98" - | "p99" - | "p99.9" - | "p99.99" - | "min" - | "max"; -/** Action to take on failure of pass/fail criteria. */ -export type PFAction = "continue" | "stop"; -/** Pass/fail criteria result. */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ export interface AutoStopCriteria { @@ -233,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Types of secrets supported. */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -256,8 +365,20 @@ export function certificateMetadataSerializer( }; } -/** Types of certificates supported. */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; /** Configurations for the load test. */ export interface LoadTestConfiguration { @@ -380,23 +501,83 @@ export interface TestFileInfo { readonly validationFailureDetails?: string; } -/** Types of file supported. */ -export type FileType = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG" - | "TEST_SCRIPT"; -/** File status. */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Test kind */ -export type TestKind = "URL" | "JMX" | "Locust"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} + +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; /** Test app components */ export interface TestAppComponents { @@ -750,28 +931,104 @@ export interface ArtifactsContainerInfo { expireDateTime?: Date; } -/** Test result based on pass/fail criteria. */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Test run status. */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Request data collection level for test run */ -export type RequestDataLevel = "NONE" | "ERRORS"; +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -834,8 +1091,32 @@ export function testRunServerMetricConfigSerializer( }; } -/** Time Grain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; /** Metrics dimension values. */ export interface DimensionValueList { @@ -884,31 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile75" - | "Percentile90" - | "Percentile95" - | "Percentile96" - | "Percentile97" - | "Percentile98" - | "Percentile99" - | "Percentile999" - | "Percentile9999"; -/** Metric unit. */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1113,8 +1455,20 @@ export function functionFlexConsumptionResourceConfigurationSerializer( }; } -/** Kind of the resource on which test profile is created. */ -export type ResourceKind = "FunctionsFlexConsumption"; +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; /** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ export interface TestProfileRun { @@ -1167,15 +1521,38 @@ export function testProfileRunSerializer( }; } -/** Test profile run status. */ -export type TestProfileRunStatus = - | "ACCEPTED" - | "NOTSTARTED" - | "EXECUTING" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED"; +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; /** Details of a particular test run for a test profile run. */ export interface TestRunDetail { @@ -1195,8 +1572,23 @@ export interface TestProfileRunRecommendation { configurations?: string[]; } -/** Category of Recommendation. */ -export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; /** Paged collection of TestFileInfo items */ export interface _PagedTestFileInfo { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 6458b009a9..9d4ae58a49 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -9,22 +9,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -39,17 +48,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -63,11 +78,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, @@ -94,22 +112,31 @@ export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, PassFailMetric as TestRunOperationsClientPassFailMetric, + KnownPFMetrics as TestRunOperationsClientKnownPFMetrics, PFMetrics as TestRunOperationsClientPFMetrics, + KnownPFAgFunc as TestRunOperationsClientKnownPFAgFunc, PFAgFunc as TestRunOperationsClientPFAgFunc, + KnownPFAction as TestRunOperationsClientKnownPFAction, PFAction as TestRunOperationsClientPFAction, + KnownPFResult as TestRunOperationsClientKnownPFResult, PFResult as TestRunOperationsClientPFResult, AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, + KnownSecretType as TestRunOperationsClientKnownSecretType, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, + KnownCertificateType as TestRunOperationsClientKnownCertificateType, CertificateType as TestRunOperationsClientCertificateType, LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, RegionalConfiguration as TestRunOperationsClientRegionalConfiguration, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, TestFileInfo as TestRunOperationsClientTestFileInfo, + KnownFileType as TestRunOperationsClientKnownFileType, FileType as TestRunOperationsClientFileType, + KnownFileStatus as TestRunOperationsClientKnownFileStatus, FileStatus as TestRunOperationsClientFileStatus, + KnownTestKind as TestRunOperationsClientKnownTestKind, TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, @@ -124,17 +151,23 @@ export { TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestRunOperationsClientKnownPFTestResult, PFTestResult as TestRunOperationsClientPFTestResult, + KnownStatus as TestRunOperationsClientKnownStatus, Status as TestRunOperationsClientStatus, + KnownRequestDataLevel as TestRunOperationsClientKnownRequestDataLevel, RequestDataLevel as TestRunOperationsClientRequestDataLevel, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, + KnownTimeGrain as TestRunOperationsClientKnownTimeGrain, TimeGrain as TestRunOperationsClientTimeGrain, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, NameAndDesc as TestRunOperationsClientNameAndDesc, + KnownAggregationType as TestRunOperationsClientKnownAggregationType, AggregationType as TestRunOperationsClientAggregationType, + KnownMetricUnit as TestRunOperationsClientKnownMetricUnit, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, @@ -148,11 +181,14 @@ export { TargetResourceConfigurations as TestRunOperationsClientTargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations as TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration as TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestRunOperationsClientKnownResourceKind, ResourceKind as TestRunOperationsClientResourceKind, TestProfileRun as TestRunOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestRunOperationsClientKnownTestProfileRunStatus, TestProfileRunStatus as TestRunOperationsClientTestProfileRunStatus, TestRunDetail as TestRunOperationsClientTestRunDetail, TestProfileRunRecommendation as TestRunOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestRunOperationsClientKnownRecommendationCategory, RecommendationCategory as TestRunOperationsClientRecommendationCategory, TargetResourceConfigurationsUnion as TestRunOperationsClientTargetResourceConfigurationsUnion, CreateOrUpdateTestRunOptionalParams, @@ -181,22 +217,31 @@ export { Test as TestProfileAdministrationOperationsClientTest, PassFailCriteria as TestProfileAdministrationOperationsClientPassFailCriteria, PassFailMetric as TestProfileAdministrationOperationsClientPassFailMetric, + KnownPFMetrics as TestProfileAdministrationOperationsClientKnownPFMetrics, PFMetrics as TestProfileAdministrationOperationsClientPFMetrics, + KnownPFAgFunc as TestProfileAdministrationOperationsClientKnownPFAgFunc, PFAgFunc as TestProfileAdministrationOperationsClientPFAgFunc, + KnownPFAction as TestProfileAdministrationOperationsClientKnownPFAction, PFAction as TestProfileAdministrationOperationsClientPFAction, + KnownPFResult as TestProfileAdministrationOperationsClientKnownPFResult, PFResult as TestProfileAdministrationOperationsClientPFResult, AutoStopCriteria as TestProfileAdministrationOperationsClientAutoStopCriteria, Secret as TestProfileAdministrationOperationsClientSecret, + KnownSecretType as TestProfileAdministrationOperationsClientKnownSecretType, SecretType as TestProfileAdministrationOperationsClientSecretType, CertificateMetadata as TestProfileAdministrationOperationsClientCertificateMetadata, + KnownCertificateType as TestProfileAdministrationOperationsClientKnownCertificateType, CertificateType as TestProfileAdministrationOperationsClientCertificateType, LoadTestConfiguration as TestProfileAdministrationOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestProfileAdministrationOperationsClientOptionalLoadTestConfig, RegionalConfiguration as TestProfileAdministrationOperationsClientRegionalConfiguration, TestInputArtifacts as TestProfileAdministrationOperationsClientTestInputArtifacts, TestFileInfo as TestProfileAdministrationOperationsClientTestFileInfo, + KnownFileType as TestProfileAdministrationOperationsClientKnownFileType, FileType as TestProfileAdministrationOperationsClientFileType, + KnownFileStatus as TestProfileAdministrationOperationsClientKnownFileStatus, FileStatus as TestProfileAdministrationOperationsClientFileStatus, + KnownTestKind as TestProfileAdministrationOperationsClientKnownTestKind, TestKind as TestProfileAdministrationOperationsClientTestKind, TestAppComponents as TestProfileAdministrationOperationsClientTestAppComponents, AppComponent as TestProfileAdministrationOperationsClientAppComponent, @@ -211,17 +256,23 @@ export { TestRunFileInfo as TestProfileAdministrationOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestProfileAdministrationOperationsClientTestRunOutputArtifacts, ArtifactsContainerInfo as TestProfileAdministrationOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestProfileAdministrationOperationsClientKnownPFTestResult, PFTestResult as TestProfileAdministrationOperationsClientPFTestResult, + KnownStatus as TestProfileAdministrationOperationsClientKnownStatus, Status as TestProfileAdministrationOperationsClientStatus, + KnownRequestDataLevel as TestProfileAdministrationOperationsClientKnownRequestDataLevel, RequestDataLevel as TestProfileAdministrationOperationsClientRequestDataLevel, TestRunAppComponents as TestProfileAdministrationOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestProfileAdministrationOperationsClientTestRunServerMetricConfig, + KnownTimeGrain as TestProfileAdministrationOperationsClientKnownTimeGrain, TimeGrain as TestProfileAdministrationOperationsClientTimeGrain, DimensionValueList as TestProfileAdministrationOperationsClientDimensionValueList, MetricDefinitionCollection as TestProfileAdministrationOperationsClientMetricDefinitionCollection, MetricDefinition as TestProfileAdministrationOperationsClientMetricDefinition, NameAndDesc as TestProfileAdministrationOperationsClientNameAndDesc, + KnownAggregationType as TestProfileAdministrationOperationsClientKnownAggregationType, AggregationType as TestProfileAdministrationOperationsClientAggregationType, + KnownMetricUnit as TestProfileAdministrationOperationsClientKnownMetricUnit, MetricUnit as TestProfileAdministrationOperationsClientMetricUnit, MetricAvailability as TestProfileAdministrationOperationsClientMetricAvailability, MetricNamespaceCollection as TestProfileAdministrationOperationsClientMetricNamespaceCollection, @@ -235,11 +286,14 @@ export { TargetResourceConfigurations as TestProfileAdministrationOperationsClientTargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations as TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration as TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestProfileAdministrationOperationsClientKnownResourceKind, ResourceKind as TestProfileAdministrationOperationsClientResourceKind, TestProfileRun as TestProfileAdministrationOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestProfileAdministrationOperationsClientKnownTestProfileRunStatus, TestProfileRunStatus as TestProfileAdministrationOperationsClientTestProfileRunStatus, TestRunDetail as TestProfileAdministrationOperationsClientTestRunDetail, TestProfileRunRecommendation as TestProfileAdministrationOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestProfileAdministrationOperationsClientKnownRecommendationCategory, RecommendationCategory as TestProfileAdministrationOperationsClientRecommendationCategory, TargetResourceConfigurationsUnion as TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion, CreateOrUpdateTestProfileOptionalParams, @@ -258,22 +312,31 @@ export { Test as TestProfileRunOperationsClientTest, PassFailCriteria as TestProfileRunOperationsClientPassFailCriteria, PassFailMetric as TestProfileRunOperationsClientPassFailMetric, + KnownPFMetrics as TestProfileRunOperationsClientKnownPFMetrics, PFMetrics as TestProfileRunOperationsClientPFMetrics, + KnownPFAgFunc as TestProfileRunOperationsClientKnownPFAgFunc, PFAgFunc as TestProfileRunOperationsClientPFAgFunc, + KnownPFAction as TestProfileRunOperationsClientKnownPFAction, PFAction as TestProfileRunOperationsClientPFAction, + KnownPFResult as TestProfileRunOperationsClientKnownPFResult, PFResult as TestProfileRunOperationsClientPFResult, AutoStopCriteria as TestProfileRunOperationsClientAutoStopCriteria, Secret as TestProfileRunOperationsClientSecret, + KnownSecretType as TestProfileRunOperationsClientKnownSecretType, SecretType as TestProfileRunOperationsClientSecretType, CertificateMetadata as TestProfileRunOperationsClientCertificateMetadata, + KnownCertificateType as TestProfileRunOperationsClientKnownCertificateType, CertificateType as TestProfileRunOperationsClientCertificateType, LoadTestConfiguration as TestProfileRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestProfileRunOperationsClientOptionalLoadTestConfig, RegionalConfiguration as TestProfileRunOperationsClientRegionalConfiguration, TestInputArtifacts as TestProfileRunOperationsClientTestInputArtifacts, TestFileInfo as TestProfileRunOperationsClientTestFileInfo, + KnownFileType as TestProfileRunOperationsClientKnownFileType, FileType as TestProfileRunOperationsClientFileType, + KnownFileStatus as TestProfileRunOperationsClientKnownFileStatus, FileStatus as TestProfileRunOperationsClientFileStatus, + KnownTestKind as TestProfileRunOperationsClientKnownTestKind, TestKind as TestProfileRunOperationsClientTestKind, TestAppComponents as TestProfileRunOperationsClientTestAppComponents, AppComponent as TestProfileRunOperationsClientAppComponent, @@ -288,17 +351,23 @@ export { TestRunFileInfo as TestProfileRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestProfileRunOperationsClientTestRunOutputArtifacts, ArtifactsContainerInfo as TestProfileRunOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestProfileRunOperationsClientKnownPFTestResult, PFTestResult as TestProfileRunOperationsClientPFTestResult, + KnownStatus as TestProfileRunOperationsClientKnownStatus, Status as TestProfileRunOperationsClientStatus, + KnownRequestDataLevel as TestProfileRunOperationsClientKnownRequestDataLevel, RequestDataLevel as TestProfileRunOperationsClientRequestDataLevel, TestRunAppComponents as TestProfileRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestProfileRunOperationsClientTestRunServerMetricConfig, + KnownTimeGrain as TestProfileRunOperationsClientKnownTimeGrain, TimeGrain as TestProfileRunOperationsClientTimeGrain, DimensionValueList as TestProfileRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestProfileRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestProfileRunOperationsClientMetricDefinition, NameAndDesc as TestProfileRunOperationsClientNameAndDesc, + KnownAggregationType as TestProfileRunOperationsClientKnownAggregationType, AggregationType as TestProfileRunOperationsClientAggregationType, + KnownMetricUnit as TestProfileRunOperationsClientKnownMetricUnit, MetricUnit as TestProfileRunOperationsClientMetricUnit, MetricAvailability as TestProfileRunOperationsClientMetricAvailability, MetricNamespaceCollection as TestProfileRunOperationsClientMetricNamespaceCollection, @@ -312,11 +381,14 @@ export { TargetResourceConfigurations as TestProfileRunOperationsClientTargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations as TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration as TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestProfileRunOperationsClientKnownResourceKind, ResourceKind as TestProfileRunOperationsClientResourceKind, TestProfileRun as TestProfileRunOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestProfileRunOperationsClientKnownTestProfileRunStatus, TestProfileRunStatus as TestProfileRunOperationsClientTestProfileRunStatus, TestRunDetail as TestProfileRunOperationsClientTestRunDetail, TestProfileRunRecommendation as TestProfileRunOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestProfileRunOperationsClientKnownRecommendationCategory, RecommendationCategory as TestProfileRunOperationsClientRecommendationCategory, TargetResourceConfigurationsUnion as TestProfileRunOperationsClientTargetResourceConfigurationsUnion, CreateOrUpdateTestProfileRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts index 7a3cc43547..b51e41f258 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/operations.ts @@ -4,7 +4,6 @@ import { targetResourceConfigurationsUnionSerializer, TestProfile, - ResourceKind, _PagedTestProfile, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; @@ -82,11 +81,7 @@ export async function _createOrUpdateTestProfileDeserialize( targetResourceId: result.body["targetResourceId"], targetResourceConfigurations: !result.body.targetResourceConfigurations ? undefined - : { - kind: result.body.targetResourceConfigurations?.[ - "kind" - ] as ResourceKind, - }, + : { kind: result.body.targetResourceConfigurations?.["kind"] }, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -181,11 +176,7 @@ export async function _getTestProfileDeserialize( targetResourceId: result.body["targetResourceId"], targetResourceConfigurations: !result.body.targetResourceConfigurations ? undefined - : { - kind: result.body.targetResourceConfigurations?.[ - "kind" - ] as ResourceKind, - }, + : { kind: result.body.targetResourceConfigurations?.["kind"] }, createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -249,7 +240,7 @@ export async function _listTestProfilesDeserialize( targetResourceId: p["targetResourceId"], targetResourceConfigurations: !p.targetResourceConfigurations ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, + : { kind: p.targetResourceConfigurations?.["kind"] }, createdDateTime: p["createdDateTime"] !== undefined ? new Date(p["createdDateTime"]) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts index 2e0e8078ae..3068dc1e80 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts @@ -9,22 +9,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -39,17 +48,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -63,11 +78,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, CreateOrUpdateTestProfileOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts index 3428af974e..e2aecc161b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/index.ts @@ -5,22 +5,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -35,17 +44,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -59,11 +74,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, } from "./models.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts index 31dd6af57e..8d3521d6b3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts @@ -169,34 +169,128 @@ export function passFailMetricSerializer( }; } -/** Metrics for pass/fail criteria. */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Aggregation functions for pass/fail criteria. */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p75" - | "p90" - | "p95" - | "p96" - | "p97" - | "p98" - | "p99" - | "p99.9" - | "p99.99" - | "min" - | "max"; -/** Action to take on failure of pass/fail criteria. */ -export type PFAction = "continue" | "stop"; -/** Pass/fail criteria result. */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ export interface AutoStopCriteria { @@ -233,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Types of secrets supported. */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -256,8 +365,20 @@ export function certificateMetadataSerializer( }; } -/** Types of certificates supported. */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; /** Configurations for the load test. */ export interface LoadTestConfiguration { @@ -380,23 +501,83 @@ export interface TestFileInfo { readonly validationFailureDetails?: string; } -/** Types of file supported. */ -export type FileType = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG" - | "TEST_SCRIPT"; -/** File status. */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Test kind */ -export type TestKind = "URL" | "JMX" | "Locust"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} + +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; /** Test app components */ export interface TestAppComponents { @@ -750,28 +931,104 @@ export interface ArtifactsContainerInfo { expireDateTime?: Date; } -/** Test result based on pass/fail criteria. */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Test run status. */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Request data collection level for test run */ -export type RequestDataLevel = "NONE" | "ERRORS"; +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -834,8 +1091,32 @@ export function testRunServerMetricConfigSerializer( }; } -/** Time Grain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; /** Metrics dimension values. */ export interface DimensionValueList { @@ -884,31 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile75" - | "Percentile90" - | "Percentile95" - | "Percentile96" - | "Percentile97" - | "Percentile98" - | "Percentile99" - | "Percentile999" - | "Percentile9999"; -/** Metric unit. */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1113,8 +1455,20 @@ export function functionFlexConsumptionResourceConfigurationSerializer( }; } -/** Kind of the resource on which test profile is created. */ -export type ResourceKind = "FunctionsFlexConsumption"; +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; /** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ export interface TestProfileRun { @@ -1167,15 +1521,38 @@ export function testProfileRunSerializer( }; } -/** Test profile run status. */ -export type TestProfileRunStatus = - | "ACCEPTED" - | "NOTSTARTED" - | "EXECUTING" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED"; +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; /** Details of a particular test run for a test profile run. */ export interface TestRunDetail { @@ -1195,8 +1572,23 @@ export interface TestProfileRunRecommendation { configurations?: string[]; } -/** Category of Recommendation. */ -export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; /** Paged collection of TestFileInfo items */ export interface _PagedTestFileInfo { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts index 8ba9e3522c..ce858f6238 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts @@ -1,13 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - ResourceKind, - TestProfileRun, - TestProfileRunStatus, - RecommendationCategory, - _PagedTestProfileRun, -} from "../models/models.js"; +import { TestProfileRun, _PagedTestProfileRun } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { @@ -80,12 +74,8 @@ export async function _createOrUpdateTestProfileRunDeserialize( targetResourceId: result.body["targetResourceId"], targetResourceConfigurations: !result.body.targetResourceConfigurations ? undefined - : { - kind: result.body.targetResourceConfigurations?.[ - "kind" - ] as ResourceKind, - }, - status: result.body["status"] as TestProfileRunStatus, + : { kind: result.body.targetResourceConfigurations?.["kind"] }, + status: result.body["status"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] @@ -101,13 +91,13 @@ export async function _createOrUpdateTestProfileRunDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"] as any, + testRunDetails: result.body["testRunDetails"], recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] : result.body["recommendations"].map((p) => { return { - category: p["category"] as RecommendationCategory, + category: p["category"], configurations: p["configurations"], }; }), @@ -209,12 +199,8 @@ export async function _getTestProfileRunDeserialize( targetResourceId: result.body["targetResourceId"], targetResourceConfigurations: !result.body.targetResourceConfigurations ? undefined - : { - kind: result.body.targetResourceConfigurations?.[ - "kind" - ] as ResourceKind, - }, - status: result.body["status"] as TestProfileRunStatus, + : { kind: result.body.targetResourceConfigurations?.["kind"] }, + status: result.body["status"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] @@ -230,13 +216,13 @@ export async function _getTestProfileRunDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"] as any, + testRunDetails: result.body["testRunDetails"], recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] : result.body["recommendations"].map((p) => { return { - category: p["category"] as RecommendationCategory, + category: p["category"], configurations: p["configurations"], }; }), @@ -312,8 +298,8 @@ export async function _listTestProfileRunsDeserialize( targetResourceId: p["targetResourceId"], targetResourceConfigurations: !p.targetResourceConfigurations ? undefined - : { kind: p.targetResourceConfigurations?.["kind"] as ResourceKind }, - status: p["status"] as TestProfileRunStatus, + : { kind: p.targetResourceConfigurations?.["kind"] }, + status: p["status"], errorDetails: p["errorDetails"] === undefined ? p["errorDetails"] @@ -329,13 +315,13 @@ export async function _listTestProfileRunsDeserialize( ? new Date(p["endDateTime"]) : undefined, durationInSeconds: p["durationInSeconds"], - testRunDetails: p["testRunDetails"] as any, + testRunDetails: p["testRunDetails"], recommendations: p["recommendations"] === undefined ? p["recommendations"] : p["recommendations"].map((p) => { return { - category: p["category"] as RecommendationCategory, + category: p["category"], configurations: p["configurations"], }; }), @@ -398,12 +384,8 @@ export async function _stopTestProfileRunDeserialize( targetResourceId: result.body["targetResourceId"], targetResourceConfigurations: !result.body.targetResourceConfigurations ? undefined - : { - kind: result.body.targetResourceConfigurations?.[ - "kind" - ] as ResourceKind, - }, - status: result.body["status"] as TestProfileRunStatus, + : { kind: result.body.targetResourceConfigurations?.["kind"] }, + status: result.body["status"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] @@ -419,13 +401,13 @@ export async function _stopTestProfileRunDeserialize( ? new Date(result.body["endDateTime"]) : undefined, durationInSeconds: result.body["durationInSeconds"], - testRunDetails: result.body["testRunDetails"] as any, + testRunDetails: result.body["testRunDetails"], recommendations: result.body["recommendations"] === undefined ? result.body["recommendations"] : result.body["recommendations"].map((p) => { return { - category: p["category"] as RecommendationCategory, + category: p["category"], configurations: p["configurations"], }; }), diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts index 65b6e576e2..135e9d4ee9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts @@ -9,22 +9,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -39,17 +48,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -63,11 +78,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, CreateOrUpdateTestProfileRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts index 7c846c70ef..704ef57adc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts @@ -5,22 +5,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -35,17 +44,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -59,11 +74,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, } from "./models.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts index 31dd6af57e..8d3521d6b3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts @@ -169,34 +169,128 @@ export function passFailMetricSerializer( }; } -/** Metrics for pass/fail criteria. */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Aggregation functions for pass/fail criteria. */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p75" - | "p90" - | "p95" - | "p96" - | "p97" - | "p98" - | "p99" - | "p99.9" - | "p99.99" - | "min" - | "max"; -/** Action to take on failure of pass/fail criteria. */ -export type PFAction = "continue" | "stop"; -/** Pass/fail criteria result. */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ export interface AutoStopCriteria { @@ -233,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Types of secrets supported. */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -256,8 +365,20 @@ export function certificateMetadataSerializer( }; } -/** Types of certificates supported. */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; /** Configurations for the load test. */ export interface LoadTestConfiguration { @@ -380,23 +501,83 @@ export interface TestFileInfo { readonly validationFailureDetails?: string; } -/** Types of file supported. */ -export type FileType = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG" - | "TEST_SCRIPT"; -/** File status. */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Test kind */ -export type TestKind = "URL" | "JMX" | "Locust"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} + +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; /** Test app components */ export interface TestAppComponents { @@ -750,28 +931,104 @@ export interface ArtifactsContainerInfo { expireDateTime?: Date; } -/** Test result based on pass/fail criteria. */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Test run status. */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Request data collection level for test run */ -export type RequestDataLevel = "NONE" | "ERRORS"; +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -834,8 +1091,32 @@ export function testRunServerMetricConfigSerializer( }; } -/** Time Grain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; /** Metrics dimension values. */ export interface DimensionValueList { @@ -884,31 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile75" - | "Percentile90" - | "Percentile95" - | "Percentile96" - | "Percentile97" - | "Percentile98" - | "Percentile99" - | "Percentile999" - | "Percentile9999"; -/** Metric unit. */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1113,8 +1455,20 @@ export function functionFlexConsumptionResourceConfigurationSerializer( }; } -/** Kind of the resource on which test profile is created. */ -export type ResourceKind = "FunctionsFlexConsumption"; +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; /** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ export interface TestProfileRun { @@ -1167,15 +1521,38 @@ export function testProfileRunSerializer( }; } -/** Test profile run status. */ -export type TestProfileRunStatus = - | "ACCEPTED" - | "NOTSTARTED" - | "EXECUTING" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED"; +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; /** Details of a particular test run for a test profile run. */ export interface TestRunDetail { @@ -1195,8 +1572,23 @@ export interface TestProfileRunRecommendation { configurations?: string[]; } -/** Category of Recommendation. */ -export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; /** Paged collection of TestFileInfo items */ export interface _PagedTestFileInfo { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index d9a15328bc..8e8a9b72ab 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -10,21 +10,13 @@ import { appComponentSerializer, resourceMetricSerializer, dimensionFilterSerializer, - CertificateType, FileType, FileStatus, - TestKind, TestRun, - PFTestResult, - Status, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - TimeGrain, DimensionValueList, MetricDefinitionCollection, - AggregationType, - MetricUnit, MetricNamespaceCollection, MetricRequestPayload, TimeSeriesElement, @@ -150,11 +142,7 @@ export async function _createOrUpdateTestRunDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { - passFailMetrics: result.body.passFailCriteria?.[ - "passFailMetrics" - ] as any, - }, + : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -163,23 +151,23 @@ export async function _createOrUpdateTestRunDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"] as any, + secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"] as CertificateType, + type: result.body.certificate?.["type"], name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"] as any, + environmentVariables: result.body["environmentVariables"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => { return { message: p["message"] }; }), - testRunStatistics: result.body["testRunStatistics"] as any, - regionalStatistics: result.body["regionalStatistics"] as any, + testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -244,8 +232,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.configFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["expireDateTime"] !== undefined @@ -254,10 +243,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.configFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -271,8 +259,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.testScriptFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["expireDateTime"] !== undefined @@ -281,10 +270,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.testScriptFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -298,8 +286,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.userPropFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["expireDateTime"] !== undefined @@ -308,10 +297,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.userPropFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -325,8 +313,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== @@ -336,10 +325,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ @@ -355,8 +343,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.urlTestConfigFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["expireDateTime"] !== @@ -366,10 +355,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.urlTestConfigFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["validationFailureDetails"], @@ -387,12 +375,12 @@ export async function _createOrUpdateTestRunDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -410,8 +398,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.resultFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["expireDateTime"] !== undefined @@ -420,10 +409,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.resultFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.resultFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -437,8 +425,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.logsFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["expireDateTime"] !== undefined @@ -447,10 +436,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.logsFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.logsFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], @@ -480,8 +468,9 @@ export async function _createOrUpdateTestRunDeserialize( ?.reportFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["expireDateTime"] !== undefined @@ -490,22 +479,21 @@ export async function _createOrUpdateTestRunDeserialize( ?.reportFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.reportFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"] as PFTestResult, + testResult: result.body["testResult"], virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"] as Status, + status: result.body["status"], startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -521,8 +509,8 @@ export async function _createOrUpdateTestRunDeserialize( portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"] as TestKind, - requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], debugLogsEnabled: result.body["debugLogsEnabled"], publicIPDisabled: result.body["publicIPDisabled"], createdDateTime: @@ -590,7 +578,7 @@ export async function _createOrUpdateAppComponentsDeserialize( } return { - components: result.body["components"] as any, + components: result.body["components"], testRunId: result.body["testRunId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -662,7 +650,7 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], - metrics: result.body["metrics"] as any, + metrics: result.body["metrics"], createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -751,7 +739,7 @@ export async function _getAppComponentsDeserialize( } return { - components: result.body["components"] as any, + components: result.body["components"], testRunId: result.body["testRunId"], createdDateTime: result.body["createdDateTime"] !== undefined @@ -803,7 +791,7 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], - metrics: result.body["metrics"] as any, + metrics: result.body["metrics"], createdDateTime: result.body["createdDateTime"] !== undefined ? new Date(result.body["createdDateTime"]) @@ -852,11 +840,7 @@ export async function _getTestRunDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { - passFailMetrics: result.body.passFailCriteria?.[ - "passFailMetrics" - ] as any, - }, + : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -865,23 +849,23 @@ export async function _getTestRunDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"] as any, + secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"] as CertificateType, + type: result.body.certificate?.["type"], name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"] as any, + environmentVariables: result.body["environmentVariables"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => { return { message: p["message"] }; }), - testRunStatistics: result.body["testRunStatistics"] as any, - regionalStatistics: result.body["regionalStatistics"] as any, + testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -946,8 +930,9 @@ export async function _getTestRunDeserialize( ?.configFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["expireDateTime"] !== undefined @@ -956,10 +941,9 @@ export async function _getTestRunDeserialize( ?.configFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -973,8 +957,9 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["expireDateTime"] !== undefined @@ -983,10 +968,9 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -1000,8 +984,9 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["expireDateTime"] !== undefined @@ -1010,10 +995,9 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -1027,8 +1011,9 @@ export async function _getTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== @@ -1038,10 +1023,9 @@ export async function _getTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ @@ -1057,8 +1041,9 @@ export async function _getTestRunDeserialize( ?.urlTestConfigFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["expireDateTime"] !== @@ -1068,10 +1053,9 @@ export async function _getTestRunDeserialize( ?.urlTestConfigFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["validationFailureDetails"], @@ -1089,12 +1073,12 @@ export async function _getTestRunDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -1112,8 +1096,9 @@ export async function _getTestRunDeserialize( ?.resultFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["expireDateTime"] !== undefined @@ -1122,10 +1107,9 @@ export async function _getTestRunDeserialize( ?.resultFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.resultFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -1139,8 +1123,9 @@ export async function _getTestRunDeserialize( ?.logsFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["expireDateTime"] !== undefined @@ -1149,10 +1134,9 @@ export async function _getTestRunDeserialize( ?.logsFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.logsFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], @@ -1182,8 +1166,9 @@ export async function _getTestRunDeserialize( ?.reportFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["expireDateTime"] !== undefined @@ -1192,22 +1177,21 @@ export async function _getTestRunDeserialize( ?.reportFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.reportFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"] as PFTestResult, + testResult: result.body["testResult"], virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"] as Status, + status: result.body["status"], startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -1223,8 +1207,8 @@ export async function _getTestRunDeserialize( portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"] as TestKind, - requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], debugLogsEnabled: result.body["debugLogsEnabled"], publicIPDisabled: result.body["publicIPDisabled"], createdDateTime: @@ -1281,12 +1265,12 @@ export async function _getTestRunFileDeserialize( return { url: result.body["url"], - fileType: result.body["fileType"] as FileType, + fileType: result.body["fileType"], expireDateTime: result.body["expireDateTime"] !== undefined ? new Date(result.body["expireDateTime"]) : undefined, - validationStatus: result.body["validationStatus"] as FileStatus, + validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } @@ -1418,14 +1402,14 @@ export async function _listMetricDefinitionsDeserialize( description: p["description"], name: p["name"], namespace: p["namespace"], - primaryAggregationType: p["primaryAggregationType"] as AggregationType, + primaryAggregationType: p["primaryAggregationType"], supportedAggregationTypes: p["supportedAggregationTypes"], - unit: p["unit"] as MetricUnit, + unit: p["unit"], metricAvailabilities: p["metricAvailabilities"] === undefined ? p["metricAvailabilities"] : p["metricAvailabilities"].map((p) => { - return { timeGrain: p["timeGrain"] as TimeGrain }; + return { timeGrain: p["timeGrain"] }; }), }; }), @@ -1621,7 +1605,7 @@ export async function _listTestRunsDeserialize( testRunId: p["testRunId"], passFailCriteria: !p.passFailCriteria ? undefined - : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] as any }, + : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !p.autoStopCriteria ? undefined : { @@ -1630,23 +1614,23 @@ export async function _listTestRunsDeserialize( errorRateTimeWindowInSeconds: p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: p["secrets"] as any, + secrets: p["secrets"], certificate: !p.certificate ? undefined : { value: p.certificate?.["value"], - type: p.certificate?.["type"] as CertificateType, + type: p.certificate?.["type"], name: p.certificate?.["name"], }, - environmentVariables: p["environmentVariables"] as any, + environmentVariables: p["environmentVariables"], errorDetails: p["errorDetails"] === undefined ? p["errorDetails"] : p["errorDetails"].map((p) => { return { message: p["message"] }; }), - testRunStatistics: p["testRunStatistics"] as any, - regionalStatistics: p["regionalStatistics"] as any, + testRunStatistics: p["testRunStatistics"], + regionalStatistics: p["regionalStatistics"], loadTestConfiguration: !p.loadTestConfiguration ? undefined : { @@ -1711,8 +1695,10 @@ export async function _listTestRunsDeserialize( ], url: p.testArtifacts?.inputArtifacts ?.configFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "fileType" + ], expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" @@ -1722,10 +1708,10 @@ export async function _listTestRunsDeserialize( ?.configFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.inputArtifacts?.configFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationFailureDetails" @@ -1740,8 +1726,9 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo?.["fileName"], url: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["expireDateTime"] !== @@ -1751,10 +1738,9 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.[ @@ -1771,8 +1757,10 @@ export async function _listTestRunsDeserialize( ], url: p.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "fileType" + ], expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" @@ -1782,10 +1770,10 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationFailureDetails" @@ -1800,10 +1788,9 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo?.["fileName"], url: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "fileType" - ] as FileType, + fileType: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ @@ -1816,10 +1803,9 @@ export async function _listTestRunsDeserialize( ], ) : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["validationStatus"], validationFailureDetails: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ @@ -1835,8 +1821,9 @@ export async function _listTestRunsDeserialize( ?.urlTestConfigFileInfo?.["fileName"], url: p.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["url"], - fileType: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["expireDateTime"] !== @@ -1846,10 +1833,9 @@ export async function _listTestRunsDeserialize( ?.urlTestConfigFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], validationFailureDetails: p.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.[ @@ -1869,14 +1855,12 @@ export async function _listTestRunsDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p[ - "validationStatus" - ] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -1895,8 +1879,10 @@ export async function _listTestRunsDeserialize( ], url: p.testArtifacts?.outputArtifacts ?.resultFileInfo?.["url"], - fileType: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "fileType" + ], expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" @@ -1906,10 +1892,10 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationFailureDetails" @@ -1926,8 +1912,10 @@ export async function _listTestRunsDeserialize( url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "url" ], - fileType: p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "fileType" + ], expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" @@ -1937,8 +1925,10 @@ export async function _listTestRunsDeserialize( ?.logsFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["validationStatus"] as FileStatus, + validationStatus: + p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationFailureDetails" @@ -1972,8 +1962,10 @@ export async function _listTestRunsDeserialize( ], url: p.testArtifacts?.outputArtifacts ?.reportFileInfo?.["url"], - fileType: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"] as FileType, + fileType: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "fileType" + ], expireDateTime: p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ "expireDateTime" @@ -1983,10 +1975,10 @@ export async function _listTestRunsDeserialize( ?.reportFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "validationStatus" + ], validationFailureDetails: p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ "validationFailureDetails" @@ -1994,12 +1986,12 @@ export async function _listTestRunsDeserialize( }, }, }, - testResult: p["testResult"] as PFTestResult, + testResult: p["testResult"], virtualUsers: p["virtualUsers"], displayName: p["displayName"], testId: p["testId"], description: p["description"], - status: p["status"] as Status, + status: p["status"], startDateTime: p["startDateTime"] !== undefined ? new Date(p["startDateTime"]) @@ -2015,8 +2007,8 @@ export async function _listTestRunsDeserialize( portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - kind: p["kind"] as TestKind, - requestDataLevel: p["requestDataLevel"] as RequestDataLevel, + kind: p["kind"], + requestDataLevel: p["requestDataLevel"], debugLogsEnabled: p["debugLogsEnabled"], publicIPDisabled: p["publicIPDisabled"], createdDateTime: @@ -2071,11 +2063,7 @@ export async function _stopTestRunDeserialize( testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined - : { - passFailMetrics: result.body.passFailCriteria?.[ - "passFailMetrics" - ] as any, - }, + : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, autoStopCriteria: !result.body.autoStopCriteria ? undefined : { @@ -2084,23 +2072,23 @@ export async function _stopTestRunDeserialize( errorRateTimeWindowInSeconds: result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], }, - secrets: result.body["secrets"] as any, + secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined : { value: result.body.certificate?.["value"], - type: result.body.certificate?.["type"] as CertificateType, + type: result.body.certificate?.["type"], name: result.body.certificate?.["name"], }, - environmentVariables: result.body["environmentVariables"] as any, + environmentVariables: result.body["environmentVariables"], errorDetails: result.body["errorDetails"] === undefined ? result.body["errorDetails"] : result.body["errorDetails"].map((p) => { return { message: p["message"] }; }), - testRunStatistics: result.body["testRunStatistics"] as any, - regionalStatistics: result.body["regionalStatistics"] as any, + testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -2165,8 +2153,9 @@ export async function _stopTestRunDeserialize( ?.configFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["expireDateTime"] !== undefined @@ -2175,10 +2164,9 @@ export async function _stopTestRunDeserialize( ?.configFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.configFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationFailureDetails"], @@ -2192,8 +2180,9 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["expireDateTime"] !== undefined @@ -2202,10 +2191,9 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.testScriptFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationFailureDetails"], @@ -2219,8 +2207,9 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["expireDateTime"] !== undefined @@ -2229,10 +2218,9 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.userPropFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationFailureDetails"], @@ -2246,8 +2234,9 @@ export async function _stopTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== @@ -2257,10 +2246,9 @@ export async function _stopTestRunDeserialize( ?.inputArtifactsZipFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.[ @@ -2276,8 +2264,9 @@ export async function _stopTestRunDeserialize( ?.urlTestConfigFileInfo?.["fileName"], url: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["url"], - fileType: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["expireDateTime"] !== @@ -2287,10 +2276,9 @@ export async function _stopTestRunDeserialize( ?.urlTestConfigFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.inputArtifacts ?.urlTestConfigFileInfo?.["validationFailureDetails"], @@ -2308,12 +2296,12 @@ export async function _stopTestRunDeserialize( return { fileName: p["fileName"], url: p["url"], - fileType: p["fileType"] as FileType, + fileType: p["fileType"], expireDateTime: p["expireDateTime"] !== undefined ? new Date(p["expireDateTime"]) : undefined, - validationStatus: p["validationStatus"] as FileStatus, + validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -2331,8 +2319,9 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["expireDateTime"] !== undefined @@ -2341,10 +2330,9 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.resultFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationFailureDetails"], @@ -2358,8 +2346,9 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["expireDateTime"] !== undefined @@ -2368,10 +2357,9 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.logsFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], @@ -2401,8 +2389,9 @@ export async function _stopTestRunDeserialize( ?.reportFileInfo?.["fileName"], url: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["url"], - fileType: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"] as FileType, + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["expireDateTime"] !== undefined @@ -2411,22 +2400,21 @@ export async function _stopTestRunDeserialize( ?.reportFileInfo?.["expireDateTime"], ) : undefined, - validationStatus: result.body.testArtifacts - ?.outputArtifacts?.reportFileInfo?.[ - "validationStatus" - ] as FileStatus, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], validationFailureDetails: result.body.testArtifacts?.outputArtifacts ?.reportFileInfo?.["validationFailureDetails"], }, }, }, - testResult: result.body["testResult"] as PFTestResult, + testResult: result.body["testResult"], virtualUsers: result.body["virtualUsers"], displayName: result.body["displayName"], testId: result.body["testId"], description: result.body["description"], - status: result.body["status"] as Status, + status: result.body["status"], startDateTime: result.body["startDateTime"] !== undefined ? new Date(result.body["startDateTime"]) @@ -2442,8 +2430,8 @@ export async function _stopTestRunDeserialize( portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"] as TestKind, - requestDataLevel: result.body["requestDataLevel"] as RequestDataLevel, + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], debugLogsEnabled: result.body["debugLogsEnabled"], publicIPDisabled: result.body["publicIPDisabled"], createdDateTime: diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index 7c2e7c297e..bab9363114 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -9,22 +9,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -39,17 +48,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -63,11 +78,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, CreateOrUpdateTestRunOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index 06b876ffed..894168a7ff 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -5,22 +5,31 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, RegionalConfiguration, TestInputArtifacts, TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, TestKind, TestAppComponents, AppComponent, @@ -35,17 +44,23 @@ export { TestRunFileInfo, TestRunOutputArtifacts, ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, + KnownTimeGrain, TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, MetricNamespaceCollection, @@ -59,11 +74,14 @@ export { TargetResourceConfigurations, FunctionFlexConsumptionTargetResourceConfigurations, FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, ResourceKind, TestProfileRun, + KnownTestProfileRunStatus, TestProfileRunStatus, TestRunDetail, TestProfileRunRecommendation, + KnownRecommendationCategory, RecommendationCategory, TargetResourceConfigurationsUnion, } from "./models.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index 31dd6af57e..8d3521d6b3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -169,34 +169,128 @@ export function passFailMetricSerializer( }; } -/** Metrics for pass/fail criteria. */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Aggregation functions for pass/fail criteria. */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p75" - | "p90" - | "p95" - | "p96" - | "p97" - | "p98" - | "p99" - | "p99.9" - | "p99.99" - | "min" - | "max"; -/** Action to take on failure of pass/fail criteria. */ -export type PFAction = "continue" | "stop"; -/** Pass/fail criteria result. */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ export interface AutoStopCriteria { @@ -233,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Types of secrets supported. */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -256,8 +365,20 @@ export function certificateMetadataSerializer( }; } -/** Types of certificates supported. */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; /** Configurations for the load test. */ export interface LoadTestConfiguration { @@ -380,23 +501,83 @@ export interface TestFileInfo { readonly validationFailureDetails?: string; } -/** Types of file supported. */ -export type FileType = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS" - | "ZIPPED_ARTIFACTS" - | "URL_TEST_CONFIG" - | "TEST_SCRIPT"; -/** File status. */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Test kind */ -export type TestKind = "URL" | "JMX" | "Locust"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} + +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; /** Test app components */ export interface TestAppComponents { @@ -750,28 +931,104 @@ export interface ArtifactsContainerInfo { expireDateTime?: Date; } -/** Test result based on pass/fail criteria. */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Test run status. */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Request data collection level for test run */ -export type RequestDataLevel = "NONE" | "ERRORS"; +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -834,8 +1091,32 @@ export function testRunServerMetricConfigSerializer( }; } -/** Time Grain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; /** Metrics dimension values. */ export interface DimensionValueList { @@ -884,31 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Aggregation type. */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile75" - | "Percentile90" - | "Percentile95" - | "Percentile96" - | "Percentile97" - | "Percentile98" - | "Percentile99" - | "Percentile999" - | "Percentile9999"; -/** Metric unit. */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1113,8 +1455,20 @@ export function functionFlexConsumptionResourceConfigurationSerializer( }; } -/** Kind of the resource on which test profile is created. */ -export type ResourceKind = "FunctionsFlexConsumption"; +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; /** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ export interface TestProfileRun { @@ -1167,15 +1521,38 @@ export function testProfileRunSerializer( }; } -/** Test profile run status. */ -export type TestProfileRunStatus = - | "ACCEPTED" - | "NOTSTARTED" - | "EXECUTING" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED"; +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; /** Details of a particular test run for a test profile run. */ export interface TestRunDetail { @@ -1195,8 +1572,23 @@ export interface TestProfileRunRecommendation { configurations?: string[]; } -/** Category of Recommendation. */ -export type RecommendationCategory = "ThroughputOptimized" | "CostOptimized"; +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; /** Paged collection of TestFileInfo items */ export interface _PagedTestFileInfo { diff --git a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml index 180c5d487a..5fe68fa528 100644 --- a/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml +++ b/packages/typespec-test/test/loadtesting_modular/tspconfig.yaml @@ -12,6 +12,7 @@ options: enableOperationGroup: true isModularLibrary: true hierarchyClient: false + experimentalExtensibleEnums: true packageDetails: name: "@azure/load-testing" description: This package contains Microsoft Azure LoadTestingClient client library. diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index e2a2a1e13f..1c186dd9c4 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -1283,9 +1283,6 @@ export function deserializeResponseValue( } } return restValue; - case "dict": - // TODO: Need to handle the dictionary cases - return `${restValue} as any`; default: return restValue; } From a7dd7fc1bd0b32ab77865c21a13011ecd7b27a6c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 14:56:19 +0800 Subject: [PATCH 12/18] Update the test cases for widget_dpg.api --- .../generated/typespec-ts/review/widget_dpg.api.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md index e3d223a430..2a58011ec9 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md @@ -24,17 +24,9 @@ export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { updateIntervalInMs?: number; } -// @public -export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; - updateIntervalInMs?: number; -} - // @public export interface BudgetsOperations { createOrReplace: (name: string, resource: User, options?: BudgetsCreateOrReplaceOptionalParams) => PollerLike, User>; - createOrUpdate: (name: string, resource: User, options?: BudgetsCreateOrUpdateOptionalParams) => PollerLike, User>; } // @public From b633c8bc1d2146f769bc10bf2b8e66f3874bcd1f Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 14:56:36 +0800 Subject: [PATCH 13/18] Update the test cases for widget_dpg.api --- .../typespec-ts/src/api/budgets/index.ts | 65 +------------------ .../typespec-ts/src/classic/budgets/index.ts | 18 +---- .../generated/typespec-ts/src/index.ts | 1 - .../generated/typespec-ts/src/models/index.ts | 1 - .../typespec-ts/src/models/options.ts | 10 --- .../typespec-ts/src/rest/clientDefinitions.ts | 20 ------ .../typespec-ts/src/rest/isUnexpected.ts | 22 +------ .../typespec-ts/src/rest/parameters.ts | 26 -------- .../typespec-ts/src/rest/pollingHelper.ts | 16 ----- .../typespec-ts/src/rest/responses.ts | 41 ------------ .../typespec-ts/src/restorePollerHelpers.ts | 7 +- .../test/widget_dpg/spec/main.tsp | 4 -- 12 files changed, 6 insertions(+), 225 deletions(-) diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts index cb9ddda7eb..a5bdc3a025 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts @@ -9,10 +9,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, - BudgetsCreateOrUpdateLogicalResponse, isUnexpected, WidgetServiceContext as Client, } from "../../rest/index.js"; @@ -21,10 +17,7 @@ import { operationOptionsToRequestParameters, createRestError, } from "@azure-rest/core-client"; -import { - BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, -} from "../../models/options.js"; +import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; export function _createOrReplaceSend( context: Client, @@ -79,59 +72,3 @@ export function createOrReplace( _createOrReplaceSend(context, name, resource, options), }) as PollerLike, User>; } - -export function _createOrUpdateSend( - context: Client, - name: string, - resource: User, - options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, -): StreamableMethod< - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - | BudgetsCreateOrUpdateLogicalResponse -> { - return context - .path("/budgets/widgets/createOrUpdate/users/{name}", name) - .patch({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, - body: { role: resource["role"], id: resource["id"] }, - }); -} - -export async function _createOrUpdateDeserialize( - result: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - | BudgetsCreateOrUpdateLogicalResponse, -): Promise { - if (isUnexpected(result)) { - throw createRestError(result); - } - - result = result as BudgetsCreateOrUpdateLogicalResponse; - return { - name: result.body["name"], - role: result.body["role"], - id: result.body["id"], - }; -} - -/** Long-running resource create or update operation template. */ -export function createOrUpdate( - context: Client, - name: string, - resource: User, - options: BudgetsCreateOrUpdateOptionalParams = { requestOptions: {} }, -): PollerLike, User> { - return getLongRunningPoller(context, _createOrUpdateDeserialize, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _createOrUpdateSend(context, name, resource, options), - }) as PollerLike, User>; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts index d891c3b353..41bfb16804 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/budgets/index.ts @@ -3,12 +3,9 @@ import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; import { User } from "../../models/models.js"; -import { createOrReplace, createOrUpdate } from "../../api/budgets/index.js"; +import { createOrReplace } from "../../api/budgets/index.js"; import { PollerLike, OperationState } from "@azure/core-lro"; -import { - BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, -} from "../../models/options.js"; +import { BudgetsCreateOrReplaceOptionalParams } from "../../models/options.js"; /** Interface representing a Budgets operations. */ export interface BudgetsOperations { @@ -18,12 +15,6 @@ export interface BudgetsOperations { resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => PollerLike, User>; - /** Long-running resource create or update operation template. */ - createOrUpdate: ( - name: string, - resource: User, - options?: BudgetsCreateOrUpdateOptionalParams, - ) => PollerLike, User>; } export function getBudgets(context: WidgetServiceContext) { @@ -33,11 +24,6 @@ export function getBudgets(context: WidgetServiceContext) { resource: User, options?: BudgetsCreateOrReplaceOptionalParams, ) => createOrReplace(context, name, resource, options), - createOrUpdate: ( - name: string, - resource: User, - options?: BudgetsCreateOrUpdateOptionalParams, - ) => createOrUpdate(context, name, resource, options), }; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts index b749c17f1e..2564ae966b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts @@ -25,7 +25,6 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index 9ba49f01b0..62aef0d529 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -22,7 +22,6 @@ export { WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, - BudgetsCreateOrUpdateOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts index 2ba48a5b1e..89feb4f796 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts @@ -49,13 +49,3 @@ export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { /** The API version to use for this operation. */ apiVersion?: string; } - -/** Optional parameters. */ -export interface BudgetsCreateOrUpdateOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** The API version to use for this operation. */ - apiVersion?: string; - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts index 14643f2b13..246c23ed06 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -12,7 +12,6 @@ import { WidgetsCreateOrReplaceParameters, WidgetsAnalyzeWidgetParameters, BudgetsCreateOrReplaceParameters, - BudgetsCreateOrUpdateParameters, } from "./parameters.js"; import { WidgetsListWidgets200Response, @@ -37,9 +36,6 @@ import { BudgetsCreateOrReplace200Response, BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; @@ -136,17 +132,6 @@ export interface BudgetsCreateOrReplace { >; } -export interface BudgetsCreateOrUpdate { - /** Long-running resource create or update operation template. */ - patch( - options: BudgetsCreateOrUpdateParameters, - ): StreamableMethod< - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse - >; -} - export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): WidgetsListWidgets; @@ -166,11 +151,6 @@ export interface Routes { path: "/budgets/widgets/createOrReplace/users/{name}", name: string, ): BudgetsCreateOrReplace; - /** Resource for '/budgets/widgets/createOrUpdate/users/\{name\}' has methods for the following verbs: patch */ - ( - path: "/budgets/widgets/createOrUpdate/users/{name}", - name: string, - ): BudgetsCreateOrUpdate; } export type WidgetServiceContext = Client & { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts index f6205b939e..2ee6febfd6 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts @@ -26,10 +26,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceLogicalResponse, BudgetsCreateOrReplaceDefaultResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateLogicalResponse, - BudgetsCreateOrUpdateDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -45,8 +41,6 @@ const responseMap: Record = { "POST /widgets/{id}/analyze": ["200"], "GET /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], "PUT /budgets/widgets/createOrReplace/users/{name}": ["200", "201"], - "GET /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], - "PATCH /budgets/widgets/createOrUpdate/users/{name}": ["200", "201"], }; export function isUnexpected( @@ -93,13 +87,6 @@ export function isUnexpected( | BudgetsCreateOrReplaceLogicalResponse | BudgetsCreateOrReplaceDefaultResponse, ): response is BudgetsCreateOrReplaceDefaultResponse; -export function isUnexpected( - response: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, -): response is BudgetsCreateOrUpdateDefaultResponse; export function isUnexpected( response: | WidgetsListWidgets200Response @@ -125,11 +112,7 @@ export function isUnexpected( | BudgetsCreateOrReplace200Response | BudgetsCreateOrReplace201Response | BudgetsCreateOrReplaceLogicalResponse - | BudgetsCreateOrReplaceDefaultResponse - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, + | BudgetsCreateOrReplaceDefaultResponse, ): response is | WidgetsListWidgetsDefaultResponse | WidgetsCreateWidgetDefaultResponse @@ -140,8 +123,7 @@ export function isUnexpected( | WidgetsDeleteWidgetDefaultResponse | WidgetsCreateOrReplaceDefaultResponse | WidgetsAnalyzeWidgetDefaultResponse - | BudgetsCreateOrReplaceDefaultResponse - | BudgetsCreateOrUpdateDefaultResponse { + | BudgetsCreateOrReplaceDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts index 24abbd70ba..8c547f10c0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts @@ -103,29 +103,3 @@ export type BudgetsCreateOrReplaceParameters = BudgetsCreateOrReplaceQueryParam & BudgetsCreateOrReplaceBodyParam & RequestParameters; -/** The resource instance. */ -export type UserResourceMergeAndPatch = Partial; - -export interface BudgetsCreateOrUpdateBodyParam { - /** The resource instance. */ - body: UserResourceMergeAndPatch; -} - -export interface BudgetsCreateOrUpdateQueryParamProperties { - /** The API version to use for this operation. */ - "api-version": string; -} - -export interface BudgetsCreateOrUpdateQueryParam { - queryParameters: BudgetsCreateOrUpdateQueryParamProperties; -} - -export interface BudgetsCreateOrUpdateMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type BudgetsCreateOrUpdateParameters = BudgetsCreateOrUpdateQueryParam & - BudgetsCreateOrUpdateMediaTypesParam & - BudgetsCreateOrUpdateBodyParam & - RequestParameters; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts index 0884bc7b40..f0fadff811 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/pollingHelper.ts @@ -20,10 +20,6 @@ import { BudgetsCreateOrReplace201Response, BudgetsCreateOrReplaceDefaultResponse, BudgetsCreateOrReplaceLogicalResponse, - BudgetsCreateOrUpdate200Response, - BudgetsCreateOrUpdate201Response, - BudgetsCreateOrUpdateDefaultResponse, - BudgetsCreateOrUpdateLogicalResponse, } from "./responses.js"; /** @@ -104,18 +100,6 @@ export interface SimplePollerLike< * @param options - Options to set a resume state or custom polling interval. * @returns - A poller object to poll for operation state updates and eventually get the final response. */ -export async function getLongRunningPoller< - TResult extends - | BudgetsCreateOrUpdateLogicalResponse - | BudgetsCreateOrUpdateDefaultResponse, ->( - client: Client, - initialResponse: - | BudgetsCreateOrUpdate200Response - | BudgetsCreateOrUpdate201Response - | BudgetsCreateOrUpdateDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; export async function getLongRunningPoller< TResult extends | WidgetsCreateOrReplaceLogicalResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts index c573254135..4b63997112 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts @@ -179,44 +179,3 @@ export interface BudgetsCreateOrReplaceLogicalResponse extends HttpResponse { status: "200"; body: UserOutput; } - -export interface BudgetsCreateOrUpdate200Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; -} - -/** The request has succeeded. */ -export interface BudgetsCreateOrUpdate200Response extends HttpResponse { - status: "200"; - body: UserOutput; - headers: RawHttpHeaders & BudgetsCreateOrUpdate200Headers; -} - -export interface BudgetsCreateOrUpdate201Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface BudgetsCreateOrUpdate201Response extends HttpResponse { - status: "201"; - body: UserOutput; - headers: RawHttpHeaders & BudgetsCreateOrUpdate201Headers; -} - -export interface BudgetsCreateOrUpdateDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface BudgetsCreateOrUpdateDefaultResponse extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & BudgetsCreateOrUpdateDefaultHeaders; -} - -/** The final response for long-running createOrUpdate operation */ -export interface BudgetsCreateOrUpdateLogicalResponse extends HttpResponse { - status: "200"; - body: UserOutput; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts index 5716b3eb7f..915a6fca24 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts @@ -10,10 +10,7 @@ import { import { WidgetServiceClient } from "./widgetServiceClient.js"; import { getLongRunningPoller } from "./api/pollingHelpers.js"; import { _createOrReplaceDeserialize } from "./api/widgets/index.js"; -import { - _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets, - _createOrUpdateDeserialize, -} from "./api/budgets/index.js"; +import { _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets } from "./api/budgets/index.js"; import { PathUncheckedResponse, OperationOptions, @@ -83,8 +80,6 @@ const deserializeMap: Record = { _createOrReplaceDeserialize, "PUT /budgets/widgets/createOrReplace/users/{name}": _createOrReplaceDeserializeBudgets, - "PATCH /budgets/widgets/createOrUpdate/users/{name}": - _createOrUpdateDeserialize, }; function getDeserializationHelper( diff --git a/packages/typespec-test/test/widget_dpg/spec/main.tsp b/packages/typespec-test/test/widget_dpg/spec/main.tsp index a75784a198..418b6276a3 100644 --- a/packages/typespec-test/test/widget_dpg/spec/main.tsp +++ b/packages/typespec-test/test/widget_dpg/spec/main.tsp @@ -176,8 +176,4 @@ interface Budgets { // the same name as Widgets.createOrReplace @route("/widgets/createOrReplace") op createOrReplace is ResourceOperations.LongRunningResourceCreateOrReplace; - - // the patch case for lro - @route("/widgets/createOrUpdate") - op createOrUpdate is ResourceOperations.LongRunningResourceCreateOrUpdate; } From cf9b97664bc256dbd757e8bd22afad7e5eada826 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 9 Jul 2024 16:14:23 +0800 Subject: [PATCH 14/18] Update the smoke testing --- .../generated/typespec-ts/README.md | 9 +- .../generated/typespec-ts/package.json | 118 +++++++++++++++++- 2 files changed, 119 insertions(+), 8 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/README.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/README.md index 4e4b15d19d..d29dea09a9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/README.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/README.md @@ -1,7 +1,6 @@ -# AzureLoadTesting REST client library for JavaScript +# Azure LoadTestService REST client library for JavaScript -These APIs allow end users to create, view and run load tests using Azure Load -Test Service. +These APIs allow end users to create, view and run load tests using Azure Load Test Service. **Please rely heavily on our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library** @@ -22,13 +21,13 @@ Key links: ### Install the `@azure/load-testing` package -Install the AzureLoadTesting REST client REST client library for JavaScript with `npm`: +Install the Azure LoadTestService REST client REST client library for JavaScript with `npm`: ```bash npm install @azure/load-testing ``` -### Create and authenticate a `AzureLoadTestingClient` +### Create and authenticate a `LoadTestServiceClient` To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token), provide an instance of the desired credential type obtained from the diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json index 28233f5928..8eb06edb14 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/package.json @@ -16,7 +16,13 @@ "./administrationOperations/models": "./src/administrationOperations/models/index.ts", "./testRunOperations": "./src/testRunOperations/index.ts", "./testRunOperations/api": "./src/testRunOperations/api/index.ts", - "./testRunOperations/models": "./src/testRunOperations/models/index.ts" + "./testRunOperations/models": "./src/testRunOperations/models/index.ts", + "./testProfileAdministrationOperations": "./src/testProfileAdministrationOperations/index.ts", + "./testProfileAdministrationOperations/api": "./src/testProfileAdministrationOperations/api/index.ts", + "./testProfileAdministrationOperations/models": "./src/testProfileAdministrationOperations/models/index.ts", + "./testProfileRunOperations": "./src/testProfileRunOperations/index.ts", + "./testProfileRunOperations/api": "./src/testProfileRunOperations/api/index.ts", + "./testProfileRunOperations/models": "./src/testProfileRunOperations/models/index.ts" }, "dialects": [ "esm", @@ -51,8 +57,6 @@ "@azure/core-rest-pipeline": "^1.5.0", "@azure/logger": "^1.0.0", "tslib": "^2.6.2", - "@azure/core-lro": "3.0.0", - "@azure/abort-controller": "^2.1.2", "@azure/core-paging": "^1.5.0" }, "devDependencies": { @@ -220,6 +224,114 @@ "types": "./dist/commonjs/testRunOperations/models/index.d.ts", "default": "./dist/commonjs/testRunOperations/models/index.js" } + }, + "./testProfileAdministrationOperations": { + "browser": { + "types": "./dist/browser/testProfileAdministrationOperations/index.d.ts", + "default": "./dist/browser/testProfileAdministrationOperations/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileAdministrationOperations/index.d.ts", + "default": "./dist/react-native/testProfileAdministrationOperations/index.js" + }, + "import": { + "types": "./dist/esm/testProfileAdministrationOperations/index.d.ts", + "default": "./dist/esm/testProfileAdministrationOperations/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileAdministrationOperations/index.d.ts", + "default": "./dist/commonjs/testProfileAdministrationOperations/index.js" + } + }, + "./testProfileAdministrationOperations/api": { + "browser": { + "types": "./dist/browser/testProfileAdministrationOperations/api/index.d.ts", + "default": "./dist/browser/testProfileAdministrationOperations/api/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileAdministrationOperations/api/index.d.ts", + "default": "./dist/react-native/testProfileAdministrationOperations/api/index.js" + }, + "import": { + "types": "./dist/esm/testProfileAdministrationOperations/api/index.d.ts", + "default": "./dist/esm/testProfileAdministrationOperations/api/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileAdministrationOperations/api/index.d.ts", + "default": "./dist/commonjs/testProfileAdministrationOperations/api/index.js" + } + }, + "./testProfileAdministrationOperations/models": { + "browser": { + "types": "./dist/browser/testProfileAdministrationOperations/models/index.d.ts", + "default": "./dist/browser/testProfileAdministrationOperations/models/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileAdministrationOperations/models/index.d.ts", + "default": "./dist/react-native/testProfileAdministrationOperations/models/index.js" + }, + "import": { + "types": "./dist/esm/testProfileAdministrationOperations/models/index.d.ts", + "default": "./dist/esm/testProfileAdministrationOperations/models/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileAdministrationOperations/models/index.d.ts", + "default": "./dist/commonjs/testProfileAdministrationOperations/models/index.js" + } + }, + "./testProfileRunOperations": { + "browser": { + "types": "./dist/browser/testProfileRunOperations/index.d.ts", + "default": "./dist/browser/testProfileRunOperations/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileRunOperations/index.d.ts", + "default": "./dist/react-native/testProfileRunOperations/index.js" + }, + "import": { + "types": "./dist/esm/testProfileRunOperations/index.d.ts", + "default": "./dist/esm/testProfileRunOperations/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileRunOperations/index.d.ts", + "default": "./dist/commonjs/testProfileRunOperations/index.js" + } + }, + "./testProfileRunOperations/api": { + "browser": { + "types": "./dist/browser/testProfileRunOperations/api/index.d.ts", + "default": "./dist/browser/testProfileRunOperations/api/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileRunOperations/api/index.d.ts", + "default": "./dist/react-native/testProfileRunOperations/api/index.js" + }, + "import": { + "types": "./dist/esm/testProfileRunOperations/api/index.d.ts", + "default": "./dist/esm/testProfileRunOperations/api/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileRunOperations/api/index.d.ts", + "default": "./dist/commonjs/testProfileRunOperations/api/index.js" + } + }, + "./testProfileRunOperations/models": { + "browser": { + "types": "./dist/browser/testProfileRunOperations/models/index.d.ts", + "default": "./dist/browser/testProfileRunOperations/models/index.js" + }, + "react-native": { + "types": "./dist/react-native/testProfileRunOperations/models/index.d.ts", + "default": "./dist/react-native/testProfileRunOperations/models/index.js" + }, + "import": { + "types": "./dist/esm/testProfileRunOperations/models/index.d.ts", + "default": "./dist/esm/testProfileRunOperations/models/index.js" + }, + "require": { + "types": "./dist/commonjs/testProfileRunOperations/models/index.d.ts", + "default": "./dist/commonjs/testProfileRunOperations/models/index.js" + } } }, "main": "./dist/commonjs/index.js", From 056f182d80993a7049b00efdac8cce6be9aa19a2 Mon Sep 17 00:00:00 2001 From: "Jiao Di (MSFT)" <80496810+v-jiaodi@users.noreply.github.com> Date: Tue, 16 Jul 2024 11:02:39 +0800 Subject: [PATCH 15/18] sync loadtest tsp to latest --- .../typespec-ts/review/load-testing.api.md | 38 ++---- .../administrationOperationsClient.ts | 18 +-- .../api/operations.ts | 36 +----- .../administrationOperations/models/models.ts | 2 +- .../generated/typespec-ts/src/index.ts | 4 +- .../generated/typespec-ts/src/rest/models.ts | 52 ++++++-- .../typespec-ts/src/rest/outputModels.ts | 120 +++++++++++++++--- .../typespec-ts/src/rest/parameters.ts | 18 ++- .../typespec-ts/src/rest/responses.ts | 28 +--- .../models/models.ts | 2 +- .../src/testProfileRunOperations/api/index.ts | 2 +- .../api/operations.ts | 20 ++- .../src/testProfileRunOperations/index.ts | 2 +- .../testProfileRunOperations/models/index.ts | 2 +- .../testProfileRunOperations/models/models.ts | 2 +- .../models/options.ts | 2 +- .../testProfileRunOperationsClient.ts | 10 +- .../src/testRunOperations/api/index.ts | 2 +- .../src/testRunOperations/api/operations.ts | 36 ++---- .../src/testRunOperations/index.ts | 2 +- .../src/testRunOperations/models/index.ts | 2 +- .../src/testRunOperations/models/models.ts | 2 +- .../src/testRunOperations/models/options.ts | 2 +- .../testRunOperationsClient.ts | 21 +-- .../test/loadtesting_modular/spec/client.tsp | 12 +- .../test/loadtesting_modular/spec/main.tsp | 2 +- .../spec/models.testprofile.tsp | 4 +- .../test/loadtesting_modular/spec/models.tsp | 4 +- .../test/loadtesting_modular/spec/routes.tsp | 2 +- 29 files changed, 238 insertions(+), 211 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index 34fe75a159..547ba3a81b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -20,23 +20,11 @@ export class AdministrationOperationsClient { getAppComponents(testId: string, options?: GetAppComponentsOptionalParams): Promise; getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptionalParams): Promise; getTest(testId: string, options?: GetTestOptionalParams): Promise; - getTestFile(testId: string, fileName: string, options?: GetTestFileOptionalParams): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }>; + getTestFile(testId: string, fileName: string, options?: GetTestFileOptionalParams): Promise; listTestFiles(testId: string, options?: ListTestFilesOptionalParams): PagedAsyncIterableIterator; listTests(options?: ListTestsOptionalParams): PagedAsyncIterableIterator; readonly pipeline: Pipeline; - uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptionalParams): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }>; + uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptionalParams): Promise; } // @public @@ -607,11 +595,7 @@ export type SecretType = string; export type Status = string; // @public -export interface StopTestProfileRunOptionalParams extends OperationOptions { -} - -// @public -export interface StopTestRunOptionalParams extends OperationOptions { +export interface StopOptionalParams extends OperationOptions { } // @public @@ -1398,7 +1382,7 @@ export class TestProfileRunOperationsClient { getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; listTestProfileRuns(options?: ListTestProfileRunsOptionalParams): TestProfileRunOperationsClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; - stopTestProfileRun(testProfileRunId: string, options?: StopTestProfileRunOptionalParams): Promise; + stop(testProfileRunId: string, options?: TestProfileRunOperationsClientStopOptionalParams): Promise; } // @public @@ -1819,6 +1803,10 @@ export type TestProfileRunOperationsClientSecretType = string; // @public export type TestProfileRunOperationsClientStatus = string; +// @public +export interface TestProfileRunOperationsClientStopOptionalParams extends OperationOptions { +} + // @public export interface TestProfileRunOperationsClientTargetResourceConfigurations { kind: TestProfileRunOperationsClientResourceKind; @@ -2164,20 +2152,14 @@ export class TestRunOperationsClient { getAppComponents(testRunId: string, options?: TestRunOperationsClientGetAppComponentsOptionalParams): Promise; getServerMetricsConfig(testRunId: string, options?: TestRunOperationsClientGetServerMetricsConfigOptionalParams): Promise; getTestRun(testRunId: string, options?: GetTestRunOptionalParams): Promise; - getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise<{ - url?: string; - fileType?: TestRunOperationsClientFileType; - expireDateTime?: Date; - validationStatus?: TestRunOperationsClientFileStatus; - validationFailureDetails?: string; - }>; + getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptionalParams): Promise; listMetricDefinitions(testRunId: string, metricNamespace: string, options?: ListMetricDefinitionsOptionalParams): Promise; listMetricDimensionValues(testRunId: string, name: string, metricname: string, metricNamespace: string, timespan: string, options?: ListMetricDimensionValuesOptionalParams): Promise; listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptionalParams): Promise; listMetrics(testRunId: string, metricname: string, metricNamespace: string, timespan: string, body?: TestRunOperationsClientMetricRequestPayload, options?: ListMetricsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; listTestRuns(options?: ListTestRunsOptionalParams): TestRunOperationsClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; - stopTestRun(testRunId: string, options?: StopTestRunOptionalParams): Promise; + stop(testRunId: string, options?: StopOptionalParams): Promise; } // @public diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index 54ba15307b..ea661d0dc9 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -6,8 +6,6 @@ import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, TestFileInfo, - FileType, - FileStatus, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -131,13 +129,7 @@ export class AdministrationOperationsClient { testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return getTestFile(this._client, testId, fileName, options); } @@ -169,13 +161,7 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return uploadTestFile(this._client, testId, fileName, body, options); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index a45606d756..7dbe0f44a8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -11,8 +11,6 @@ import { resourceMetricSerializer, Test, TestFileInfo, - FileType, - FileStatus, TestAppComponents, TestServerMetricConfig, _PagedTest, @@ -942,18 +940,13 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { + fileName: result.body["fileName"], url: result.body["url"], fileType: result.body["fileType"], expireDateTime: @@ -971,13 +964,7 @@ export async function getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -1348,18 +1335,13 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { + fileName: result.body["fileName"], url: result.body["url"], fileType: result.body["fileType"], expireDateTime: @@ -1382,13 +1364,7 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _uploadTestFileSend( context, testId, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index 8d3521d6b3..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -1440,7 +1440,7 @@ export function functionFlexConsumptionTargetResourceConfigurationsSerializer( /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 9d4ae58a49..0139380968 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -204,7 +204,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings as TestRunOperationsClientPageSettings, ContinuablePage as TestRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestRunOperationsClientPagedAsyncIterableIterator, @@ -395,7 +395,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, + StopOptionalParams as TestProfileRunOperationsClientStopOptionalParams, PageSettings as TestProfileRunOperationsClientPageSettings, ContinuablePage as TestProfileRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestProfileRunOperationsClientPagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index c0a95b9edc..c44491cdab 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -29,7 +29,11 @@ export interface Test { displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ + /** + * Kind of test. + * + * Possible values: "URL", "JMX", "Locust" + */ kind?: TestKind; /** Inject load test engines without deploying public IP for outbound access */ publicIPDisabled?: boolean; @@ -47,13 +51,19 @@ export interface PassFailCriteria { /** Pass fail metric */ export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ + /** + * The client metric on which the criteria should be applied. + * + * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" + */ clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests + * + * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFunc; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -65,7 +75,11 @@ export interface PassFailMetric { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ + /** + * Action taken after the threshold is met. Default is ‘continue’. + * + * Possible values: "continue", "stop" + */ action?: PFAction; } @@ -83,7 +97,11 @@ export interface AutoStopCriteria { export interface Secret { /** The value of the secret for the respective type */ value?: string; - /** Type of secret */ + /** + * Type of secret + * + * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" + */ type?: SecretType; } @@ -91,7 +109,11 @@ export interface Secret { export interface CertificateMetadata { /** The value of the certificate for respective type */ value?: string; - /** Type of certificate */ + /** + * Type of certificate + * + * Possible values: "AKV_CERT_URI" + */ type?: CertificateType; /** Name of the certificate. */ name?: string; @@ -247,7 +269,11 @@ export interface TestRun { testId?: string; /** The test run description. */ description?: string; - /** Request data collection level for test run */ + /** + * Request data collection level for test run + * + * Possible values: "NONE", "ERRORS" + */ requestDataLevel?: RequestDataLevel; /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ debugLogsEnabled?: boolean; @@ -377,7 +403,7 @@ export interface FunctionFlexConsumptionTargetResourceConfigurations /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; @@ -395,7 +421,11 @@ export interface TestProfileRun { /** Details of a particular test run for a test profile run. */ export interface TestRunDetail { - /** Status of the test run. */ + /** + * Status of the test run. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ status: Status; /** ID of the configuration on which the test ran. */ configurationId: string; @@ -405,7 +435,11 @@ export interface TestRunDetail { /** A recommendation object that provides a list of configuration that optimizes its category. */ export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ + /** + * Category of the recommendation. + * + * Possible values: "ThroughputOptimized", "CostOptimized" + */ category: RecommendationCategory; /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ configurations?: string[]; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index bd84788e85..1d62e9319d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -35,7 +35,11 @@ export interface TestOutput { displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ + /** + * Kind of test. + * + * Possible values: "URL", "JMX", "Locust" + */ kind?: TestKindOutput; /** Inject load test engines without deploying public IP for outbound access */ publicIPDisabled?: boolean; @@ -61,13 +65,19 @@ export interface PassFailCriteriaOutput { /** Pass fail metric */ export interface PassFailMetricOutput { - /** The client metric on which the criteria should be applied. */ + /** + * The client metric on which the criteria should be applied. + * + * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" + */ clientMetric?: PFMetricsOutput; /** * The aggregation function to be applied on the client metric. Allowed functions * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests + * + * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFuncOutput; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -79,11 +89,19 @@ export interface PassFailMetricOutput { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ + /** + * Action taken after the threshold is met. Default is ‘continue’. + * + * Possible values: "continue", "stop" + */ action?: PFActionOutput; /** The actual value of the client metric for the test run. */ readonly actualValue?: number; - /** Outcome of the test run. */ + /** + * Outcome of the test run. + * + * Possible values: "passed", "undetermined", "failed" + */ readonly result?: PFResultOutput; } @@ -101,7 +119,11 @@ export interface AutoStopCriteriaOutput { export interface SecretOutput { /** The value of the secret for the respective type */ value?: string; - /** Type of secret */ + /** + * Type of secret + * + * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" + */ type?: SecretTypeOutput; } @@ -109,7 +131,11 @@ export interface SecretOutput { export interface CertificateMetadataOutput { /** The value of the certificate for respective type */ value?: string; - /** Type of certificate */ + /** + * Type of certificate + * + * Possible values: "AKV_CERT_URI" + */ type?: CertificateTypeOutput; /** Name of the certificate. */ name?: string; @@ -187,11 +213,19 @@ export interface TestFileInfoOutput { fileName: string; /** File URL. */ readonly url?: string; - /** File type */ + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ readonly fileType?: FileTypeOutput; /** Expiry time of the file (RFC 3339 literal format) */ readonly expireDateTime?: string; - /** Validation status of the file */ + /** + * Validation status of the file + * + * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" + */ readonly validationStatus?: FileStatusOutput; /** Validation failure error details */ readonly validationFailureDetails?: string; @@ -317,7 +351,11 @@ export interface TestRunOutput { loadTestConfiguration?: LoadTestConfigurationOutput; /** Collection of test run artifacts */ readonly testArtifacts?: TestRunArtifactsOutput; - /** Test result for pass/Fail criteria used during the test run. */ + /** + * Test result for pass/Fail criteria used during the test run. + * + * Possible values: "PASSED", "NOT_APPLICABLE", "FAILED" + */ readonly testResult?: PFTestResultOutput; /** Number of virtual users, for which test has been run. */ readonly virtualUsers?: number; @@ -327,7 +365,11 @@ export interface TestRunOutput { testId?: string; /** The test run description. */ description?: string; - /** The test run status. */ + /** + * The test run status. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ readonly status?: StatusOutput; /** The test run start DateTime(RFC 3339 literal format). */ readonly startDateTime?: string; @@ -341,9 +383,17 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ + /** + * Type of test. + * + * Possible values: "URL", "JMX", "Locust" + */ readonly kind?: TestKindOutput; - /** Request data collection level for test run */ + /** + * Request data collection level for test run + * + * Possible values: "NONE", "ERRORS" + */ requestDataLevel?: RequestDataLevelOutput; /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ debugLogsEnabled?: boolean; @@ -439,11 +489,19 @@ export interface TestRunFileInfoOutput { fileName: string; /** File URL. */ readonly url?: string; - /** File type */ + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ readonly fileType?: FileTypeOutput; /** Expiry time of the file (RFC 3339 literal format) */ readonly expireDateTime?: string; - /** Validation status of the file */ + /** + * Validation status of the file + * + * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" + */ readonly validationStatus?: FileStatusOutput; /** Validation failure error details */ readonly validationFailureDetails?: string; @@ -499,11 +557,19 @@ export interface MetricDefinitionOutput { name?: string; /** The namespace the metric belongs to. */ namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ + /** + * The primary aggregation type value defining how to use the values for display. + * + * Possible values: "Average", "Count", "None", "Total", "Percentile75", "Percentile90", "Percentile95", "Percentile96", "Percentile97", "Percentile98", "Percentile99", "Percentile999", "Percentile9999" + */ primaryAggregationType?: AggregationTypeOutput; /** The collection of what all aggregation types are supported. */ supportedAggregationTypes?: string[]; - /** The unit of the metric. */ + /** + * The unit of the metric. + * + * Possible values: "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" + */ unit?: MetricUnitOutput; /** * Metric availability specifies the time grain (aggregation interval or @@ -525,6 +591,8 @@ export interface MetricAvailabilityOutput { /** * The time grain specifies the aggregation interval for the metric. Expressed as * a duration 'PT1M', 'PT1H', etc. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ timeGrain?: TimeGrainOutput; } @@ -649,7 +717,7 @@ export interface FunctionFlexConsumptionTargetResourceConfigurationsOutput /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfigurationOutput { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; @@ -669,7 +737,11 @@ export interface TestProfileRunOutput { readonly targetResourceId?: string; /** Configurations of the target resource on which the test profile ran. */ readonly targetResourceConfigurations?: TargetResourceConfigurationsOutput; - /** The test profile run status. */ + /** + * The test profile run status. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "EXECUTING", "DONE", "CANCELLING", "CANCELLED", "FAILED" + */ readonly status?: TestProfileRunStatusOutput; /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ readonly errorDetails?: Array; @@ -698,7 +770,11 @@ export interface TestProfileRunOutput { /** Details of a particular test run for a test profile run. */ export interface TestRunDetailOutput { - /** Status of the test run. */ + /** + * Status of the test run. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ status: StatusOutput; /** ID of the configuration on which the test ran. */ configurationId: string; @@ -708,7 +784,11 @@ export interface TestRunDetailOutput { /** A recommendation object that provides a list of configuration that optimizes its category. */ export interface TestProfileRunRecommendationOutput { - /** Category of the recommendation. */ + /** + * Category of the recommendation. + * + * Possible values: "ThroughputOptimized", "CostOptimized" + */ category: RecommendationCategoryOutput; /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ configurations?: string[]; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 55814d74ea..72c1d3b8d0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -77,7 +77,11 @@ export interface LoadTestAdministrationUploadTestFileBodyParam { } export interface LoadTestAdministrationUploadTestFileQueryParamProperties { - /** File type */ + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ fileType?: FileType; } @@ -228,7 +232,11 @@ export interface LoadTestRunListMetricsQueryParamProperties { aggregation?: string; /** Metric name */ metricname: string; - /** The interval (i.e. timegrain) of the query. */ + /** + * The interval (i.e. timegrain) of the query. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" + */ interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ metricNamespace: string; @@ -248,7 +256,11 @@ export type LoadTestRunListMetricsParameters = export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { /** Metric name */ metricname: string; - /** The interval (i.e. timegrain) of the query. */ + /** + * The interval (i.e. timegrain) of the query. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" + */ interval?: TimeGrain; /** Metric namespace to query metric definitions for. */ metricNamespace: string; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index 8e1df1b17a..65d9fbf613 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,13 +6,13 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - FileTypeOutput, - FileStatusOutput, + TestFileInfoOutput, PagedTestFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, + TestRunFileInfoOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, MetricsOutput, @@ -111,13 +111,7 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: TestFileInfoOutput; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -136,13 +130,7 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: TestFileInfoOutput; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -367,13 +355,7 @@ export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { /** The request has succeeded. */ export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: { - url?: string; - fileType?: FileTypeOutput; - expireDateTime?: string; - validationStatus?: FileStatusOutput; - validationFailureDetails?: string; - }; + body: TestRunFileInfoOutput; } export interface LoadTestRunGetTestRunFileDefaultHeaders { diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts index 8d3521d6b3..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/models/models.ts @@ -1440,7 +1440,7 @@ export function functionFlexConsumptionTargetResourceConfigurationsSerializer( /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts index 2d642b00d5..5acd70fe5d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts @@ -6,7 +6,7 @@ export { deleteTestProfileRun, getTestProfileRun, listTestProfileRuns, - stopTestProfileRun, + stop, } from "./operations.js"; export { createTestProfileRunOperations, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts index ce858f6238..addd8d3d0e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/operations.ts @@ -29,7 +29,7 @@ import { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, + StopOptionalParams, } from "../models/options.js"; export function _createOrUpdateTestProfileRunSend( @@ -354,10 +354,10 @@ export function listTestProfileRuns( ); } -export function _stopTestProfileRunSend( +export function _stopSend( context: Client, testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): StreamableMethod< | TestProfileRunAdministrationStop200Response | TestProfileRunAdministrationStopDefaultResponse @@ -367,7 +367,7 @@ export function _stopTestProfileRunSend( .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestProfileRunDeserialize( +export async function _stopDeserialize( result: | TestProfileRunAdministrationStop200Response | TestProfileRunAdministrationStopDefaultResponse, @@ -425,15 +425,11 @@ export async function _stopTestProfileRunDeserialize( } /** Stop test profile run for the given test profile run Id. */ -export async function stopTestProfileRun( +export async function stop( context: Client, testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestProfileRunSend( - context, - testProfileRunId, - options, - ); - return _stopTestProfileRunDeserialize(result); + const result = await _stopSend(context, testProfileRunId, options); + return _stopDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts index 135e9d4ee9..72b3603320 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts @@ -92,7 +92,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, + StopOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts index 704ef57adc..fb926ce5d3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/index.ts @@ -90,7 +90,7 @@ export { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, + StopOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts index 8d3521d6b3..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/models.ts @@ -1440,7 +1440,7 @@ export function functionFlexConsumptionTargetResourceConfigurationsSerializer( /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts index f4a3642273..998363629b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/models/options.ts @@ -41,4 +41,4 @@ export interface ListTestProfileRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopTestProfileRunOptionalParams extends OperationOptions {} +export interface StopOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts index 7714d981c6..21bd8823dd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts @@ -9,7 +9,7 @@ import { DeleteTestProfileRunOptionalParams, GetTestProfileRunOptionalParams, ListTestProfileRunsOptionalParams, - StopTestProfileRunOptionalParams, + StopOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { @@ -17,7 +17,7 @@ import { deleteTestProfileRun, getTestProfileRun, listTestProfileRuns, - stopTestProfileRun, + stop, createTestProfileRunOperations, TestProfileRunOperationsClientOptions, LoadTestServiceContext, @@ -87,10 +87,10 @@ export class TestProfileRunOperationsClient { } /** Stop test profile run for the given test profile run Id. */ - stopTestProfileRun( + stop( testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - return stopTestProfileRun(this._client, testProfileRunId, options); + return stop(this._client, testProfileRunId, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index de60e781ee..8e35dc0cd3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -15,7 +15,7 @@ export { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, } from "./operations.js"; export { createTestRunOperations, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 8e8a9b72ab..ffd48f173b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -10,9 +10,8 @@ import { appComponentSerializer, resourceMetricSerializer, dimensionFilterSerializer, - FileType, - FileStatus, TestRun, + TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -80,7 +79,7 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "../models/options.js"; export function _createOrUpdateTestRunSend( @@ -1252,18 +1251,13 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { + fileName: result.body["fileName"], url: result.body["url"], fileType: result.body["fileType"], expireDateTime: @@ -1281,13 +1275,7 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; -}> { +): Promise { const result = await _getTestRunFileSend( context, testRunId, @@ -2040,10 +2028,10 @@ export function listTestRuns( ); } -export function _stopTestRunSend( +export function _stopSend( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunStop200Response | LoadTestRunStopDefaultResponse > { @@ -2052,7 +2040,7 @@ export function _stopTestRunSend( .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestRunDeserialize( +export async function _stopDeserialize( result: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, ): Promise { if (isUnexpected(result)) { @@ -2448,11 +2436,11 @@ export async function _stopTestRunDeserialize( } /** Stop test run by test run Id. */ -export async function stopTestRun( +export async function stop( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestRunSend(context, testRunId, options); - return _stopTestRunDeserialize(result); + const result = await _stopSend(context, testRunId, options); + return _stopDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index bab9363114..55924f8f49 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -101,7 +101,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index 894168a7ff..5dd83b954e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -99,7 +99,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index 8d3521d6b3..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -1440,7 +1440,7 @@ export function functionFlexConsumptionTargetResourceConfigurationsSerializer( /** Resource configuration instance for a Flex Consumption based Azure Function App. */ export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 512, 2048, 2096. */ + /** Memory size of the instance. Supported values are 2048, 4096. */ instanceMemoryMB: number; /** HTTP Concurrency for the function app. */ httpConcurrency: number; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index 170b68325d..b7d2fc2c49 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -94,4 +94,4 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopTestRunOptionalParams extends OperationOptions {} +export interface StopOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index d320d25083..a3b32aa2f3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -4,9 +4,8 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - FileType, - FileStatus, TestRun, + TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -29,7 +28,7 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { @@ -46,7 +45,7 @@ import { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, createTestRunOperations, TestRunOperationsClientOptions, LoadTestServiceContext, @@ -150,13 +149,7 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise<{ - url?: string; - fileType?: FileType; - expireDateTime?: Date; - validationStatus?: FileStatus; - validationFailureDetails?: string; - }> { + ): Promise { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -230,10 +223,10 @@ export class TestRunOperationsClient { } /** Stop test run by test run Id. */ - stopTestRun( + stop( testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - return stopTestRun(this._client, testRunId, options); + return stop(this._client, testRunId, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp index cd11aa13d1..6a86935d57 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/client.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/client.tsp @@ -1,9 +1,7 @@ import "./main.tsp"; import "@azure-tools/typespec-client-generator-core"; -import "@typespec/rest"; using TypeSpec.Versioning; -using TypeSpec.Rest; using Azure.ClientGenerator.Core; using Microsoft.LoadTestService; @@ -59,8 +57,8 @@ interface TestRunOperations { listMetrics is LoadTestRun.listMetrics; listTestRuns is LoadTestRun.listTestRuns; #suppress "@azure-tools/typespec-azure-core/no-operation-id" - @action("stop") - stopTestRun is LoadTestRun.stop; + @clientName("stopTestRun", "javascript,python,java,csharp,go") + stop is LoadTestRun.stop; } @client({ @@ -84,6 +82,6 @@ interface TestProfileRunOperations { getTestProfileRun is TestProfileRunAdministration.getTestProfileRun; listTestProfileRuns is TestProfileRunAdministration.listTestProfileRuns; #suppress "@azure-tools/typespec-azure-core/no-operation-id" - @action("stop") - stopTestProfileRun is TestProfileRunAdministration.stop; -} + @clientName("stopTestProfileRun", "javascript,python,java,csharp,go") + stop is TestProfileRunAdministration.stop; +} \ No newline at end of file diff --git a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp index 9eeccba0b3..9e5294c522 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/main.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/main.tsp @@ -52,4 +52,4 @@ model Oauth2 authorizationUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"; scopes: ["https://cnt-prod.loadtesting.azure.com/.default"]; } - ]>; + ]>; \ No newline at end of file diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp index 02e1e85232..f525087308 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.testprofile.tsp @@ -85,7 +85,7 @@ union RecommendationCategory { @added(APIVersions.v2024_05_01_preview) model FunctionFlexConsumptionResourceConfiguration { #suppress "@azure-tools/typespec-azure-core/casing-style" "Abbreviating MB to Mb changes the meaning of the value." - @doc("Memory size of the instance. Supported values are 512, 2048, 2096.") + @doc("Memory size of the instance. Supported values are 2048, 4096.") instanceMemoryMB: int64; @doc("HTTP Concurrency for the function app.") @@ -321,4 +321,4 @@ model ListTestProfileRunQueryParams { @doc("Comma separated list of Statuses of the test profile runs to filter.") @query statuses?: string; -} +} \ No newline at end of file diff --git a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp index 5f1ccb5d57..6e943ade67 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/models.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/models.tsp @@ -496,9 +496,9 @@ model TestInputArtifacts { @doc("File info") model FileInfo { + #suppress "@azure-tools/typespec-azure-core/key-visibility-required" "model is output only" @doc("Name of the file.") @key - @visibility fileName: string; @doc("File URL.") @@ -1233,4 +1233,4 @@ alias ResourceCreatedResponse = TypeSpec.Ht T; alias ResourceCreatedOrOkResponse = ResourceCreatedResponse | (TypeSpec.Http.Response<200> & - T); + T); \ No newline at end of file diff --git a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp index eccc08c3d8..9eafe04811 100644 --- a/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp +++ b/packages/typespec-test/test/loadtesting_modular/spec/routes.tsp @@ -508,4 +508,4 @@ interface TestProfileRunAdministration { TestProfileRun, ListQueryParametersTrait >; -} +} \ No newline at end of file From 302299f352fcda19445200871da008b7a0ccb3c7 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 16 Jul 2024 19:52:28 +0800 Subject: [PATCH 16/18] update to the latest main --- .../administrationOperationsClient.ts | 30 +- .../api/administrationOperationsContext.ts | 11 +- .../src/administrationOperations/api/index.ts | 4 +- .../api/operations.ts | 479 ++----- .../src/administrationOperations/index.ts | 42 +- .../administrationOperations/models/index.ts | 40 +- .../administrationOperations/models/models.ts | 1154 +++-------------- .../models/options.ts | 18 +- .../generated/typespec-ts/src/index.ts | 283 +--- .../src/rest/azureLoadTestingClient.ts | 73 ++ .../typespec-ts/src/rest/clientDefinitions.ts | 243 +--- .../generated/typespec-ts/src/rest/index.ts | 7 +- .../typespec-ts/src/rest/isUnexpected.ts | 194 +-- .../generated/typespec-ts/src/rest/models.ts | 329 ++--- .../typespec-ts/src/rest/outputModels.ts | 560 +++----- .../typespec-ts/src/rest/parameters.ts | 186 +-- .../typespec-ts/src/rest/pollingHelper.ts | 223 ++++ .../typespec-ts/src/rest/responses.ts | 294 +---- .../src/testRunOperations/api/index.ts | 8 +- .../src/testRunOperations/api/operations.ts | 1123 ++++------------ .../testRunOperations/api/pollingHelpers.ts | 139 ++ .../api/testRunOperationsContext.ts | 10 +- .../src/testRunOperations/index.ts | 47 +- .../src/testRunOperations/models/index.ts | 44 +- .../src/testRunOperations/models/models.ts | 1154 +++-------------- .../src/testRunOperations/models/options.ts | 43 +- .../testRunOperations/restorePollerHelpers.ts | 156 +++ .../testRunOperationsClient.ts | 82 +- 28 files changed, 1890 insertions(+), 5086 deletions(-) create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index ea661d0dc9..c6758208ac 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -5,7 +5,7 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, - TestFileInfo, + FileInfo, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -26,8 +26,8 @@ import { import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createAdministrationOperations, - AdministrationOperationsClientOptions, - LoadTestServiceContext, + AdministrationOperationsClientOptionalParams, + AzureLoadTestingContext, createOrUpdateTest, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, @@ -42,17 +42,17 @@ import { deleteTest, } from "./api/index.js"; -export { AdministrationOperationsClientOptions } from "./api/administrationOperationsContext.js"; +export { AdministrationOperationsClientOptionalParams } from "./api/administrationOperationsContext.js"; export class AdministrationOperationsClient { - private _client: LoadTestServiceContext; + private _client: AzureLoadTestingContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; constructor( endpointParam: string, credential: TokenCredential, - options: AdministrationOperationsClientOptions = {}, + options: AdministrationOperationsClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -66,7 +66,7 @@ export class AdministrationOperationsClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test by providing the test Id. */ + /** Create a new test or update an existing test. */ createOrUpdateTest( testId: string, body: Test, @@ -75,7 +75,7 @@ export class AdministrationOperationsClient { return createOrUpdateTest(this._client, testId, body, options); } - /** Add an app component to a test by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test */ createOrUpdateAppComponents( testId: string, body: TestAppComponents, @@ -116,7 +116,7 @@ export class AdministrationOperationsClient { return getServerMetricsConfig(this._client, testId, options); } - /** Get load test details by test Id */ + /** Get load test details by test name */ getTest( testId: string, options: GetTestOptionalParams = { requestOptions: {} }, @@ -124,12 +124,12 @@ export class AdministrationOperationsClient { return getTest(this._client, testId, options); } - /** Get all the files that are associated with a test. */ + /** Get test file by the file name. */ getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return getTestFile(this._client, testId, fileName, options); } @@ -137,7 +137,7 @@ export class AdministrationOperationsClient { listTestFiles( testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -152,7 +152,7 @@ export class AdministrationOperationsClient { } /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -161,7 +161,7 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return uploadTestFile(this._client, testId, fileName, body, options); } @@ -174,7 +174,7 @@ export class AdministrationOperationsClient { return deleteTestFile(this._client, testId, fileName, options); } - /** Delete a test by its test Id. */ + /** Delete a test by its name. */ deleteTest( testId: string, options: DeleteTestOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 8bc2c2a6ab..63ab99b143 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -3,22 +3,23 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { LoadTestServiceContext } from "../../rest/index.js"; +import { AzureLoadTestingContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ -export interface AdministrationOperationsClientOptions extends ClientOptions { +export interface AdministrationOperationsClientOptionalParams + extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; } -export { LoadTestServiceContext } from "../../rest/index.js"; +export { AzureLoadTestingContext } from "../../rest/index.js"; export function createAdministrationOperations( endpointParam: string, credential: TokenCredential, - options: AdministrationOperationsClientOptions = {}, -): LoadTestServiceContext { + options: AdministrationOperationsClientOptionalParams = {}, +): AzureLoadTestingContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts index 342aa50e7a..a19e1a4bc4 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts @@ -3,8 +3,8 @@ export { createAdministrationOperations, - AdministrationOperationsClientOptions, - LoadTestServiceContext, + AdministrationOperationsClientOptionalParams, + AzureLoadTestingContext, } from "./administrationOperationsContext.js"; export { createOrUpdateTest, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index 7dbe0f44a8..c4e7c08c20 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -3,23 +3,23 @@ import { passFailCriteriaSerializer, - autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, Test, - TestFileInfo, + FileInfo, TestAppComponents, TestServerMetricConfig, + _PagedFileInfo, _PagedTest, - _PagedTestFileInfo, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, + AzureLoadTestingContext as Client, LoadTestAdministrationCreateOrUpdateAppComponents200Response, LoadTestAdministrationCreateOrUpdateAppComponents201Response, LoadTestAdministrationCreateOrUpdateAppComponentsDefaultResponse, @@ -47,7 +47,6 @@ import { LoadTestAdministrationListTestsDefaultResponse, LoadTestAdministrationUploadTestFile201Response, LoadTestAdministrationUploadTestFileDefaultResponse, - LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -90,9 +89,6 @@ export function _createOrUpdateTestSend( passFailCriteria: !body.passFailCriteria ? body.passFailCriteria : passFailCriteriaSerializer(body.passFailCriteria), - autoStopCriteria: !body.autoStopCriteria - ? body.autoStopCriteria - : autoStopCriteriaSerializer(body.autoStopCriteria), secrets: !body.secrets ? body.secrets : (serializeRecord(body.secrets as any, secretSerializer) as any), @@ -105,12 +101,9 @@ export function _createOrUpdateTestSend( loadTestConfiguration: !body.loadTestConfiguration ? body.loadTestConfiguration : loadTestConfigurationSerializer(body.loadTestConfiguration), - baselineTestRunId: body["baselineTestRunId"], description: body["description"], displayName: body["displayName"], subnetId: body["subnetId"], - kind: body["kind"], - publicIPDisabled: body["publicIPDisabled"], keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], }, @@ -131,14 +124,6 @@ export async function _createOrUpdateTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -163,14 +148,6 @@ export async function _createOrUpdateTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -184,41 +161,22 @@ export async function _createOrUpdateTestDeserialize( "duration" ], }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), }, - baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -231,21 +189,15 @@ export async function _createOrUpdateTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -258,21 +210,15 @@ export async function _createOrUpdateTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -286,13 +232,13 @@ export async function _createOrUpdateTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -300,13 +246,7 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -316,50 +256,15 @@ export async function _createOrUpdateTestDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -369,24 +274,16 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create a new test or update an existing test by providing the test Id. */ +/** Create a new test or update an existing test. */ export async function createOrUpdateTest( context: Client, testId: string, @@ -435,20 +332,14 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Add an app component to a test by providing the resource Id, name and type. */ +/** Associate an app component (collection of azure resources) to a test */ export async function createOrUpdateAppComponents( context: Client, testId: string, @@ -483,10 +374,12 @@ export function _createOrUpdateServerMetricsConfigSend( contentType: (options.contentType as any) ?? "application/merge-patch+json", body: { - metrics: serializeRecord( - body.metrics as any, - resourceMetricSerializer, - ) as any, + metrics: !body.metrics + ? body.metrics + : (serializeRecord( + body.metrics as any, + resourceMetricSerializer, + ) as any), }, }); } @@ -504,15 +397,9 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -560,15 +447,9 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -608,15 +489,9 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -657,14 +532,6 @@ export async function _getTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -689,14 +556,6 @@ export async function _getTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -710,41 +569,22 @@ export async function _getTestDeserialize( "duration" ], }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), }, - baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -757,21 +597,15 @@ export async function _getTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -784,21 +618,15 @@ export async function _getTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -812,13 +640,13 @@ export async function _getTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -826,13 +654,7 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -842,50 +664,15 @@ export async function _getTestDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileName" - ], - url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "fileType" - ], - expireDateTime: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - result.body.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -895,24 +682,16 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get load test details by test Id */ +/** Get load test details by test name */ export async function getTest( context: Client, testId: string, @@ -940,31 +719,28 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - fileName: result.body["fileName"], url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } -/** Get all the files that are associated with a test. */ +/** Get test file by the file name. */ export async function getTestFile( context: Client, testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -986,7 +762,7 @@ export async function _listTestFilesDeserialize( result: | LoadTestAdministrationListTestFiles200Response | LoadTestAdministrationListTestFilesDefaultResponse, -): Promise<_PagedTestFileInfo> { +): Promise<_PagedFileInfo> { if (isUnexpected(result)) { throw createRestError(result); } @@ -994,13 +770,10 @@ export async function _listTestFilesDeserialize( return { value: result.body["value"].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -1014,7 +787,7 @@ export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), @@ -1037,8 +810,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), - lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), + lastModifiedStartTime: options?.lastModifiedStartTime, + lastModifiedEndTime: options?.lastModifiedEndTime, maxpagesize: options?.maxpagesize, }, }); @@ -1059,14 +832,6 @@ export async function _listTestsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1090,14 +855,6 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1111,38 +868,18 @@ export async function _listTestsDeserialize( "duration" ], }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }, - ), }, - baselineTestRunId: p["baselineTestRunId"], inputArtifacts: !p.inputArtifacts ? undefined : { configFileInfo: !p.inputArtifacts?.configFileInfo ? undefined : { - fileName: p.inputArtifacts?.configFileInfo?.["fileName"], url: p.inputArtifacts?.configFileInfo?.["url"], + fileName: p.inputArtifacts?.configFileInfo?.["fileName"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.configFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + p.inputArtifacts?.configFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -1153,21 +890,13 @@ export async function _listTestsDeserialize( testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo ? undefined : { + url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], - url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.testScriptFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -1180,18 +909,11 @@ export async function _listTestsDeserialize( userPropFileInfo: !p.inputArtifacts?.userPropFileInfo ? undefined : { - fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], url: p.inputArtifacts?.userPropFileInfo?.["url"], + fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.inputArtifacts?.userPropFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -1203,21 +925,15 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ], validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -1227,45 +943,15 @@ export async function _listTestsDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], - url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], - fileType: - p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, - validationStatus: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.inputArtifacts?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: p.inputArtifacts?.["additionalFileInfo"] === undefined ? p.inputArtifacts?.["additionalFileInfo"] : p.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -1275,19 +961,11 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], - kind: p["kind"], - publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, + createdDateTime: p["createdDateTime"], createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: p["lastModifiedDateTime"], lastModifiedBy: p["lastModifiedBy"], }; }), @@ -1335,26 +1013,23 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - fileName: result.body["fileName"], url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -1364,7 +1039,7 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _uploadTestFileSend( context, testId, @@ -1437,7 +1112,7 @@ export async function _deleteTestDeserialize( return; } -/** Delete a test by its test Id. */ +/** Delete a test by its name. */ export async function deleteTest( context: Client, testId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index e861e89c88..23a819ab77 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -3,38 +3,26 @@ export { AdministrationOperationsClient, - AdministrationOperationsClientOptions, + AdministrationOperationsClientOptionalParams, } from "./administrationOperationsClient.js"; export { Test, PassFailCriteria, PassFailMetric, - KnownPFMetrics, PFMetrics, - KnownPFAgFunc, PFAgFunc, - KnownPFAction, PFAction, - KnownPFResult, PFResult, - AutoStopCriteria, Secret, - KnownSecretType, SecretType, CertificateMetadata, - KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, - RegionalConfiguration, TestInputArtifacts, - TestFileInfo, - KnownFileType, + FileInfo, FileType, - KnownFileStatus, FileStatus, - KnownTestKind, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -45,28 +33,20 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, PFTestResult, - KnownStatus, Status, - KnownRequestDataLevel, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, - KnownAggregationType, AggregationType, - KnownMetricUnit, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -74,20 +54,6 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index 5968849e35..8385d30729 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -5,32 +5,20 @@ export { Test, PassFailCriteria, PassFailMetric, - KnownPFMetrics, PFMetrics, - KnownPFAgFunc, PFAgFunc, - KnownPFAction, PFAction, - KnownPFResult, PFResult, - AutoStopCriteria, Secret, - KnownSecretType, SecretType, CertificateMetadata, - KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, - RegionalConfiguration, TestInputArtifacts, - TestFileInfo, - KnownFileType, + FileInfo, FileType, - KnownFileStatus, FileStatus, - KnownTestKind, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -41,28 +29,20 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, PFTestResult, - KnownStatus, Status, - KnownRequestDataLevel, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, - KnownAggregationType, AggregationType, - KnownMetricUnit, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -70,20 +50,6 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, } from "./models.js"; export { CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index b95c47ad79..3a7491a214 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -6,12 +6,10 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, - AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, - RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -21,19 +19,12 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, - TestProfile as TestProfileRest, - TargetResourceConfigurations as TargetResourceConfigurationsRest, - FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, - FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, - TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model. */ +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -42,38 +33,32 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -83,9 +68,6 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -98,12 +80,9 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -134,7 +113,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -169,148 +148,28 @@ export function passFailMetricSerializer( }; } -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): AutoStopCriteriaRest { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} +/** Type of PFMetrics */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Type of PFAgFunc */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; +/** Type of PFAction */ +export type PFAction = "continue" | "stop"; +/** Type of PFResult */ +export type PFResult = "passed" | "undetermined" | "failed"; /** Secret */ export interface Secret { @@ -327,23 +186,8 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; +/** Type of SecretType */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ export interface CertificateMetadata { @@ -365,24 +209,15 @@ export function certificateMetadataSerializer( }; } -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; +/** Type of CertificateType */ +export type CertificateType = "AKV_CERT_URI"; -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -396,10 +231,8 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -412,26 +245,21 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } @@ -440,146 +268,53 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): RegionalConfigurationRest { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; + readonly additionalFileInfo?: FileInfo[]; } -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfo { /** File URL. */ - readonly url?: string; + url?: string; + /** Name of the file. */ + fileName?: string; /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; /** Validation status of the file */ - readonly validationStatus?: FileStatus; + validationStatus?: FileStatus; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} +/** Type of FileType */ +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +/** Type of FileStatus */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -589,12 +324,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -610,14 +345,20 @@ export function testAppComponentsSerializer( }; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -646,13 +387,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -661,10 +402,9 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), }; } @@ -706,21 +446,31 @@ export function resourceMetricSerializer( }; } -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; +/** Collection of files. */ +export interface _PagedFileInfo { + /** The FileInfo items on this page */ + value: FileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Collection of tests */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Type of APIVersions */ +export type APIVersions = "2022-11-01"; /** Load test run model */ export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -735,18 +485,8 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ + /** Test run statistics. */ readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -763,32 +503,24 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; + /** The test run start DateTime(ISO 8601 literal format). */ + readonly startDateTime?: string; + /** The test run end DateTime(ISO 8601 literal format). */ + readonly endDateTime?: string; /** Test run initiated time. */ - readonly executedDateTime?: Date; + readonly executedDateTime?: string; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -798,9 +530,6 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -816,8 +545,6 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -851,18 +578,6 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -882,153 +597,45 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: FileInfo[]; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; + logsFileInfo?: FileInfo; +} + +/** Type of PFTestResult */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Type of Status */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; /** Test run app component */ export interface TestRunAppComponents { @@ -1040,12 +647,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -1071,12 +678,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -1091,41 +698,11 @@ export function testRunServerMetricConfigSerializer( }; } -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; +/** Type of Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; -/** Metrics dimension values. */ export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Represents collection of metric definitions. */ @@ -1165,92 +742,25 @@ export interface NameAndDesc { name?: string; } -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; +/** Type of AggregationType */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile90" + | "Percentile95" + | "Percentile99"; +/** Type of MetricUnit */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1261,6 +771,9 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } +/** Type of TimeGrain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -1275,7 +788,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -1315,7 +828,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _Metrics { +export interface _PagedTimeSeriesElement { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -1332,8 +845,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; + /** The timestamp for the metric value in ISO 8601 format. */ + timestamp?: string; /** The metric value. */ value?: number; } @@ -1346,267 +859,7 @@ export interface DimensionValue { value?: string; } -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer(item: TestProfile): TestProfileRest { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): TargetResourceConfigurationsRest { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): FunctionFlexConsumptionTargetResourceConfigurationsRest { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): FunctionFlexConsumptionResourceConfigurationRest { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): TestProfileRunRest { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ +/** Collection of test runs */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -1614,23 +867,10 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; +/** Paged collection of DimensionValueList items */ +export interface _PagedDimensionValueList { + /** The DimensionValueList items on this page */ + value: DimensionValueList[]; /** The link to the next page of items */ nextLink?: string; } - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts index 4a2f18723c..f6d6da0948 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts @@ -6,21 +6,18 @@ import { FileType } from "./models.js"; /** Optional parameters. */ export interface CreateOrUpdateTestOptionalParams extends OperationOptions { - /** This request has a JSON Merge Patch body. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } @@ -53,17 +50,22 @@ export interface ListTestsOptionalParams extends OperationOptions { * the search parameter can be Login. */ search?: string; - /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedStartTime?: Date; - /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedEndTime?: Date; + /** + * Start DateTime(ISO 8601 literal format) of the last updated time range to + * filter tests. + */ + lastModifiedStartTime?: string; + /** + * End DateTime(ISO 8601 literal format) of the last updated time range to filter + * tests. + */ + lastModifiedEndTime?: string; /** Number of results in response. */ maxpagesize?: number; } /** Optional parameters. */ export interface UploadTestFileOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; /** File type */ fileType?: FileType; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 0139380968..d2d938a6f2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -3,38 +3,26 @@ export { AdministrationOperationsClient, - AdministrationOperationsClientOptions, + AdministrationOperationsClientOptionalParams, } from "./administrationOperations/administrationOperationsClient.js"; export { Test, PassFailCriteria, PassFailMetric, - KnownPFMetrics, PFMetrics, - KnownPFAgFunc, PFAgFunc, - KnownPFAction, PFAction, - KnownPFResult, PFResult, - AutoStopCriteria, Secret, - KnownSecretType, SecretType, CertificateMetadata, - KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, - RegionalConfiguration, TestInputArtifacts, - TestFileInfo, - KnownFileType, + FileInfo, FileType, - KnownFileStatus, FileStatus, - KnownTestKind, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -45,28 +33,20 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, PFTestResult, - KnownStatus, Status, - KnownRequestDataLevel, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, - KnownAggregationType, AggregationType, - KnownMetricUnit, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -74,20 +54,6 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -106,38 +72,30 @@ export { } from "./administrationOperations/models/index.js"; export { TestRunOperationsClient, - TestRunOperationsClientOptions, + TestRunOperationsClientOptionalParams, } from "./testRunOperations/testRunOperationsClient.js"; +export { + restorePoller, + RestorePollerOptions, +} from "./testRunOperations/restorePollerHelpers.js"; export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, PassFailMetric as TestRunOperationsClientPassFailMetric, - KnownPFMetrics as TestRunOperationsClientKnownPFMetrics, PFMetrics as TestRunOperationsClientPFMetrics, - KnownPFAgFunc as TestRunOperationsClientKnownPFAgFunc, PFAgFunc as TestRunOperationsClientPFAgFunc, - KnownPFAction as TestRunOperationsClientKnownPFAction, PFAction as TestRunOperationsClientPFAction, - KnownPFResult as TestRunOperationsClientKnownPFResult, PFResult as TestRunOperationsClientPFResult, - AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, - KnownSecretType as TestRunOperationsClientKnownSecretType, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, - KnownCertificateType as TestRunOperationsClientKnownCertificateType, CertificateType as TestRunOperationsClientCertificateType, LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, - RegionalConfiguration as TestRunOperationsClientRegionalConfiguration, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, - TestFileInfo as TestRunOperationsClientTestFileInfo, - KnownFileType as TestRunOperationsClientKnownFileType, + FileInfo as TestRunOperationsClientFileInfo, FileType as TestRunOperationsClientFileType, - KnownFileStatus as TestRunOperationsClientKnownFileStatus, FileStatus as TestRunOperationsClientFileStatus, - KnownTestKind as TestRunOperationsClientKnownTestKind, - TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, TestServerMetricConfig as TestRunOperationsClientTestServerMetricConfig, @@ -148,28 +106,20 @@ export { TestRunStatistics as TestRunOperationsClientTestRunStatistics, TestRunArtifacts as TestRunOperationsClientTestRunArtifacts, TestRunInputArtifacts as TestRunOperationsClientTestRunInputArtifacts, - TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, - KnownPFTestResult as TestRunOperationsClientKnownPFTestResult, PFTestResult as TestRunOperationsClientPFTestResult, - KnownStatus as TestRunOperationsClientKnownStatus, Status as TestRunOperationsClientStatus, - KnownRequestDataLevel as TestRunOperationsClientKnownRequestDataLevel, - RequestDataLevel as TestRunOperationsClientRequestDataLevel, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, - KnownTimeGrain as TestRunOperationsClientKnownTimeGrain, - TimeGrain as TestRunOperationsClientTimeGrain, + Interval as TestRunOperationsClientInterval, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, NameAndDesc as TestRunOperationsClientNameAndDesc, - KnownAggregationType as TestRunOperationsClientKnownAggregationType, AggregationType as TestRunOperationsClientAggregationType, - KnownMetricUnit as TestRunOperationsClientKnownMetricUnit, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, + TimeGrain as TestRunOperationsClientTimeGrain, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, MetricNamespace as TestRunOperationsClientMetricNamespace, MetricRequestPayload as TestRunOperationsClientMetricRequestPayload, @@ -177,21 +127,7 @@ export { TimeSeriesElement as TestRunOperationsClientTimeSeriesElement, MetricValue as TestRunOperationsClientMetricValue, DimensionValue as TestRunOperationsClientDimensionValue, - TestProfile as TestRunOperationsClientTestProfile, - TargetResourceConfigurations as TestRunOperationsClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as TestRunOperationsClientKnownResourceKind, - ResourceKind as TestRunOperationsClientResourceKind, - TestProfileRun as TestRunOperationsClientTestProfileRun, - KnownTestProfileRunStatus as TestRunOperationsClientKnownTestProfileRunStatus, - TestProfileRunStatus as TestRunOperationsClientTestProfileRunStatus, - TestRunDetail as TestRunOperationsClientTestRunDetail, - TestProfileRunRecommendation as TestRunOperationsClientTestProfileRunRecommendation, - KnownRecommendationCategory as TestRunOperationsClientKnownRecommendationCategory, - RecommendationCategory as TestRunOperationsClientRecommendationCategory, - TargetResourceConfigurationsUnion as TestRunOperationsClientTargetResourceConfigurationsUnion, - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -204,199 +140,8 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, PageSettings as TestRunOperationsClientPageSettings, ContinuablePage as TestRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestRunOperationsClientPagedAsyncIterableIterator, } from "./testRunOperations/models/index.js"; -export { - TestProfileAdministrationOperationsClient, - TestProfileAdministrationOperationsClientOptions, -} from "./testProfileAdministrationOperations/testProfileAdministrationOperationsClient.js"; -export { - Test as TestProfileAdministrationOperationsClientTest, - PassFailCriteria as TestProfileAdministrationOperationsClientPassFailCriteria, - PassFailMetric as TestProfileAdministrationOperationsClientPassFailMetric, - KnownPFMetrics as TestProfileAdministrationOperationsClientKnownPFMetrics, - PFMetrics as TestProfileAdministrationOperationsClientPFMetrics, - KnownPFAgFunc as TestProfileAdministrationOperationsClientKnownPFAgFunc, - PFAgFunc as TestProfileAdministrationOperationsClientPFAgFunc, - KnownPFAction as TestProfileAdministrationOperationsClientKnownPFAction, - PFAction as TestProfileAdministrationOperationsClientPFAction, - KnownPFResult as TestProfileAdministrationOperationsClientKnownPFResult, - PFResult as TestProfileAdministrationOperationsClientPFResult, - AutoStopCriteria as TestProfileAdministrationOperationsClientAutoStopCriteria, - Secret as TestProfileAdministrationOperationsClientSecret, - KnownSecretType as TestProfileAdministrationOperationsClientKnownSecretType, - SecretType as TestProfileAdministrationOperationsClientSecretType, - CertificateMetadata as TestProfileAdministrationOperationsClientCertificateMetadata, - KnownCertificateType as TestProfileAdministrationOperationsClientKnownCertificateType, - CertificateType as TestProfileAdministrationOperationsClientCertificateType, - LoadTestConfiguration as TestProfileAdministrationOperationsClientLoadTestConfiguration, - OptionalLoadTestConfig as TestProfileAdministrationOperationsClientOptionalLoadTestConfig, - RegionalConfiguration as TestProfileAdministrationOperationsClientRegionalConfiguration, - TestInputArtifacts as TestProfileAdministrationOperationsClientTestInputArtifacts, - TestFileInfo as TestProfileAdministrationOperationsClientTestFileInfo, - KnownFileType as TestProfileAdministrationOperationsClientKnownFileType, - FileType as TestProfileAdministrationOperationsClientFileType, - KnownFileStatus as TestProfileAdministrationOperationsClientKnownFileStatus, - FileStatus as TestProfileAdministrationOperationsClientFileStatus, - KnownTestKind as TestProfileAdministrationOperationsClientKnownTestKind, - TestKind as TestProfileAdministrationOperationsClientTestKind, - TestAppComponents as TestProfileAdministrationOperationsClientTestAppComponents, - AppComponent as TestProfileAdministrationOperationsClientAppComponent, - TestServerMetricConfig as TestProfileAdministrationOperationsClientTestServerMetricConfig, - ResourceMetric as TestProfileAdministrationOperationsClientResourceMetric, - APIVersions as TestProfileAdministrationOperationsClientAPIVersions, - TestRun as TestProfileAdministrationOperationsClientTestRun, - ErrorDetails as TestProfileAdministrationOperationsClientErrorDetails, - TestRunStatistics as TestProfileAdministrationOperationsClientTestRunStatistics, - TestRunArtifacts as TestProfileAdministrationOperationsClientTestRunArtifacts, - TestRunInputArtifacts as TestProfileAdministrationOperationsClientTestRunInputArtifacts, - TestRunFileInfo as TestProfileAdministrationOperationsClientTestRunFileInfo, - TestRunOutputArtifacts as TestProfileAdministrationOperationsClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestProfileAdministrationOperationsClientArtifactsContainerInfo, - KnownPFTestResult as TestProfileAdministrationOperationsClientKnownPFTestResult, - PFTestResult as TestProfileAdministrationOperationsClientPFTestResult, - KnownStatus as TestProfileAdministrationOperationsClientKnownStatus, - Status as TestProfileAdministrationOperationsClientStatus, - KnownRequestDataLevel as TestProfileAdministrationOperationsClientKnownRequestDataLevel, - RequestDataLevel as TestProfileAdministrationOperationsClientRequestDataLevel, - TestRunAppComponents as TestProfileAdministrationOperationsClientTestRunAppComponents, - TestRunServerMetricConfig as TestProfileAdministrationOperationsClientTestRunServerMetricConfig, - KnownTimeGrain as TestProfileAdministrationOperationsClientKnownTimeGrain, - TimeGrain as TestProfileAdministrationOperationsClientTimeGrain, - DimensionValueList as TestProfileAdministrationOperationsClientDimensionValueList, - MetricDefinitionCollection as TestProfileAdministrationOperationsClientMetricDefinitionCollection, - MetricDefinition as TestProfileAdministrationOperationsClientMetricDefinition, - NameAndDesc as TestProfileAdministrationOperationsClientNameAndDesc, - KnownAggregationType as TestProfileAdministrationOperationsClientKnownAggregationType, - AggregationType as TestProfileAdministrationOperationsClientAggregationType, - KnownMetricUnit as TestProfileAdministrationOperationsClientKnownMetricUnit, - MetricUnit as TestProfileAdministrationOperationsClientMetricUnit, - MetricAvailability as TestProfileAdministrationOperationsClientMetricAvailability, - MetricNamespaceCollection as TestProfileAdministrationOperationsClientMetricNamespaceCollection, - MetricNamespace as TestProfileAdministrationOperationsClientMetricNamespace, - MetricRequestPayload as TestProfileAdministrationOperationsClientMetricRequestPayload, - DimensionFilter as TestProfileAdministrationOperationsClientDimensionFilter, - TimeSeriesElement as TestProfileAdministrationOperationsClientTimeSeriesElement, - MetricValue as TestProfileAdministrationOperationsClientMetricValue, - DimensionValue as TestProfileAdministrationOperationsClientDimensionValue, - TestProfile as TestProfileAdministrationOperationsClientTestProfile, - TargetResourceConfigurations as TestProfileAdministrationOperationsClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as TestProfileAdministrationOperationsClientKnownResourceKind, - ResourceKind as TestProfileAdministrationOperationsClientResourceKind, - TestProfileRun as TestProfileAdministrationOperationsClientTestProfileRun, - KnownTestProfileRunStatus as TestProfileAdministrationOperationsClientKnownTestProfileRunStatus, - TestProfileRunStatus as TestProfileAdministrationOperationsClientTestProfileRunStatus, - TestRunDetail as TestProfileAdministrationOperationsClientTestRunDetail, - TestProfileRunRecommendation as TestProfileAdministrationOperationsClientTestProfileRunRecommendation, - KnownRecommendationCategory as TestProfileAdministrationOperationsClientKnownRecommendationCategory, - RecommendationCategory as TestProfileAdministrationOperationsClientRecommendationCategory, - TargetResourceConfigurationsUnion as TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion, - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, - ListTestProfilesOptionalParams, - PageSettings as TestProfileAdministrationOperationsClientPageSettings, - ContinuablePage as TestProfileAdministrationOperationsClientContinuablePage, - PagedAsyncIterableIterator as TestProfileAdministrationOperationsClientPagedAsyncIterableIterator, -} from "./testProfileAdministrationOperations/models/index.js"; -export { - TestProfileRunOperationsClient, - TestProfileRunOperationsClientOptions, -} from "./testProfileRunOperations/testProfileRunOperationsClient.js"; -export { - Test as TestProfileRunOperationsClientTest, - PassFailCriteria as TestProfileRunOperationsClientPassFailCriteria, - PassFailMetric as TestProfileRunOperationsClientPassFailMetric, - KnownPFMetrics as TestProfileRunOperationsClientKnownPFMetrics, - PFMetrics as TestProfileRunOperationsClientPFMetrics, - KnownPFAgFunc as TestProfileRunOperationsClientKnownPFAgFunc, - PFAgFunc as TestProfileRunOperationsClientPFAgFunc, - KnownPFAction as TestProfileRunOperationsClientKnownPFAction, - PFAction as TestProfileRunOperationsClientPFAction, - KnownPFResult as TestProfileRunOperationsClientKnownPFResult, - PFResult as TestProfileRunOperationsClientPFResult, - AutoStopCriteria as TestProfileRunOperationsClientAutoStopCriteria, - Secret as TestProfileRunOperationsClientSecret, - KnownSecretType as TestProfileRunOperationsClientKnownSecretType, - SecretType as TestProfileRunOperationsClientSecretType, - CertificateMetadata as TestProfileRunOperationsClientCertificateMetadata, - KnownCertificateType as TestProfileRunOperationsClientKnownCertificateType, - CertificateType as TestProfileRunOperationsClientCertificateType, - LoadTestConfiguration as TestProfileRunOperationsClientLoadTestConfiguration, - OptionalLoadTestConfig as TestProfileRunOperationsClientOptionalLoadTestConfig, - RegionalConfiguration as TestProfileRunOperationsClientRegionalConfiguration, - TestInputArtifacts as TestProfileRunOperationsClientTestInputArtifacts, - TestFileInfo as TestProfileRunOperationsClientTestFileInfo, - KnownFileType as TestProfileRunOperationsClientKnownFileType, - FileType as TestProfileRunOperationsClientFileType, - KnownFileStatus as TestProfileRunOperationsClientKnownFileStatus, - FileStatus as TestProfileRunOperationsClientFileStatus, - KnownTestKind as TestProfileRunOperationsClientKnownTestKind, - TestKind as TestProfileRunOperationsClientTestKind, - TestAppComponents as TestProfileRunOperationsClientTestAppComponents, - AppComponent as TestProfileRunOperationsClientAppComponent, - TestServerMetricConfig as TestProfileRunOperationsClientTestServerMetricConfig, - ResourceMetric as TestProfileRunOperationsClientResourceMetric, - APIVersions as TestProfileRunOperationsClientAPIVersions, - TestRun as TestProfileRunOperationsClientTestRun, - ErrorDetails as TestProfileRunOperationsClientErrorDetails, - TestRunStatistics as TestProfileRunOperationsClientTestRunStatistics, - TestRunArtifacts as TestProfileRunOperationsClientTestRunArtifacts, - TestRunInputArtifacts as TestProfileRunOperationsClientTestRunInputArtifacts, - TestRunFileInfo as TestProfileRunOperationsClientTestRunFileInfo, - TestRunOutputArtifacts as TestProfileRunOperationsClientTestRunOutputArtifacts, - ArtifactsContainerInfo as TestProfileRunOperationsClientArtifactsContainerInfo, - KnownPFTestResult as TestProfileRunOperationsClientKnownPFTestResult, - PFTestResult as TestProfileRunOperationsClientPFTestResult, - KnownStatus as TestProfileRunOperationsClientKnownStatus, - Status as TestProfileRunOperationsClientStatus, - KnownRequestDataLevel as TestProfileRunOperationsClientKnownRequestDataLevel, - RequestDataLevel as TestProfileRunOperationsClientRequestDataLevel, - TestRunAppComponents as TestProfileRunOperationsClientTestRunAppComponents, - TestRunServerMetricConfig as TestProfileRunOperationsClientTestRunServerMetricConfig, - KnownTimeGrain as TestProfileRunOperationsClientKnownTimeGrain, - TimeGrain as TestProfileRunOperationsClientTimeGrain, - DimensionValueList as TestProfileRunOperationsClientDimensionValueList, - MetricDefinitionCollection as TestProfileRunOperationsClientMetricDefinitionCollection, - MetricDefinition as TestProfileRunOperationsClientMetricDefinition, - NameAndDesc as TestProfileRunOperationsClientNameAndDesc, - KnownAggregationType as TestProfileRunOperationsClientKnownAggregationType, - AggregationType as TestProfileRunOperationsClientAggregationType, - KnownMetricUnit as TestProfileRunOperationsClientKnownMetricUnit, - MetricUnit as TestProfileRunOperationsClientMetricUnit, - MetricAvailability as TestProfileRunOperationsClientMetricAvailability, - MetricNamespaceCollection as TestProfileRunOperationsClientMetricNamespaceCollection, - MetricNamespace as TestProfileRunOperationsClientMetricNamespace, - MetricRequestPayload as TestProfileRunOperationsClientMetricRequestPayload, - DimensionFilter as TestProfileRunOperationsClientDimensionFilter, - TimeSeriesElement as TestProfileRunOperationsClientTimeSeriesElement, - MetricValue as TestProfileRunOperationsClientMetricValue, - DimensionValue as TestProfileRunOperationsClientDimensionValue, - TestProfile as TestProfileRunOperationsClientTestProfile, - TargetResourceConfigurations as TestProfileRunOperationsClientTargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations as TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration as TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration, - KnownResourceKind as TestProfileRunOperationsClientKnownResourceKind, - ResourceKind as TestProfileRunOperationsClientResourceKind, - TestProfileRun as TestProfileRunOperationsClientTestProfileRun, - KnownTestProfileRunStatus as TestProfileRunOperationsClientKnownTestProfileRunStatus, - TestProfileRunStatus as TestProfileRunOperationsClientTestProfileRunStatus, - TestRunDetail as TestProfileRunOperationsClientTestRunDetail, - TestProfileRunRecommendation as TestProfileRunOperationsClientTestProfileRunRecommendation, - KnownRecommendationCategory as TestProfileRunOperationsClientKnownRecommendationCategory, - RecommendationCategory as TestProfileRunOperationsClientRecommendationCategory, - TargetResourceConfigurationsUnion as TestProfileRunOperationsClientTargetResourceConfigurationsUnion, - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, - StopOptionalParams as TestProfileRunOperationsClientStopOptionalParams, - PageSettings as TestProfileRunOperationsClientPageSettings, - ContinuablePage as TestProfileRunOperationsClientContinuablePage, - PagedAsyncIterableIterator as TestProfileRunOperationsClientPagedAsyncIterableIterator, -} from "./testProfileRunOperations/models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts new file mode 100644 index 0000000000..fb04796c1d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { TokenCredential } from "@azure/core-auth"; +import { AzureLoadTestingContext } from "./clientDefinitions.js"; + +/** The optional parameters for the client */ +export interface AzureLoadTestingContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + +/** + * Initialize a new instance of `AzureLoadTestingContext` + * @param endpointParam - A sequence of textual characters. + * @param credentials - uniquely identify client credential + * @param options - the parameter for all optional parameters + */ +export default function createClient( + endpointParam: string, + credentials: TokenCredential, + { + apiVersion = "2022-11-01", + ...options + }: AzureLoadTestingContextOptions = {}, +): AzureLoadTestingContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; + const userAgentInfo = `azsdk-js-load-testing/1.0.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + credentials: { + scopes: options.credentials?.scopes ?? [ + "https://cnt-prod.loadtesting.azure.com/.default", + ], + }, + }; + const client = getClient( + endpointUrl, + credentials, + options, + ) as AzureLoadTestingContext; + + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts index fa2d60737c..2d1d85129a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -14,12 +14,12 @@ import { LoadTestAdministrationGetAppComponentsParameters, LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters, LoadTestAdministrationGetServerMetricsConfigParameters, - LoadTestRunGetTestRunParameters, - LoadTestRunCreateOrUpdateTestRunParameters, LoadTestRunDeleteTestRunParameters, - LoadTestRunListTestRunsParameters, + LoadTestRunCreateOrUpdateTestRunParameters, + LoadTestRunGetTestRunParameters, LoadTestRunGetTestRunFileParameters, - LoadTestRunStopParameters, + LoadTestRunListTestRunsParameters, + LoadTestRunStopTestRunParameters, LoadTestRunListMetricNamespacesParameters, LoadTestRunListMetricDefinitionsParameters, LoadTestRunListMetricsParameters, @@ -27,16 +27,7 @@ import { LoadTestRunCreateOrUpdateAppComponentsParameters, LoadTestRunGetAppComponentsParameters, LoadTestRunCreateOrUpdateServerMetricsConfigParameters, - LoadTestRunGetServerMetricsConfigParameters, - TestProfileAdministrationCreateOrUpdateTestProfileParameters, - TestProfileAdministrationDeleteTestProfileParameters, - TestProfileAdministrationGetTestProfileParameters, - TestProfileAdministrationListTestProfilesParameters, - TestProfileRunAdministrationGetTestProfileRunParameters, - TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, - TestProfileRunAdministrationDeleteTestProfileRunParameters, - TestProfileRunAdministrationStopParameters, - TestProfileRunAdministrationListTestProfileRunsParameters, + LoadTestRunTestRunListServerMetricsConfigParameters, } from "./parameters.js"; import { LoadTestAdministrationCreateOrUpdateTest200Response, @@ -66,19 +57,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, - LoadTestRunListTestRuns200Response, - LoadTestRunListTestRunsDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, LoadTestRunGetTestRunFileDefaultResponse, - LoadTestRunStop200Response, - LoadTestRunStopDefaultResponse, + LoadTestRunListTestRuns200Response, + LoadTestRunListTestRunsDefaultResponse, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -95,33 +86,13 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, - TestProfileAdministrationCreateOrUpdateTestProfile200Response, - TestProfileAdministrationCreateOrUpdateTestProfile201Response, - TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, - TestProfileAdministrationDeleteTestProfile204Response, - TestProfileAdministrationDeleteTestProfileDefaultResponse, - TestProfileAdministrationGetTestProfile200Response, - TestProfileAdministrationGetTestProfileDefaultResponse, - TestProfileAdministrationListTestProfiles200Response, - TestProfileAdministrationListTestProfilesDefaultResponse, - TestProfileRunAdministrationGetTestProfileRun200Response, - TestProfileRunAdministrationGetTestProfileRunDefaultResponse, - TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, - TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, - TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, - TestProfileRunAdministrationDeleteTestProfileRun204Response, - TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, - TestProfileRunAdministrationStop200Response, - TestProfileRunAdministrationStopDefaultResponse, - TestProfileRunAdministrationListTestProfileRuns200Response, - TestProfileRunAdministrationListTestProfileRunsDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; export interface LoadTestAdministrationCreateOrUpdateTest { - /** Create a new test or update an existing test by providing the test Id. */ + /** Create a new test or update an existing test. */ patch( options: LoadTestAdministrationCreateOrUpdateTestParameters, ): StreamableMethod< @@ -129,14 +100,14 @@ export interface LoadTestAdministrationCreateOrUpdateTest { | LoadTestAdministrationCreateOrUpdateTest201Response | LoadTestAdministrationCreateOrUpdateTestDefaultResponse >; - /** Delete a test by its test Id. */ + /** Delete a test by its name. */ delete( options?: LoadTestAdministrationDeleteTestParameters, ): StreamableMethod< | LoadTestAdministrationDeleteTest204Response | LoadTestAdministrationDeleteTestDefaultResponse >; - /** Get load test details by test Id */ + /** Get load test details by test name */ get( options?: LoadTestAdministrationGetTestParameters, ): StreamableMethod< @@ -160,7 +131,7 @@ export interface LoadTestAdministrationListTests { export interface LoadTestAdministrationUploadTestFile { /** - * Upload input file for a given test Id. File size can't be more than 50 MB. + * Upload input file for a given test name. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -170,7 +141,7 @@ export interface LoadTestAdministrationUploadTestFile { | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse >; - /** Get all the files that are associated with a test. */ + /** Get test file by the file name. */ get( options?: LoadTestAdministrationGetTestFileParameters, ): StreamableMethod< @@ -197,7 +168,7 @@ export interface LoadTestAdministrationListTestFiles { } export interface LoadTestAdministrationCreateOrUpdateAppComponents { - /** Add an app component to a test by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test */ patch( options: LoadTestAdministrationCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -232,14 +203,15 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfig { >; } -export interface LoadTestRunGetTestRun { - /** Get test run details by test run Id. */ - get( - options?: LoadTestRunGetTestRunParameters, +export interface LoadTestRunDeleteTestRun { + /** Delete a test run by its name. */ + delete( + options?: LoadTestRunDeleteTestRunParameters, ): StreamableMethod< - LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse >; - /** Create and start a new test run with the given test run Id. */ + /** Create and start a new test run with the given name. */ patch( options: LoadTestRunCreateOrUpdateTestRunParameters, ): StreamableMethod< @@ -247,21 +219,11 @@ export interface LoadTestRunGetTestRun { | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse >; - /** Delete an existing load test run by providing the testRunId. */ - delete( - options?: LoadTestRunDeleteTestRunParameters, - ): StreamableMethod< - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse - >; -} - -export interface LoadTestRunListTestRuns { - /** Get all test runs for the given filters. */ + /** Get test run details by name. */ get( - options?: LoadTestRunListTestRunsParameters, + options?: LoadTestRunGetTestRunParameters, ): StreamableMethod< - LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse + LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse >; } @@ -275,12 +237,21 @@ export interface LoadTestRunGetTestRunFile { >; } -export interface LoadTestRunStop { - /** Stop test run by test run Id. */ +export interface LoadTestRunListTestRuns { + /** Get all test runs with given filters */ + get( + options?: LoadTestRunListTestRunsParameters, + ): StreamableMethod< + LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse + >; +} + +export interface LoadTestRunStopTestRun { + /** Stop test run by name. */ post( - options?: LoadTestRunStopParameters, + options?: LoadTestRunStopTestRunParameters, ): StreamableMethod< - LoadTestRunStop200Response | LoadTestRunStopDefaultResponse + LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse >; } @@ -297,7 +268,7 @@ export interface LoadTestRunListMetricNamespaces { export interface LoadTestRunListMetricDefinitions { /** List the metric definitions for a load test run. */ get( - options: LoadTestRunListMetricDefinitionsParameters, + options?: LoadTestRunListMetricDefinitionsParameters, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response | LoadTestRunListMetricDefinitionsDefaultResponse @@ -324,7 +295,7 @@ export interface LoadTestRunListMetricDimensionValues { } export interface LoadTestRunCreateOrUpdateAppComponents { - /** Add an app component to a test run by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test run */ patch( options: LoadTestRunCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -353,92 +324,12 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfig { | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse >; - /** Get associated server metrics configuration for the given test run. */ + /** List server metrics configuration for the given test run. */ get( - options?: LoadTestRunGetServerMetricsConfigParameters, + options?: LoadTestRunTestRunListServerMetricsConfigParameters, ): StreamableMethod< - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse - >; -} - -export interface TestProfileAdministrationCreateOrUpdateTestProfile { - /** Create a new test profile or update an existing test profile by providing the test profile Id. */ - patch( - options: TestProfileAdministrationCreateOrUpdateTestProfileParameters, - ): StreamableMethod< - | TestProfileAdministrationCreateOrUpdateTestProfile200Response - | TestProfileAdministrationCreateOrUpdateTestProfile201Response - | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse - >; - /** Delete a test profile by its test profile Id. */ - delete( - options?: TestProfileAdministrationDeleteTestProfileParameters, - ): StreamableMethod< - | TestProfileAdministrationDeleteTestProfile204Response - | TestProfileAdministrationDeleteTestProfileDefaultResponse - >; - /** Get load test profile details by test profile Id. */ - get( - options?: TestProfileAdministrationGetTestProfileParameters, - ): StreamableMethod< - | TestProfileAdministrationGetTestProfile200Response - | TestProfileAdministrationGetTestProfileDefaultResponse - >; -} - -export interface TestProfileAdministrationListTestProfiles { - /** Get all test profiles for the given filters. */ - get( - options?: TestProfileAdministrationListTestProfilesParameters, - ): StreamableMethod< - | TestProfileAdministrationListTestProfiles200Response - | TestProfileAdministrationListTestProfilesDefaultResponse - >; -} - -export interface TestProfileRunAdministrationGetTestProfileRun { - /** Get test profile run details by test profile run Id. */ - get( - options?: TestProfileRunAdministrationGetTestProfileRunParameters, - ): StreamableMethod< - | TestProfileRunAdministrationGetTestProfileRun200Response - | TestProfileRunAdministrationGetTestProfileRunDefaultResponse - >; - /** Create and start a new test profile run with the given test profile run Id. */ - patch( - options: TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, - ): StreamableMethod< - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse - >; - /** Delete an existing load test profile run by providing the test profile run Id. */ - delete( - options?: TestProfileRunAdministrationDeleteTestProfileRunParameters, - ): StreamableMethod< - | TestProfileRunAdministrationDeleteTestProfileRun204Response - | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse - >; -} - -export interface TestProfileRunAdministrationStop { - /** Stop test profile run for the given test profile run Id. */ - post( - options?: TestProfileRunAdministrationStopParameters, - ): StreamableMethod< - | TestProfileRunAdministrationStop200Response - | TestProfileRunAdministrationStopDefaultResponse - >; -} - -export interface TestProfileRunAdministrationListTestProfileRuns { - /** Get all test profile runs for the given filters. */ - get( - options?: TestProfileRunAdministrationListTestProfileRunsParameters, - ): StreamableMethod< - | TestProfileRunAdministrationListTestProfileRuns200Response - | TestProfileRunAdministrationListTestProfileRunsDefaultResponse + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse >; } @@ -471,18 +362,21 @@ export interface Routes { path: "/tests/{testId}/server-metrics-config", testId: string, ): LoadTestAdministrationCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: get, patch, delete */ - (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunGetTestRun; - /** Resource for '/test-runs' has methods for the following verbs: get */ - (path: "/test-runs"): LoadTestRunListTestRuns; + /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: delete, patch, get */ + (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunDeleteTestRun; /** Resource for '/test-runs/\{testRunId\}/files/\{fileName\}' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/files/{fileName}", testRunId: string, fileName: string, ): LoadTestRunGetTestRunFile; + /** Resource for '/test-runs' has methods for the following verbs: get */ + (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}:stop' has methods for the following verbs: post */ - (path: "/test-runs/{testRunId}:stop", testRunId: string): LoadTestRunStop; + ( + path: "/test-runs/{testRunId}:stop", + testRunId: string, + ): LoadTestRunStopTestRun; /** Resource for '/test-runs/\{testRunId\}/metric-namespaces' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/metric-namespaces", @@ -514,27 +408,8 @@ export interface Routes { path: "/test-runs/{testRunId}/server-metrics-config", testRunId: string, ): LoadTestRunCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-profiles/\{testProfileId\}' has methods for the following verbs: patch, delete, get */ - ( - path: "/test-profiles/{testProfileId}", - testProfileId: string, - ): TestProfileAdministrationCreateOrUpdateTestProfile; - /** Resource for '/test-profiles' has methods for the following verbs: get */ - (path: "/test-profiles"): TestProfileAdministrationListTestProfiles; - /** Resource for '/test-profile-runs/\{testProfileRunId\}' has methods for the following verbs: get, patch, delete */ - ( - path: "/test-profile-runs/{testProfileRunId}", - testProfileRunId: string, - ): TestProfileRunAdministrationGetTestProfileRun; - /** Resource for '/test-profile-runs/\{testProfileRunId\}:stop' has methods for the following verbs: post */ - ( - path: "/test-profile-runs/{testProfileRunId}:stop", - testProfileRunId: string, - ): TestProfileRunAdministrationStop; - /** Resource for '/test-profile-runs' has methods for the following verbs: get */ - (path: "/test-profile-runs"): TestProfileRunAdministrationListTestProfileRuns; } -export type LoadTestServiceContext = Client & { +export type AzureLoadTestingContext = Client & { path: Routes; }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts index b57cb81db2..a22d574c4f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import LoadTestServiceClient from "./loadTestServiceClient.js"; +import AzureLoadTestingClient from "./azureLoadTestingClient.js"; -export * from "./loadTestServiceClient.js"; +export * from "./azureLoadTestingClient.js"; export * from "./parameters.js"; export * from "./responses.js"; export * from "./clientDefinitions.js"; @@ -11,5 +11,6 @@ export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; export * from "./paginateHelper.js"; +export * from "./pollingHelper.js"; -export default LoadTestServiceClient; +export default AzureLoadTestingClient; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts index fdb24b329f..e02ac644d2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts @@ -29,19 +29,20 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, - LoadTestRunListTestRuns200Response, - LoadTestRunListTestRunsDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, LoadTestRunGetTestRunFileDefaultResponse, - LoadTestRunStop200Response, - LoadTestRunStopDefaultResponse, + LoadTestRunListTestRuns200Response, + LoadTestRunListTestRunsDefaultResponse, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -58,28 +59,8 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, - TestProfileAdministrationCreateOrUpdateTestProfile200Response, - TestProfileAdministrationCreateOrUpdateTestProfile201Response, - TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, - TestProfileAdministrationDeleteTestProfile204Response, - TestProfileAdministrationDeleteTestProfileDefaultResponse, - TestProfileAdministrationGetTestProfile200Response, - TestProfileAdministrationGetTestProfileDefaultResponse, - TestProfileAdministrationListTestProfiles200Response, - TestProfileAdministrationListTestProfilesDefaultResponse, - TestProfileRunAdministrationGetTestProfileRun200Response, - TestProfileRunAdministrationGetTestProfileRunDefaultResponse, - TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, - TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, - TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, - TestProfileRunAdministrationDeleteTestProfileRun204Response, - TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, - TestProfileRunAdministrationStop200Response, - TestProfileRunAdministrationStopDefaultResponse, - TestProfileRunAdministrationListTestProfileRuns200Response, - TestProfileRunAdministrationListTestProfileRunsDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -95,11 +76,11 @@ const responseMap: Record = { "GET /tests/{testId}/app-components": ["200"], "PATCH /tests/{testId}/server-metrics-config": ["200", "201"], "GET /tests/{testId}/server-metrics-config": ["200"], + "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs/{testRunId}": ["200"], "PATCH /test-runs/{testRunId}": ["200", "201"], - "DELETE /test-runs/{testRunId}": ["204"], - "GET /test-runs": ["200"], "GET /test-runs/{testRunId}/files/{fileName}": ["200"], + "GET /test-runs": ["200"], "POST /test-runs/{testRunId}:stop": ["200"], "GET /test-runs/{testRunId}/metric-namespaces": ["200"], "GET /test-runs/{testRunId}/metric-definitions": ["200"], @@ -109,15 +90,6 @@ const responseMap: Record = { "GET /test-runs/{testRunId}/app-components": ["200"], "PATCH /test-runs/{testRunId}/server-metrics-config": ["200", "201"], "GET /test-runs/{testRunId}/server-metrics-config": ["200"], - "PATCH /test-profiles/{testProfileId}": ["200", "201"], - "DELETE /test-profiles/{testProfileId}": ["204"], - "GET /test-profiles/{testProfileId}": ["200"], - "GET /test-profiles": ["200"], - "GET /test-profile-runs/{testProfileRunId}": ["200"], - "PATCH /test-profile-runs/{testProfileRunId}": ["200", "201"], - "DELETE /test-profile-runs/{testProfileRunId}": ["204"], - "POST /test-profile-runs/{testProfileRunId}:stop": ["200"], - "GET /test-profile-runs": ["200"], }; export function isUnexpected( @@ -185,20 +157,26 @@ export function isUnexpected( ): response is LoadTestAdministrationGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse, -): response is LoadTestRunGetTestRunDefaultResponse; + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse, +): response is LoadTestRunDeleteTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): response is LoadTestRunCreateOrUpdateTestRunDefaultResponse; export function isUnexpected( response: - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse, -): response is LoadTestRunDeleteTestRunDefaultResponse; + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse, +): response is LoadTestRunGetTestRunDefaultResponse; +export function isUnexpected( + response: + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse, +): response is LoadTestRunGetTestRunFileDefaultResponse; export function isUnexpected( response: | LoadTestRunListTestRuns200Response @@ -206,12 +184,9 @@ export function isUnexpected( ): response is LoadTestRunListTestRunsDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse, -): response is LoadTestRunGetTestRunFileDefaultResponse; -export function isUnexpected( - response: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, -): response is LoadTestRunStopDefaultResponse; + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse, +): response is LoadTestRunStopTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunListMetricNamespaces200Response @@ -251,56 +226,9 @@ export function isUnexpected( ): response is LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse, -): response is LoadTestRunGetServerMetricsConfigDefaultResponse; -export function isUnexpected( - response: - | TestProfileAdministrationCreateOrUpdateTestProfile200Response - | TestProfileAdministrationCreateOrUpdateTestProfile201Response - | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, -): response is TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse; -export function isUnexpected( - response: - | TestProfileAdministrationDeleteTestProfile204Response - | TestProfileAdministrationDeleteTestProfileDefaultResponse, -): response is TestProfileAdministrationDeleteTestProfileDefaultResponse; -export function isUnexpected( - response: - | TestProfileAdministrationGetTestProfile200Response - | TestProfileAdministrationGetTestProfileDefaultResponse, -): response is TestProfileAdministrationGetTestProfileDefaultResponse; -export function isUnexpected( - response: - | TestProfileAdministrationListTestProfiles200Response - | TestProfileAdministrationListTestProfilesDefaultResponse, -): response is TestProfileAdministrationListTestProfilesDefaultResponse; -export function isUnexpected( - response: - | TestProfileRunAdministrationGetTestProfileRun200Response - | TestProfileRunAdministrationGetTestProfileRunDefaultResponse, -): response is TestProfileRunAdministrationGetTestProfileRunDefaultResponse; -export function isUnexpected( - response: - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, -): response is TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse; -export function isUnexpected( - response: - | TestProfileRunAdministrationDeleteTestProfileRun204Response - | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, -): response is TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse; -export function isUnexpected( - response: - | TestProfileRunAdministrationStop200Response - | TestProfileRunAdministrationStopDefaultResponse, -): response is TestProfileRunAdministrationStopDefaultResponse; -export function isUnexpected( - response: - | TestProfileRunAdministrationListTestProfileRuns200Response - | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, -): response is TestProfileRunAdministrationListTestProfileRunsDefaultResponse; + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, +): response is LoadTestRunTestRunListServerMetricsConfigDefaultResponse; export function isUnexpected( response: | LoadTestAdministrationCreateOrUpdateTest200Response @@ -330,19 +258,20 @@ export function isUnexpected( | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfig200Response | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunListTestRuns200Response - | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse - | LoadTestRunStop200Response - | LoadTestRunStopDefaultResponse + | LoadTestRunListTestRuns200Response + | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse | LoadTestRunListMetricNamespaces200Response | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitions200Response @@ -359,28 +288,8 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateServerMetricsConfig200Response | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse - | TestProfileAdministrationCreateOrUpdateTestProfile200Response - | TestProfileAdministrationCreateOrUpdateTestProfile201Response - | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse - | TestProfileAdministrationDeleteTestProfile204Response - | TestProfileAdministrationDeleteTestProfileDefaultResponse - | TestProfileAdministrationGetTestProfile200Response - | TestProfileAdministrationGetTestProfileDefaultResponse - | TestProfileAdministrationListTestProfiles200Response - | TestProfileAdministrationListTestProfilesDefaultResponse - | TestProfileRunAdministrationGetTestProfileRun200Response - | TestProfileRunAdministrationGetTestProfileRunDefaultResponse - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response - | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse - | TestProfileRunAdministrationDeleteTestProfileRun204Response - | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse - | TestProfileRunAdministrationStop200Response - | TestProfileRunAdministrationStopDefaultResponse - | TestProfileRunAdministrationListTestProfileRuns200Response - | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, ): response is | LoadTestAdministrationCreateOrUpdateTestDefaultResponse | LoadTestAdministrationDeleteTestDefaultResponse @@ -394,12 +303,12 @@ export function isUnexpected( | LoadTestAdministrationGetAppComponentsDefaultResponse | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunGetTestRunFileDefaultResponse - | LoadTestRunStopDefaultResponse + | LoadTestRunListTestRunsDefaultResponse + | LoadTestRunStopTestRunDefaultResponse | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitionsDefaultResponse | LoadTestRunListMetricsDefaultResponse @@ -407,16 +316,7 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateAppComponentsDefaultResponse | LoadTestRunGetAppComponentsDefaultResponse | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunGetServerMetricsConfigDefaultResponse - | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse - | TestProfileAdministrationDeleteTestProfileDefaultResponse - | TestProfileAdministrationGetTestProfileDefaultResponse - | TestProfileAdministrationListTestProfilesDefaultResponse - | TestProfileRunAdministrationGetTestProfileRunDefaultResponse - | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse - | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse - | TestProfileRunAdministrationStopDefaultResponse - | TestProfileRunAdministrationListTestProfileRunsDefaultResponse { + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index c44491cdab..a102d07cb8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -1,12 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model. */ +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,28 +13,18 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** - * Kind of test. - * - * Possible values: "URL", "JMX", "Locust" - */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ @@ -51,19 +39,13 @@ export interface PassFailCriteria { /** Pass fail metric */ export interface PassFailMetric { - /** - * The client metric on which the criteria should be applied. - * - * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" - */ + /** The client metric on which the criteria should be applied. */ clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests - * - * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFunc; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -75,33 +57,15 @@ export interface PassFailMetric { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** - * Action taken after the threshold is met. Default is ‘continue’. - * - * Possible values: "continue", "stop" - */ + /** Action taken after the threshold is met. Default is ‘continue’. */ action?: PFAction; } -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - /** Secret */ export interface Secret { /** The value of the secret for the respective type */ value?: string; - /** - * Type of secret - * - * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" - */ + /** Type of secret */ type?: SecretType; } @@ -109,19 +73,18 @@ export interface Secret { export interface CertificateMetadata { /** The value of the certificate for respective type */ value?: string; - /** - * Type of certificate - * - * Possible values: "AKV_CERT_URI" - */ + /** Type of certificate */ type?: CertificateType; /** Name of the certificate. */ name?: string; } -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -135,61 +98,54 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: Array; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; } -/** Test file info. */ -export interface TestFileInfo { +/** File info */ +export interface FileInfo { + /** File URL. */ + url?: string; /** Name of the file. */ - fileName: string; -} - -/** Test app components */ + fileName?: string; + /** File type */ + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; + /** Validation status of the file */ + validationStatus?: FileStatus; + /** Validation failure error details */ + validationFailureDetails?: string; +} + +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -199,12 +155,15 @@ export interface TestAppComponents { components: Record; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Kind of Azure resource type */ @@ -218,7 +177,7 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; + metrics?: Record; } /** @@ -247,8 +206,6 @@ export interface ResourceMetric { export interface TestRun { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -269,14 +226,6 @@ export interface TestRun { testId?: string; /** The test run description. */ description?: string; - /** - * Request data collection level for test run - * - * Possible values: "NONE", "ERRORS" - */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; } /** Error details if there is any failure in load test run */ @@ -294,44 +243,24 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; + inputArtifactsZipFileInfo?: FileInfo; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date | string; + logsFileInfo?: FileInfo; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -370,114 +299,60 @@ export interface TestRunServerMetricConfig { metrics?: Record; } -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurations; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurationsParent { - kind: ResourceKind; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurationsParent { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; -} - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** - * Status of the test run. - * - * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" - */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** - * Category of the recommendation. - * - * Possible values: "ThroughputOptimized", "CostOptimized" - */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export type TargetResourceConfigurations = - | TargetResourceConfigurationsParent - | FunctionFlexConsumptionTargetResourceConfigurations; /** Alias for PFMetrics */ -export type PFMetrics = string; +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; /** Alias for PFAgFunc */ -export type PFAgFunc = string; +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; /** Alias for PFAction */ -export type PFAction = string; +export type PFAction = "continue" | "stop"; /** Alias for PFResult */ -export type PFResult = string; +export type PFResult = "passed" | "undetermined" | "failed"; /** Alias for SecretType */ -export type SecretType = string; +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateType */ -export type CertificateType = string; +export type CertificateType = "AKV_CERT_URI"; /** Alias for FileType */ -export type FileType = string; +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; /** Alias for FileStatus */ -export type FileStatus = string; -/** Alias for TestKind */ -export type TestKind = string; +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; /** Alias for PFTestResult */ -export type PFTestResult = string; +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; /** Alias for Status */ -export type Status = string; -/** Alias for RequestDataLevel */ -export type RequestDataLevel = string; -/** Alias for TimeGrain */ -export type TimeGrain = string; -/** Alias for ResourceKind */ -export type ResourceKind = string; -/** Alias for TestProfileRunStatus */ -export type TestProfileRunStatus = string; -/** Alias for RecommendationCategory */ -export type RecommendationCategory = string; +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; +/** Alias for Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index 1d62e9319d..392e850e81 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -3,12 +3,10 @@ import { Paged } from "@azure/core-paging"; -/** Load test model. */ +/** Load test model */ export interface TestOutput { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -17,41 +15,31 @@ export interface TestOutput { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadataOutput; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifactsOutput; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** - * Kind of test. - * - * Possible values: "URL", "JMX", "Locust" - */ - kind?: TestKindOutput; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -65,19 +53,13 @@ export interface PassFailCriteriaOutput { /** Pass fail metric */ export interface PassFailMetricOutput { - /** - * The client metric on which the criteria should be applied. - * - * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" - */ + /** The client metric on which the criteria should be applied. */ clientMetric?: PFMetricsOutput; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests - * - * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFuncOutput; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -89,41 +71,19 @@ export interface PassFailMetricOutput { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** - * Action taken after the threshold is met. Default is ‘continue’. - * - * Possible values: "continue", "stop" - */ + /** Action taken after the threshold is met. Default is ‘continue’. */ action?: PFActionOutput; /** The actual value of the client metric for the test run. */ readonly actualValue?: number; - /** - * Outcome of the test run. - * - * Possible values: "passed", "undetermined", "failed" - */ + /** Outcome of the test run. */ readonly result?: PFResultOutput; } -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteriaOutput { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - /** Secret */ export interface SecretOutput { /** The value of the secret for the respective type */ value?: string; - /** - * Type of secret - * - * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" - */ + /** Type of secret */ type?: SecretTypeOutput; } @@ -131,19 +91,18 @@ export interface SecretOutput { export interface CertificateMetadataOutput { /** The value of the certificate for respective type */ value?: string; - /** - * Type of certificate - * - * Possible values: "AKV_CERT_URI" - */ + /** Type of certificate */ type?: CertificateTypeOutput; /** Name of the certificate. */ name?: string; } -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfigurationOutput { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -157,81 +116,56 @@ export interface LoadTestConfigurationOutput { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfigOutput; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: Array; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfigOutput { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } -/** Region distribution configuration for the load test. */ -export interface RegionalConfigurationOutput { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - /** The input artifacts for the test. */ export interface TestInputArtifactsOutput { /** File info */ - configFileInfo?: TestFileInfoOutput; + configFileInfo?: FileInfoOutput; /** File info */ - testScriptFileInfo?: TestFileInfoOutput; + testScriptFileInfo?: FileInfoOutput; /** File info */ - userPropFileInfo?: TestFileInfoOutput; + userPropFileInfo?: FileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfoOutput; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfoOutput; + inputArtifactsZipFileInfo?: FileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; } -/** Test file info. */ -export interface TestFileInfoOutput { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfoOutput { /** File URL. */ - readonly url?: string; - /** - * File type - * - * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" - */ - readonly fileType?: FileTypeOutput; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: string; - /** - * Validation status of the file - * - * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" - */ - readonly validationStatus?: FileStatusOutput; + url?: string; + /** Name of the file. */ + fileName?: string; + /** File type */ + fileType?: FileTypeOutput; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; + /** Validation status of the file */ + validationStatus?: FileStatusOutput; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Test app components */ +/** Test app component */ export interface TestAppComponentsOutput { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -241,24 +175,30 @@ export interface TestAppComponentsOutput { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponentOutput { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -278,12 +218,12 @@ export interface TestServerMetricConfigOutput { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -315,12 +255,10 @@ export interface ResourceMetricOutput { /** Load test run model */ export interface TestRunOutput { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -335,27 +273,13 @@ export interface TestRunOutput { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: Array; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ + /** Test run statistics. */ readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; /** Collection of test run artifacts */ readonly testArtifacts?: TestRunArtifactsOutput; - /** - * Test result for pass/Fail criteria used during the test run. - * - * Possible values: "PASSED", "NOT_APPLICABLE", "FAILED" - */ + /** Test result for pass/Fail criteria used during the test run. */ readonly testResult?: PFTestResultOutput; /** Number of virtual users, for which test has been run. */ readonly virtualUsers?: number; @@ -365,15 +289,11 @@ export interface TestRunOutput { testId?: string; /** The test run description. */ description?: string; - /** - * The test run status. - * - * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" - */ + /** The test run status. */ readonly status?: StatusOutput; - /** The test run start DateTime(RFC 3339 literal format). */ + /** The test run start DateTime(ISO 8601 literal format). */ readonly startDateTime?: string; - /** The test run end DateTime(RFC 3339 literal format). */ + /** The test run end DateTime(ISO 8601 literal format). */ readonly endDateTime?: string; /** Test run initiated time. */ readonly executedDateTime?: string; @@ -383,27 +303,11 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** - * Type of test. - * - * Possible values: "URL", "JMX", "Locust" - */ - readonly kind?: TestKindOutput; - /** - * Request data collection level for test run - * - * Possible values: "NONE", "ERRORS" - */ - requestDataLevel?: RequestDataLevelOutput; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -439,18 +343,6 @@ export interface TestRunStatisticsOutput { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -470,61 +362,23 @@ export interface TestRunArtifactsOutput { /** The input artifacts for the test run. */ export interface TestRunInputArtifactsOutput { /** File info */ - configFileInfo?: TestRunFileInfoOutput; + configFileInfo?: FileInfoOutput; /** File info */ - testScriptFileInfo?: TestRunFileInfoOutput; + testScriptFileInfo?: FileInfoOutput; /** File info */ - userPropFileInfo?: TestRunFileInfoOutput; + userPropFileInfo?: FileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfoOutput; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfoOutput; + inputArtifactsZipFileInfo?: FileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; -} - -/** Test run file info. */ -export interface TestRunFileInfoOutput { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** - * File type - * - * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" - */ - readonly fileType?: FileTypeOutput; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: string; - /** - * Validation status of the file - * - * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" - */ - readonly validationStatus?: FileStatusOutput; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: Array; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifactsOutput { /** File info */ - resultFileInfo?: TestRunFileInfoOutput; + resultFileInfo?: FileInfoOutput; /** File info */ - logsFileInfo?: TestRunFileInfoOutput; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfoOutput; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfoOutput; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfoOutput { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: string; + logsFileInfo?: FileInfoOutput; } /** Represents collection of metric namespaces. */ @@ -557,19 +411,11 @@ export interface MetricDefinitionOutput { name?: string; /** The namespace the metric belongs to. */ namespace?: string; - /** - * The primary aggregation type value defining how to use the values for display. - * - * Possible values: "Average", "Count", "None", "Total", "Percentile75", "Percentile90", "Percentile95", "Percentile96", "Percentile97", "Percentile98", "Percentile99", "Percentile999", "Percentile9999" - */ + /** The primary aggregation type value defining how to use the values for display. */ primaryAggregationType?: AggregationTypeOutput; /** The collection of what all aggregation types are supported. */ supportedAggregationTypes?: string[]; - /** - * The unit of the metric. - * - * Possible values: "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" - */ + /** The unit of the metric. */ unit?: MetricUnitOutput; /** * Metric availability specifies the time grain (aggregation interval or @@ -591,8 +437,6 @@ export interface MetricAvailabilityOutput { /** * The time grain specifies the aggregation interval for the metric. Expressed as * a duration 'PT1M', 'PT1H', etc. - * - * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ timeGrain?: TimeGrainOutput; } @@ -607,7 +451,7 @@ export interface TimeSeriesElementOutput { /** Represents a metric value. */ export interface MetricValueOutput { - /** The timestamp for the metric value in RFC 3339 format. */ + /** The timestamp for the metric value in ISO 8601 format. */ timestamp?: string; /** The metric value. */ value?: number; @@ -621,14 +465,8 @@ export interface DimensionValueOutput { value?: string; } -/** Metrics dimension values. */ export interface DimensionValueListOutput { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Test run app component */ @@ -641,11 +479,11 @@ export interface TestRunAppComponentsOutput { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -661,188 +499,102 @@ export interface TestRunServerMetricConfigOutput { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: string; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: string; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfileOutput { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsOutput; - /** The creation datetime(RFC 3339 literal format). */ + /** The creation datetime(ISO 8601 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ + /** The last Modified datetime(ISO 8601 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurationsOutputParent { - kind: ResourceKindOutput; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurationsOutput - extends TargetResourceConfigurationsOutputParent { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record< - string, - FunctionFlexConsumptionResourceConfigurationOutput - >; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfigurationOutput { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRunOutput { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsOutput; - /** - * The test profile run status. - * - * Possible values: "ACCEPTED", "NOTSTARTED", "EXECUTING", "DONE", "CANCELLING", "CANCELLED", "FAILED" - */ - readonly status?: TestProfileRunStatusOutput; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: Array; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: string; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: string; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: Array; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: string; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: string; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetailOutput { - /** - * Status of the test run. - * - * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" - */ - status: StatusOutput; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendationOutput { - /** - * Category of the recommendation. - * - * Possible values: "ThroughputOptimized", "CostOptimized" - */ - category: RecommendationCategoryOutput; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export type TargetResourceConfigurationsOutput = - | TargetResourceConfigurationsOutputParent - | FunctionFlexConsumptionTargetResourceConfigurationsOutput; /** Alias for PFMetricsOutput */ -export type PFMetricsOutput = string; +export type PFMetricsOutput = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; /** Alias for PFAgFuncOutput */ -export type PFAgFuncOutput = string; +export type PFAgFuncOutput = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; /** Alias for PFActionOutput */ -export type PFActionOutput = string; +export type PFActionOutput = "continue" | "stop"; /** Alias for PFResultOutput */ -export type PFResultOutput = string; +export type PFResultOutput = "passed" | "undetermined" | "failed"; /** Alias for SecretTypeOutput */ -export type SecretTypeOutput = string; +export type SecretTypeOutput = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Alias for CertificateTypeOutput */ -export type CertificateTypeOutput = string; +export type CertificateTypeOutput = "AKV_CERT_URI"; /** Alias for FileTypeOutput */ -export type FileTypeOutput = string; +export type FileTypeOutput = + | "JMX_FILE" + | "USER_PROPERTIES" + | "ADDITIONAL_ARTIFACTS"; /** Alias for FileStatusOutput */ -export type FileStatusOutput = string; -/** Alias for TestKindOutput */ -export type TestKindOutput = string; -/** Paged collection of Test items */ +export type FileStatusOutput = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; +/** Collection of tests */ export type PagedTestOutput = Paged; -/** Paged collection of TestFileInfo items */ -export type PagedTestFileInfoOutput = Paged; +/** Collection of files. */ +export type PagedFileInfoOutput = Paged; /** Alias for PFTestResultOutput */ -export type PFTestResultOutput = string; +export type PFTestResultOutput = "PASSED" | "NOT_APPLICABLE" | "FAILED"; /** Alias for StatusOutput */ -export type StatusOutput = string; -/** Alias for RequestDataLevelOutput */ -export type RequestDataLevelOutput = string; -/** Paged collection of TestRun items */ +export type StatusOutput = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; +/** Collection of test runs */ export type PagedTestRunOutput = Paged; /** Alias for AggregationTypeOutput */ -export type AggregationTypeOutput = string; +export type AggregationTypeOutput = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile90" + | "Percentile95" + | "Percentile99"; /** Alias for MetricUnitOutput */ -export type MetricUnitOutput = string; +export type MetricUnitOutput = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; /** Alias for TimeGrainOutput */ -export type TimeGrainOutput = string; +export type TimeGrainOutput = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; /** The response to a metrics query. */ -export type MetricsOutput = Paged; -/** Alias for ResourceKindOutput */ -export type ResourceKindOutput = string; -/** Paged collection of TestProfile items */ -export type PagedTestProfileOutput = Paged; -/** Alias for TestProfileRunStatusOutput */ -export type TestProfileRunStatusOutput = string; -/** Alias for RecommendationCategoryOutput */ -export type RecommendationCategoryOutput = string; -/** Paged collection of TestProfileRun items */ -export type PagedTestProfileRunOutput = Paged; +export type PagedTimeSeriesElementOutput = Paged; +/** Paged collection of DimensionValueList items */ +export type PagedDimensionValueListOutput = Paged; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 72c1d3b8d0..9437426616 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -8,24 +8,21 @@ import { TestAppComponents, TestServerMetricConfig, TestRun, - TimeGrain, + Interval, MetricRequestPayload, TestRunAppComponents, TestRunServerMetricConfig, - TestProfile, - TestProfileRun, } from "./models.js"; -/** The resource instance. */ +/** Load test model */ export type TestResourceMergeAndPatch = Partial; export interface LoadTestAdministrationCreateOrUpdateTestBodyParam { - /** The resource instance. */ + /** Load test model */ body: TestResourceMergeAndPatch; } export interface LoadTestAdministrationCreateOrUpdateTestMediaTypesParam { - /** This request has a JSON Merge Patch body. */ contentType: "application/merge-patch+json"; } @@ -48,10 +45,16 @@ export interface LoadTestAdministrationListTestsQueryParamProperties { * the search parameter can be Login. */ search?: string; - /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedStartTime?: Date | string; - /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ - lastModifiedEndTime?: Date | string; + /** + * Start DateTime(ISO 8601 literal format) of the last updated time range to + * filter tests. + */ + lastModifiedStartTime?: string; + /** + * End DateTime(ISO 8601 literal format) of the last updated time range to filter + * tests. + */ + lastModifiedEndTime?: string; /** Number of results in response. */ maxpagesize?: number; } @@ -77,11 +80,7 @@ export interface LoadTestAdministrationUploadTestFileBodyParam { } export interface LoadTestAdministrationUploadTestFileQueryParamProperties { - /** - * File type - * - * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" - */ + /** File type */ fileType?: FileType; } @@ -90,7 +89,6 @@ export interface LoadTestAdministrationUploadTestFileQueryParam { } export interface LoadTestAdministrationUploadTestFileMediaTypesParam { - /** Content type. */ contentType: "application/octet-stream"; } @@ -111,7 +109,6 @@ export interface LoadTestAdministrationCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestAdministrationCreateOrUpdateAppComponentsMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -131,7 +128,6 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigBodyPara } export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -141,7 +137,7 @@ export type LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters = RequestParameters; export type LoadTestAdministrationGetServerMetricsConfigParameters = RequestParameters; -export type LoadTestRunGetTestRunParameters = RequestParameters; +export type LoadTestRunDeleteTestRunParameters = RequestParameters; /** The resource instance. */ export type TestRunResourceMergeAndPatch = Partial; @@ -174,7 +170,8 @@ export type LoadTestRunCreateOrUpdateTestRunParameters = LoadTestRunCreateOrUpdateTestRunMediaTypesParam & LoadTestRunCreateOrUpdateTestRunBodyParam & RequestParameters; -export type LoadTestRunDeleteTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunFileParameters = RequestParameters; export interface LoadTestRunListTestRunsQueryParamProperties { /** @@ -190,10 +187,10 @@ export interface LoadTestRunListTestRunsQueryParamProperties { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionFrom?: Date | string; - /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionTo?: Date | string; + /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionFrom?: string; + /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionTo?: string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -206,17 +203,16 @@ export interface LoadTestRunListTestRunsQueryParam { export type LoadTestRunListTestRunsParameters = LoadTestRunListTestRunsQueryParam & RequestParameters; -export type LoadTestRunGetTestRunFileParameters = RequestParameters; -export type LoadTestRunStopParameters = RequestParameters; +export type LoadTestRunStopTestRunParameters = RequestParameters; export type LoadTestRunListMetricNamespacesParameters = RequestParameters; export interface LoadTestRunListMetricDefinitionsQueryParamProperties { /** Metric namespace to query metric definitions for. */ - metricNamespace: string; + metricNamespace?: string; } export interface LoadTestRunListMetricDefinitionsQueryParam { - queryParameters: LoadTestRunListMetricDefinitionsQueryParamProperties; + queryParameters?: LoadTestRunListMetricDefinitionsQueryParamProperties; } export type LoadTestRunListMetricDefinitionsParameters = @@ -224,28 +220,27 @@ export type LoadTestRunListMetricDefinitionsParameters = export interface LoadTestRunListMetricsBodyParam { /** Metric dimension filter */ - body?: MetricRequestPayload; + body: MetricRequestPayload; } export interface LoadTestRunListMetricsQueryParamProperties { /** The aggregation */ aggregation?: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: Interval; /** Metric name */ - metricname: string; + metricName?: string; + /** Metric namespace to query metric definitions for. */ + metricNamespace?: string; /** - * The interval (i.e. timegrain) of the query. - * - * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. */ - interval?: TimeGrain; - /** Metric namespace to query metric definitions for. */ - metricNamespace: string; - /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ - timespan: string; + timespan?: string; } export interface LoadTestRunListMetricsQueryParam { - queryParameters: LoadTestRunListMetricsQueryParamProperties; + queryParameters?: LoadTestRunListMetricsQueryParamProperties; } export type LoadTestRunListMetricsParameters = @@ -254,18 +249,17 @@ export type LoadTestRunListMetricsParameters = RequestParameters; export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { + /** The interval (i.e. timegrain) of the query. */ + interval?: Interval; /** Metric name */ - metricname: string; - /** - * The interval (i.e. timegrain) of the query. - * - * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" - */ - interval?: TimeGrain; + metricName?: string; /** Metric namespace to query metric definitions for. */ metricNamespace: string; - /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ - timespan: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } export interface LoadTestRunListMetricDimensionValuesQueryParam { @@ -284,7 +278,6 @@ export interface LoadTestRunCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestRunCreateOrUpdateAppComponentsMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -303,7 +296,6 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam { } export interface LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam { - /** Content type. */ contentType: "application/merge-patch+json"; } @@ -311,97 +303,5 @@ export type LoadTestRunCreateOrUpdateServerMetricsConfigParameters = LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam & LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam & RequestParameters; -export type LoadTestRunGetServerMetricsConfigParameters = RequestParameters; -/** The resource instance. */ -export type TestProfileResourceMergeAndPatch = Partial; - -export interface TestProfileAdministrationCreateOrUpdateTestProfileBodyParam { - /** The resource instance. */ - body: TestProfileResourceMergeAndPatch; -} - -export interface TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type TestProfileAdministrationCreateOrUpdateTestProfileParameters = - TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam & - TestProfileAdministrationCreateOrUpdateTestProfileBodyParam & - RequestParameters; -export type TestProfileAdministrationDeleteTestProfileParameters = - RequestParameters; -export type TestProfileAdministrationGetTestProfileParameters = - RequestParameters; - -export interface TestProfileAdministrationListTestProfilesQueryParamProperties { - /** Maximum number of results to include in a single response. */ - maxpagesize?: number; - /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ - lastModifiedStartTime?: Date | string; - /** End DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ - lastModifiedEndTime?: Date | string; - /** Comma separated list of IDs of the test profiles to filter. */ - testProfileIds?: string; - /** Comma separated list IDs of the tests which should be associated with the test profiles to fetch. */ - testIds?: string; -} - -export interface TestProfileAdministrationListTestProfilesQueryParam { - queryParameters?: TestProfileAdministrationListTestProfilesQueryParamProperties; -} - -export type TestProfileAdministrationListTestProfilesParameters = - TestProfileAdministrationListTestProfilesQueryParam & RequestParameters; -export type TestProfileRunAdministrationGetTestProfileRunParameters = - RequestParameters; -/** The resource instance. */ -export type TestProfileRunResourceMergeAndPatch = Partial; - -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam { - /** The resource instance. */ - body: TestProfileRunResourceMergeAndPatch; -} - -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam { - /** This request has a JSON Merge Patch body. */ - contentType: "application/merge-patch+json"; -} - -export type TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters = - TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam & - TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam & - RequestParameters; -export type TestProfileRunAdministrationDeleteTestProfileRunParameters = +export type LoadTestRunTestRunListServerMetricsConfigParameters = RequestParameters; -export type TestProfileRunAdministrationStopParameters = RequestParameters; - -export interface TestProfileRunAdministrationListTestProfileRunsQueryParamProperties { - /** Maximum number of results to include in a single response. */ - maxpagesize?: number; - /** Minimum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ - minStartDateTime?: Date | string; - /** Maximum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ - maxStartDateTime?: Date | string; - /** Minimum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ - minEndDateTime?: Date | string; - /** Maximum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ - maxEndDateTime?: Date | string; - /** Start DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ - createdDateStartTime?: Date | string; - /** End DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ - createdDateEndTime?: Date | string; - /** Comma separated list of IDs of the test profile runs to filter. */ - testProfileRunIds?: string; - /** Comma separated IDs of the test profiles which should be associated with the test profile runs to fetch. */ - testProfileIds?: string; - /** Comma separated list of Statuses of the test profile runs to filter. */ - statuses?: string; -} - -export interface TestProfileRunAdministrationListTestProfileRunsQueryParam { - queryParameters?: TestProfileRunAdministrationListTestProfileRunsQueryParamProperties; -} - -export type TestProfileRunAdministrationListTestProfileRunsParameters = - TestProfileRunAdministrationListTestProfileRunsQueryParam & RequestParameters; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts new file mode 100644 index 0000000000..19a90195ba --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Client, HttpResponse } from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { + CancelOnProgress, + CreateHttpPollerOptions, + RunningOperation, + OperationResponse, + OperationState, + createHttpPoller, +} from "@azure/core-lro"; +import { + LoadTestRunCreateOrUpdateTestRun200Response, + LoadTestRunCreateOrUpdateTestRun201Response, + LoadTestRunCreateOrUpdateTestRunDefaultResponse, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, +} from "./responses.js"; + +/** + * A simple poller that can be used to poll a long running operation. + */ +export interface SimplePollerLike< + TState extends OperationState, + TResult, +> { + /** + * Returns true if the poller has finished polling. + */ + isDone(): boolean; + /** + * Returns the state of the operation. + */ + getOperationState(): TState; + /** + * Returns the result value of the operation, + * regardless of the state of the poller. + * It can return undefined or an incomplete form of the final TResult value + * depending on the implementation. + */ + getResult(): TResult | undefined; + /** + * Returns a promise that will resolve once a single polling request finishes. + * It does this by calling the update method of the Poller's operation. + */ + poll(options?: { abortSignal?: AbortSignalLike }): Promise; + /** + * Returns a promise that will resolve once the underlying operation is completed. + */ + pollUntilDone(pollOptions?: { + abortSignal?: AbortSignalLike; + }): Promise; + /** + * Invokes the provided callback after each polling is completed, + * sending the current state of the poller's operation. + * + * It returns a method that can be used to stop receiving updates on the given callback function. + */ + onProgress(callback: (state: TState) => void): CancelOnProgress; + + /** + * Returns a promise that could be used for serialized version of the poller's operation + * by invoking the operation's serialize method. + */ + serialize(): Promise; + + /** + * Wait the poller to be submitted. + */ + submitted(): Promise; + + /** + * Returns a string representation of the poller's operation. Similar to serialize but returns a string. + * @deprecated Use serialize() instead. + */ + toString(): string; + + /** + * Stops the poller from continuing to poll. Please note this will only stop the client-side polling + * @deprecated Use abortSignal to stop polling instead. + */ + stopPolling(): void; + + /** + * Returns true if the poller is stopped. + * @deprecated Use abortSignal status to track this instead. + */ + isStopped(): boolean; +} + +/** + * Helper function that builds a Poller object to help polling a long running operation. + * @param client - Client to use for sending the request to get additional pages. + * @param initialResponse - The initial response. + * @param options - Options to set a resume state or custom polling interval. + * @returns - A poller object to poll for operation state updates and eventually get the final response. + */ +export async function getLongRunningPoller< + TResult extends + | LoadTestRunCreateOrUpdateTestRunLogicalResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, +>( + client: Client, + initialResponse: + | LoadTestRunCreateOrUpdateTestRun200Response + | LoadTestRunCreateOrUpdateTestRun201Response + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, + options?: CreateHttpPollerOptions>, +): Promise, TResult>>; +export async function getLongRunningPoller( + client: Client, + initialResponse: TResult, + options: CreateHttpPollerOptions> = {}, +): Promise, TResult>> { + const abortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + // In the case of Rest Clients we are building the LRO poller object from a response that's the reason + // we are not triggering the initial request here, just extracting the information from the + // response we were provided. + return getLroResponse(initialResponse); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { abortSignal?: AbortSignalLike }, + ) => { + // This is the callback that is going to be called to poll the service + // to get the latest status. We use the client provided and the polling path + // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location + // depending on the lro pattern that the service implements. If non is provided we default to the initial path. + function abortListener(): void { + abortController.abort(); + } + const inputAbortSignal = pollOptions?.abortSignal; + const abortSignal = abortController.signal; + if (inputAbortSignal?.aborted) { + abortController.abort(); + } else if (!abortSignal.aborted) { + inputAbortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client + .pathUnchecked(path ?? initialResponse.request.url) + .get({ abortSignal }); + } finally { + inputAbortSignal?.removeEventListener("abort", abortListener); + } + const lroResponse = getLroResponse(response as TResult); + lroResponse.rawResponse.headers["x-ms-original-url"] = + initialResponse.request.url; + return lroResponse; + }, + }; + + options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; + const httpPoller = createHttpPoller(poller, options); + const simplePoller: SimplePollerLike, TResult> = { + isDone() { + return httpPoller.isDone; + }, + isStopped() { + return abortController.signal.aborted; + }, + getOperationState() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + return httpPoller.operationState; + }, + getResult() { + return httpPoller.result; + }, + toString() { + if (!httpPoller.operationState) { + throw new Error( + "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", + ); + } + return JSON.stringify({ + state: httpPoller.operationState, + }); + }, + stopPolling() { + abortController.abort(); + }, + onProgress: httpPoller.onProgress, + poll: httpPoller.poll, + pollUntilDone: httpPoller.pollUntilDone, + serialize: httpPoller.serialize, + submitted: httpPoller.submitted, + }; + return simplePoller; +} + +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResult, +): OperationResponse { + if (Number.isNaN(response.status)) { + throw new TypeError( + `Status code of the response is not a number. Value: ${response.status}`, + ); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index 65d9fbf613..2c79e0b52c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,23 +6,18 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - TestFileInfoOutput, - PagedTestFileInfoOutput, + FileInfoOutput, + PagedFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, - TestRunFileInfoOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, - MetricsOutput, - DimensionValueListOutput, + PagedTimeSeriesElementOutput, + PagedDimensionValueListOutput, TestRunAppComponentsOutput, TestRunServerMetricConfigOutput, - TestProfileOutput, - PagedTestProfileOutput, - TestProfileRunOutput, - PagedTestProfileRunOutput, } from "./outputModels.js"; /** The request has succeeded. */ @@ -111,7 +106,7 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: TestFileInfoOutput; + body: FileInfoOutput; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -130,7 +125,7 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: TestFileInfoOutput; + body: FileInfoOutput; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -167,7 +162,7 @@ export interface LoadTestAdministrationDeleteTestFileDefaultResponse export interface LoadTestAdministrationListTestFiles200Response extends HttpResponse { status: "200"; - body: PagedTestFileInfoOutput; + body: PagedFileInfoOutput; } export interface LoadTestAdministrationListTestFilesDefaultHeaders { @@ -276,21 +271,25 @@ export interface LoadTestAdministrationGetServerMetricsConfigDefaultResponse LoadTestAdministrationGetServerMetricsConfigDefaultHeaders; } -/** The request has succeeded. */ -export interface LoadTestRunGetTestRun200Response extends HttpResponse { - status: "200"; - body: TestRunOutput; +/** There is no content to send for this request, but the headers may be useful. */ +export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { + status: "204"; } -export interface LoadTestRunGetTestRunDefaultHeaders { +export interface LoadTestRunDeleteTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; +} + +export interface LoadTestRunCreateOrUpdateTestRun200Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; } /** The request has succeeded. */ @@ -298,6 +297,12 @@ export interface LoadTestRunCreateOrUpdateTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; + headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun200Headers; +} + +export interface LoadTestRunCreateOrUpdateTestRun201Headers { + /** The location for monitoring the operation state. */ + "operation-location": string; } /** The request has succeeded and a new resource has been created as a result. */ @@ -305,6 +310,7 @@ export interface LoadTestRunCreateOrUpdateTestRun201Response extends HttpResponse { status: "201"; body: TestRunOutput; + headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun201Headers; } export interface LoadTestRunCreateOrUpdateTestRunDefaultHeaders { @@ -319,71 +325,79 @@ export interface LoadTestRunCreateOrUpdateTestRunDefaultResponse headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRunDefaultHeaders; } -/** There is no content to send for this request, but the headers may be useful. */ -export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { - status: "204"; +/** The final response for long-running CreateOrUpdateTestRun operation */ +export interface LoadTestRunCreateOrUpdateTestRunLogicalResponse + extends HttpResponse { + status: "200"; + body: TestRunOutput; } -export interface LoadTestRunDeleteTestRunDefaultHeaders { +/** The request has succeeded. */ +export interface LoadTestRunGetTestRun200Response extends HttpResponse { + status: "200"; + body: TestRunOutput; +} + +export interface LoadTestRunGetTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunListTestRuns200Response extends HttpResponse { +export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: PagedTestRunOutput; + body: FileInfoOutput; } -export interface LoadTestRunListTestRunsDefaultHeaders { +export interface LoadTestRunGetTestRunFileDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { +export interface LoadTestRunListTestRuns200Response extends HttpResponse { status: "200"; - body: TestRunFileInfoOutput; + body: PagedTestRunOutput; } -export interface LoadTestRunGetTestRunFileDefaultHeaders { +export interface LoadTestRunListTestRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { +export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunStop200Response extends HttpResponse { +export interface LoadTestRunStopTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; } -export interface LoadTestRunStopDefaultHeaders { +export interface LoadTestRunStopTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunStopDefaultResponse extends HttpResponse { +export interface LoadTestRunStopTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunStopDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunStopTestRunDefaultHeaders; } /** The request has succeeded. */ @@ -427,7 +441,7 @@ export interface LoadTestRunListMetricDefinitionsDefaultResponse /** The request has succeeded. */ export interface LoadTestRunListMetrics200Response extends HttpResponse { status: "200"; - body: MetricsOutput; + body: PagedTimeSeriesElementOutput; } export interface LoadTestRunListMetricsDefaultHeaders { @@ -445,7 +459,7 @@ export interface LoadTestRunListMetricsDefaultResponse extends HttpResponse { export interface LoadTestRunListMetricDimensionValues200Response extends HttpResponse { status: "200"; - body: DimensionValueListOutput; + body: PagedDimensionValueListOutput; } export interface LoadTestRunListMetricDimensionValuesDefaultHeaders { @@ -533,211 +547,21 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse } /** The request has succeeded. */ -export interface LoadTestRunGetServerMetricsConfig200Response +export interface LoadTestRunTestRunListServerMetricsConfig200Response extends HttpResponse { status: "200"; body: TestRunServerMetricConfigOutput; } -export interface LoadTestRunGetServerMetricsConfigDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface LoadTestRunGetServerMetricsConfigDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetServerMetricsConfigDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileAdministrationCreateOrUpdateTestProfile200Response - extends HttpResponse { - status: "200"; - body: TestProfileOutput; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface TestProfileAdministrationCreateOrUpdateTestProfile201Response - extends HttpResponse { - status: "201"; - body: TestProfileOutput; -} - -export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface TestProfileAdministrationDeleteTestProfile204Response - extends HttpResponse { - status: "204"; -} - -export interface TestProfileAdministrationDeleteTestProfileDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileAdministrationDeleteTestProfileDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileAdministrationDeleteTestProfileDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileAdministrationGetTestProfile200Response - extends HttpResponse { - status: "200"; - body: TestProfileOutput; -} - -export interface TestProfileAdministrationGetTestProfileDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileAdministrationGetTestProfileDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileAdministrationGetTestProfileDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileAdministrationListTestProfiles200Response - extends HttpResponse { - status: "200"; - body: PagedTestProfileOutput; -} - -export interface TestProfileAdministrationListTestProfilesDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileAdministrationListTestProfilesDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileAdministrationListTestProfilesDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileRunAdministrationGetTestProfileRun200Response - extends HttpResponse { - status: "200"; - body: TestProfileRunOutput; -} - -export interface TestProfileRunAdministrationGetTestProfileRunDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileRunAdministrationGetTestProfileRunDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileRunAdministrationGetTestProfileRunDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response - extends HttpResponse { - status: "200"; - body: TestProfileRunOutput; -} - -/** The request has succeeded and a new resource has been created as a result. */ -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response - extends HttpResponse { - status: "201"; - body: TestProfileRunOutput; -} - -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders; -} - -/** There is no content to send for this request, but the headers may be useful. */ -export interface TestProfileRunAdministrationDeleteTestProfileRun204Response - extends HttpResponse { - status: "204"; -} - -export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & - TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileRunAdministrationStop200Response - extends HttpResponse { - status: "200"; - body: TestProfileRunOutput; -} - -export interface TestProfileRunAdministrationStopDefaultHeaders { - /** String error code indicating what went wrong. */ - "x-ms-error-code"?: string; -} - -export interface TestProfileRunAdministrationStopDefaultResponse - extends HttpResponse { - status: string; - body: ErrorResponse; - headers: RawHttpHeaders & TestProfileRunAdministrationStopDefaultHeaders; -} - -/** The request has succeeded. */ -export interface TestProfileRunAdministrationListTestProfileRuns200Response - extends HttpResponse { - status: "200"; - body: PagedTestProfileRunOutput; -} - -export interface TestProfileRunAdministrationListTestProfileRunsDefaultHeaders { +export interface LoadTestRunTestRunListServerMetricsConfigDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface TestProfileRunAdministrationListTestProfileRunsDefaultResponse +export interface LoadTestRunTestRunListServerMetricsConfigDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & - TestProfileRunAdministrationListTestProfileRunsDefaultHeaders; + LoadTestRunTestRunListServerMetricsConfigDefaultHeaders; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index 8e35dc0cd3..4822ef0017 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. export { - createOrUpdateTestRun, + testRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -15,10 +15,10 @@ export { listMetricNamespaces, listMetrics, listTestRuns, - stop, + stopTestRun, } from "./operations.js"; export { createTestRunOperations, - TestRunOperationsClientOptions, - LoadTestServiceContext, + TestRunOperationsClientOptionalParams, + AzureLoadTestingContext, } from "./testRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index ffd48f173b..728e5a3ad8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -1,17 +1,18 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { getLongRunningPoller } from "./pollingHelpers.js"; +import { PollerLike, OperationState } from "@azure/core-lro"; import { passFailCriteriaSerializer, - autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, dimensionFilterSerializer, + FileInfo, TestRun, - TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -19,13 +20,15 @@ import { MetricNamespaceCollection, MetricRequestPayload, TimeSeriesElement, - _Metrics, + _PagedDimensionValueList, _PagedTestRun, + _PagedTimeSeriesElement, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, + AzureLoadTestingContext as Client, LoadTestRunCreateOrUpdateAppComponents200Response, LoadTestRunCreateOrUpdateAppComponents201Response, LoadTestRunCreateOrUpdateAppComponentsDefaultResponse, @@ -35,12 +38,11 @@ import { LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, + LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunDeleteTestRun204Response, LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunGetAppComponents200Response, LoadTestRunGetAppComponentsDefaultResponse, - LoadTestRunGetServerMetricsConfig200Response, - LoadTestRunGetServerMetricsConfigDefaultResponse, LoadTestRunGetTestRun200Response, LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, @@ -55,9 +57,10 @@ import { LoadTestRunListMetricsDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStop200Response, - LoadTestRunStopDefaultResponse, - LoadTestServiceContext as Client, + LoadTestRunStopTestRun200Response, + LoadTestRunStopTestRunDefaultResponse, + LoadTestRunTestRunListServerMetricsConfig200Response, + LoadTestRunTestRunListServerMetricsConfigDefaultResponse, } from "../../rest/index.js"; import { StreamableMethod, @@ -66,7 +69,7 @@ import { } from "@azure-rest/core-client"; import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -79,18 +82,19 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "../models/options.js"; -export function _createOrUpdateTestRunSend( +export function _testRunSend( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunCreateOrUpdateTestRunLogicalResponse > { return context .path("/test-runs/{testRunId}", testRunId) @@ -100,56 +104,45 @@ export function _createOrUpdateTestRunSend( (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, body: { - passFailCriteria: !body.passFailCriteria - ? body.passFailCriteria - : passFailCriteriaSerializer(body.passFailCriteria), - autoStopCriteria: !body.autoStopCriteria - ? body.autoStopCriteria - : autoStopCriteriaSerializer(body.autoStopCriteria), - secrets: !body.secrets - ? body.secrets - : (serializeRecord(body.secrets as any, secretSerializer) as any), - certificate: !body.certificate - ? body.certificate - : certificateMetadataSerializer(body.certificate), - environmentVariables: !body.environmentVariables - ? body.environmentVariables - : (serializeRecord(body.environmentVariables as any) as any), - loadTestConfiguration: !body.loadTestConfiguration - ? body.loadTestConfiguration - : loadTestConfigurationSerializer(body.loadTestConfiguration), - displayName: body["displayName"], - testId: body["testId"], - description: body["description"], - requestDataLevel: body["requestDataLevel"], - debugLogsEnabled: body["debugLogsEnabled"], + passFailCriteria: !resource.passFailCriteria + ? resource.passFailCriteria + : passFailCriteriaSerializer(resource.passFailCriteria), + secrets: !resource.secrets + ? resource.secrets + : (serializeRecord(resource.secrets as any, secretSerializer) as any), + certificate: !resource.certificate + ? resource.certificate + : certificateMetadataSerializer(resource.certificate), + environmentVariables: !resource.environmentVariables + ? resource.environmentVariables + : (serializeRecord(resource.environmentVariables as any) as any), + loadTestConfiguration: !resource.loadTestConfiguration + ? resource.loadTestConfiguration + : loadTestConfigurationSerializer(resource.loadTestConfiguration), + displayName: resource["displayName"], + testId: resource["testId"], + description: resource["description"], }, }); } -export async function _createOrUpdateTestRunDeserialize( +export async function _testRunDeserialize( result: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunCreateOrUpdateTestRunLogicalResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); } + result = result as LoadTestRunCreateOrUpdateTestRunLogicalResponse; return { testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -166,7 +159,6 @@ export async function _createOrUpdateTestRunDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -182,14 +174,6 @@ export async function _createOrUpdateTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -203,18 +187,6 @@ export async function _createOrUpdateTestRunDeserialize( "duration" ], }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -226,22 +198,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -253,22 +220,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -280,22 +242,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -307,23 +264,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -333,34 +284,6 @@ export async function _createOrUpdateTestRunDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -372,13 +295,10 @@ export async function _createOrUpdateTestRunDeserialize( "additionalFileInfo" ].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -392,22 +312,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -419,22 +334,17 @@ export async function _createOrUpdateTestRunDeserialize( ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -442,49 +352,6 @@ export async function _createOrUpdateTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, }, }, testResult: result.body["testResult"], @@ -493,52 +360,32 @@ export async function _createOrUpdateTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create and start a new test run with the given test run Id. */ -export async function createOrUpdateTestRun( +/** Create and start a new test run with the given name. */ +export function testRun( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateTestRunSend( - context, - testRunId, - body, - options, - ); - return _createOrUpdateTestRunDeserialize(result); + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, +): PollerLike, TestRun> { + return getLongRunningPoller(context, _testRunDeserialize, { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _testRunSend(context, testRunId, resource, options), + }) as PollerLike, TestRun>; } export function _createOrUpdateAppComponentsSend( @@ -579,20 +426,14 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Add an app component to a test run by providing the resource Id, name and type. */ +/** Associate an app component (collection of azure resources) to a test run */ export async function createOrUpdateAppComponents( context: Client, testRunId: string, @@ -650,15 +491,9 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -705,7 +540,7 @@ export async function _deleteTestRunDeserialize( return; } -/** Delete an existing load test run by providing the testRunId. */ +/** Delete a test run by its name. */ export async function deleteTestRun( context: Client, testRunId: string, @@ -740,15 +575,9 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -771,8 +600,8 @@ export function _getServerMetricsConfigSend( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod< - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse > { return context .path("/test-runs/{testRunId}/server-metrics-config", testRunId) @@ -781,8 +610,8 @@ export function _getServerMetricsConfigSend( export async function _getServerMetricsConfigDeserialize( result: - | LoadTestRunGetServerMetricsConfig200Response - | LoadTestRunGetServerMetricsConfigDefaultResponse, + | LoadTestRunTestRunListServerMetricsConfig200Response + | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -791,20 +620,14 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get associated server metrics configuration for the given test run. */ +/** List server metrics configuration for the given test run. */ export async function getServerMetricsConfig( context: Client, testRunId: string, @@ -840,14 +663,6 @@ export async function _getTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -864,7 +679,6 @@ export async function _getTestRunDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -880,14 +694,6 @@ export async function _getTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -901,18 +707,6 @@ export async function _getTestRunDeserialize( "duration" ], }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -924,22 +718,17 @@ export async function _getTestRunDeserialize( ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -951,22 +740,17 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -978,22 +762,17 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -1005,23 +784,17 @@ export async function _getTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1031,34 +804,6 @@ export async function _getTestRunDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1070,13 +815,10 @@ export async function _getTestRunDeserialize( "additionalFileInfo" ].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1090,22 +832,17 @@ export async function _getTestRunDeserialize( ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1117,22 +854,17 @@ export async function _getTestRunDeserialize( ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1140,49 +872,6 @@ export async function _getTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, }, }, testResult: result.body["testResult"], @@ -1191,39 +880,20 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get test run details by test run Id. */ +/** Get test run details by name. */ export async function getTestRun( context: Client, testRunId: string, @@ -1251,19 +921,16 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - fileName: result.body["fileName"], url: result.body["url"], + fileName: result.body["fileName"], fileType: result.body["fileType"], - expireDateTime: - result.body["expireDateTime"] !== undefined - ? new Date(result.body["expireDateTime"]) - : undefined, + expireDateTime: result.body["expireDateTime"], validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -1275,7 +942,7 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _getTestRunFileSend( context, testRunId, @@ -1289,9 +956,7 @@ export function _listMetricDimensionValuesSend( context: Client, testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDimensionValues200Response @@ -1306,10 +971,10 @@ export function _listMetricDimensionValuesSend( .get({ ...operationOptionsToRequestParameters(options), queryParameters: { - metricname: metricname, interval: options?.interval, + metricName: options?.metricName, metricNamespace: metricNamespace, - timespan: timespan, + timespan: options?.timespan, }, }); } @@ -1318,44 +983,45 @@ export async function _listMetricDimensionValuesDeserialize( result: | LoadTestRunListMetricDimensionValues200Response | LoadTestRunListMetricDimensionValuesDefaultResponse, -): Promise { +): Promise<_PagedDimensionValueList> { if (isUnexpected(result)) { throw createRestError(result); } return { - name: result.body["name"], - value: result.body["value"], + value: result.body["value"].map((p) => { + return { value: p["value"] }; + }), nextLink: result.body["nextLink"], }; } /** List the dimension values for the given metric dimension name. */ -export async function listMetricDimensionValues( +export function listMetricDimensionValues( context: Client, testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMetricDimensionValuesSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testRunId, - name, - metricname, - metricNamespace, - timespan, - options, + () => + _listMetricDimensionValuesSend( + context, + testRunId, + name, + metricNamespace, + options, + ), + _listMetricDimensionValuesDeserialize, + { itemName: "value", nextLinkName: "nextLink" }, ); - return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( context: Client, testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response @@ -1365,7 +1031,7 @@ export function _listMetricDefinitionsSend( .path("/test-runs/{testRunId}/metric-definitions", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: metricNamespace }, + queryParameters: { metricNamespace: options?.metricNamespace }, }); } @@ -1408,15 +1074,9 @@ export async function _listMetricDefinitionsDeserialize( export async function listMetricDefinitions( context: Client, testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _listMetricDefinitionsSend( - context, - testRunId, - metricNamespace, - options, - ); + const result = await _listMetricDefinitionsSend(context, testRunId, options); return _listMetricDefinitionsDeserialize(result); } @@ -1462,10 +1122,7 @@ export async function listMetricNamespaces( export function _listMetricsSend( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse @@ -1476,20 +1133,17 @@ export function _listMetricsSend( ...operationOptionsToRequestParameters(options), queryParameters: { aggregation: options?.aggregation, - metricname: metricname, interval: options?.interval, - metricNamespace: metricNamespace, - timespan: timespan, + metricName: options?.metricName, + metricNamespace: options?.metricNamespace, + timespan: options?.timespan, + }, + body: { + filters: + body["filters"] === undefined + ? body["filters"] + : body["filters"].map(dimensionFilterSerializer), }, - body: - body === undefined - ? body - : { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map(dimensionFilterSerializer), - }, }); } @@ -1497,7 +1151,7 @@ export async function _listMetricsDeserialize( result: | LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse, -): Promise<_Metrics> { +): Promise<_PagedTimeSeriesElement> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1509,13 +1163,7 @@ export async function _listMetricsDeserialize( p["data"] === undefined ? p["data"] : p["data"].map((p) => { - return { - timestamp: - p["timestamp"] !== undefined - ? new Date(p["timestamp"]) - : undefined, - value: p["value"], - }; + return { timestamp: p["timestamp"], value: p["value"] }; }), dimensionValues: p["dimensionValues"] === undefined @@ -1533,24 +1181,12 @@ export async function _listMetricsDeserialize( export function listMetrics( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => - _listMetricsSend( - context, - testRunId, - metricname, - metricNamespace, - timespan, - body, - options, - ), + () => _listMetricsSend(context, testRunId, body, options), _listMetricsDeserialize, { itemName: "value", nextLinkName: "nextLink" }, ); @@ -1570,8 +1206,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom?.toISOString(), - executionTo: options?.executionTo?.toISOString(), + executionFrom: options?.executionFrom, + executionTo: options?.executionTo, status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1594,14 +1230,6 @@ export async function _listTestRunsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !p.autoStopCriteria - ? undefined - : { - autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], - errorRate: p.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1618,7 +1246,6 @@ export async function _listTestRunsDeserialize( return { message: p["message"] }; }), testRunStatistics: p["testRunStatistics"], - regionalStatistics: p["regionalStatistics"], loadTestConfiguration: !p.loadTestConfiguration ? undefined : { @@ -1633,14 +1260,6 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - p.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1654,18 +1273,6 @@ export async function _listTestRunsDeserialize( "duration" ], }, - regionalLoadTestConfig: - p.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? p.loadTestConfiguration?.["regionalLoadTestConfig"] - : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( - (p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }, - ), }, testArtifacts: !p.testArtifacts ? undefined @@ -1677,12 +1284,12 @@ export async function _listTestRunsDeserialize( ?.configFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileName" ], - url: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileType" @@ -1690,12 +1297,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1709,23 +1311,17 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1739,12 +1335,12 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileName" ], - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileType" @@ -1752,12 +1348,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1771,26 +1362,17 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.[ - "expireDateTime" - ], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1800,36 +1382,6 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - p.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.[ - "validationFailureDetails" - ], - }, additionalFileInfo: p.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1841,13 +1393,10 @@ export async function _listTestRunsDeserialize( "additionalFileInfo" ].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1861,12 +1410,12 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo ? undefined : { + url: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileName" ], - url: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileType" @@ -1874,12 +1423,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1893,13 +1437,13 @@ export async function _listTestRunsDeserialize( ?.logsFileInfo ? undefined : { + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" + ], fileName: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileName" ], - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], fileType: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileType" @@ -1907,12 +1451,7 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ], validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1922,56 +1461,6 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, - artifactsContainerInfo: !p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo - ? undefined - : { - url: p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.[ - "expireDateTime" - ], - ) - : undefined, - }, - reportFileInfo: !p.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "fileName" - ], - url: p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "fileType" - ], - expireDateTime: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "expireDateTime" - ] !== undefined - ? new Date( - p.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationStatus" - ], - validationFailureDetails: - p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ - "validationFailureDetails" - ], - }, }, }, testResult: p["testResult"], @@ -1980,34 +1469,15 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: - p["startDateTime"] !== undefined - ? new Date(p["startDateTime"]) - : undefined, - endDateTime: - p["endDateTime"] !== undefined - ? new Date(p["endDateTime"]) - : undefined, - executedDateTime: - p["executedDateTime"] !== undefined - ? new Date(p["executedDateTime"]) - : undefined, + startDateTime: p["startDateTime"], + endDateTime: p["endDateTime"], + executedDateTime: p["executedDateTime"], portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - kind: p["kind"], - requestDataLevel: p["requestDataLevel"], - debugLogsEnabled: p["debugLogsEnabled"], - publicIPDisabled: p["publicIPDisabled"], - createdDateTime: - p["createdDateTime"] !== undefined - ? new Date(p["createdDateTime"]) - : undefined, + createdDateTime: p["createdDateTime"], createdBy: p["createdBy"], - lastModifiedDateTime: - p["lastModifiedDateTime"] !== undefined - ? new Date(p["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: p["lastModifiedDateTime"], lastModifiedBy: p["lastModifiedBy"], }; }), @@ -2015,7 +1485,7 @@ export async function _listTestRunsDeserialize( }; } -/** Get all test runs for the given filters. */ +/** Get all test runs with given filters */ export function listTestRuns( context: Client, options: ListTestRunsOptionalParams = { requestOptions: {} }, @@ -2028,20 +1498,22 @@ export function listTestRuns( ); } -export function _stopSend( +export function _stopTestRunSend( context: Client, testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< - LoadTestRunStop200Response | LoadTestRunStopDefaultResponse + LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse > { return context .path("/test-runs/{testRunId}:stop", testRunId) .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopDeserialize( - result: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, +export async function _stopTestRunDeserialize( + result: + | LoadTestRunStopTestRun200Response + | LoadTestRunStopTestRunDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -2052,14 +1524,6 @@ export async function _stopDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, - autoStopCriteria: !result.body.autoStopCriteria - ? undefined - : { - autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], - errorRate: result.body.autoStopCriteria?.["errorRate"], - errorRateTimeWindowInSeconds: - result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], - }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -2076,7 +1540,6 @@ export async function _stopDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], - regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -2092,14 +1555,6 @@ export async function _stopDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], - requestsPerSecond: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "requestsPerSecond" - ], - maxResponseTimeInMs: - result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ - "maxResponseTimeInMs" - ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -2113,18 +1568,6 @@ export async function _stopDeserialize( "duration" ], }, - regionalLoadTestConfig: - result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === - undefined - ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] - : result.body.loadTestConfiguration?.[ - "regionalLoadTestConfig" - ].map((p) => { - return { - engineInstances: p["engineInstances"], - region: p["region"], - }; - }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -2136,22 +1579,17 @@ export async function _stopDeserialize( ?.configFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], - ) - : undefined, + ?.configFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -2163,22 +1601,17 @@ export async function _stopDeserialize( ?.testScriptFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], - ) - : undefined, + ?.testScriptFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -2190,22 +1623,17 @@ export async function _stopDeserialize( ?.userPropFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], - ) - : undefined, + ?.userPropFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -2217,23 +1645,17 @@ export async function _stopDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], - ) - : undefined, + ?.inputArtifactsZipFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -2243,34 +1665,6 @@ export async function _stopDeserialize( "validationFailureDetails" ], }, - urlTestConfigFileInfo: !result.body.testArtifacts - ?.inputArtifacts?.urlTestConfigFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileName"], - url: result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["url"], - fileType: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.inputArtifacts - ?.urlTestConfigFileInfo?.["validationFailureDetails"], - }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -2282,13 +1676,10 @@ export async function _stopDeserialize( "additionalFileInfo" ].map((p) => { return { - fileName: p["fileName"], url: p["url"], + fileName: p["fileName"], fileType: p["fileType"], - expireDateTime: - p["expireDateTime"] !== undefined - ? new Date(p["expireDateTime"]) - : undefined, + expireDateTime: p["expireDateTime"], validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -2302,22 +1693,17 @@ export async function _stopDeserialize( ?.resultFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], - ) - : undefined, + ?.resultFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -2329,22 +1715,17 @@ export async function _stopDeserialize( ?.logsFileInfo ? undefined : { + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], - ) - : undefined, + ?.logsFileInfo?.["expireDateTime"], validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -2352,49 +1733,6 @@ export async function _stopDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, - artifactsContainerInfo: !result.body.testArtifacts - ?.outputArtifacts?.artifactsContainerInfo - ? undefined - : { - url: result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["url"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"] !== - undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.artifactsContainerInfo?.["expireDateTime"], - ) - : undefined, - }, - reportFileInfo: !result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo - ? undefined - : { - fileName: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileName"], - url: result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["url"], - fileType: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["fileType"], - expireDateTime: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"] !== undefined - ? new Date( - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["expireDateTime"], - ) - : undefined, - validationStatus: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationStatus"], - validationFailureDetails: - result.body.testArtifacts?.outputArtifacts - ?.reportFileInfo?.["validationFailureDetails"], - }, }, }, testResult: result.body["testResult"], @@ -2403,44 +1741,25 @@ export async function _stopDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: - result.body["startDateTime"] !== undefined - ? new Date(result.body["startDateTime"]) - : undefined, - endDateTime: - result.body["endDateTime"] !== undefined - ? new Date(result.body["endDateTime"]) - : undefined, - executedDateTime: - result.body["executedDateTime"] !== undefined - ? new Date(result.body["executedDateTime"]) - : undefined, + startDateTime: result.body["startDateTime"], + endDateTime: result.body["endDateTime"], + executedDateTime: result.body["executedDateTime"], portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - kind: result.body["kind"], - requestDataLevel: result.body["requestDataLevel"], - debugLogsEnabled: result.body["debugLogsEnabled"], - publicIPDisabled: result.body["publicIPDisabled"], - createdDateTime: - result.body["createdDateTime"] !== undefined - ? new Date(result.body["createdDateTime"]) - : undefined, + createdDateTime: result.body["createdDateTime"], createdBy: result.body["createdBy"], - lastModifiedDateTime: - result.body["lastModifiedDateTime"] !== undefined - ? new Date(result.body["lastModifiedDateTime"]) - : undefined, + lastModifiedDateTime: result.body["lastModifiedDateTime"], lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Stop test run by test run Id. */ -export async function stop( +/** Stop test run by name. */ +export async function stopTestRun( context: Client, testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopSend(context, testRunId, options); - return _stopDeserialize(result); + const result = await _stopTestRunSend(context, testRunId, options); + return _stopTestRunDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts new file mode 100644 index 0000000000..d4d54d4e32 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + PollerLike, + OperationState, + ResourceLocationConfig, + RunningOperation, + createHttpPoller, + OperationResponse, +} from "@azure/core-lro"; + +import { + Client, + PathUncheckedResponse, + createRestError, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { isUnexpected } from "../../rest/index.js"; + +export interface GetLongRunningPollerOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * The potential location of the result of the LRO if specified by the LRO extension in the swagger. + */ + resourceLocationConfig?: ResourceLocationConfig; + /** + * The original url of the LRO + * Should not be null when restoreFrom is set + */ + initialRequestUrl?: string; + /** + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. + */ + restoreFrom?: string; + /** + * The function to get the initial response + */ + getInitialResponse?: () => PromiseLike; +} +export function getLongRunningPoller< + TResponse extends PathUncheckedResponse, + TResult = void, +>( + client: Client, + processResponseBody: (result: TResponse) => Promise, + options: GetLongRunningPollerOptions, +): PollerLike, TResult> { + const { restoreFrom, getInitialResponse } = options; + if (!restoreFrom && !getInitialResponse) { + throw new Error( + "Either restoreFrom or getInitialResponse must be specified", + ); + } + let initialResponse: TResponse | undefined = undefined; + const pollAbortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + if (!getInitialResponse) { + throw new Error( + "getInitialResponse is required when initializing a new poller", + ); + } + initialResponse = await getInitialResponse(); + return getLroResponse(initialResponse); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { + abortSignal?: AbortSignalLike; + }, + ) => { + // The poll request would both listen to the user provided abort signal and the poller's own abort signal + function abortListener(): void { + pollAbortController.abort(); + } + const abortSignal = pollAbortController.signal; + if (options.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (pollOptions?.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (!abortSignal.aborted) { + options.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + pollOptions?.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client.pathUnchecked(path).get({ abortSignal }); + } finally { + options.abortSignal?.removeEventListener("abort", abortListener); + pollOptions?.abortSignal?.removeEventListener("abort", abortListener); + } + if (options.initialRequestUrl || initialResponse) { + response.headers["x-ms-original-url"] = + options.initialRequestUrl ?? initialResponse!.request.url; + } + + return getLroResponse(response as TResponse); + }, + }; + return createHttpPoller(poller, { + intervalInMs: options?.updateIntervalInMs, + resourceLocationConfig: options?.resourceLocationConfig, + restoreFrom: options?.restoreFrom, + processResult: (result: unknown) => { + return processResponseBody(result as TResponse); + }, + }); +} +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @param deserializeFn - deserialize function to convert Rest response to modular output + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResponse, +): OperationResponse { + if (isUnexpected(response as PathUncheckedResponse)) { + throw createRestError(response); + } + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index 7e596e790f..8ed47fc3e2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -3,22 +3,22 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { LoadTestServiceContext } from "../../rest/index.js"; +import { AzureLoadTestingContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ -export interface TestRunOperationsClientOptions extends ClientOptions { +export interface TestRunOperationsClientOptionalParams extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; } -export { LoadTestServiceContext } from "../../rest/index.js"; +export { AzureLoadTestingContext } from "../../rest/index.js"; export function createTestRunOperations( endpointParam: string, credential: TokenCredential, - options: TestRunOperationsClientOptions = {}, -): LoadTestServiceContext { + options: TestRunOperationsClientOptionalParams = {}, +): AzureLoadTestingContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index 55924f8f49..03b74076da 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -3,38 +3,27 @@ export { TestRunOperationsClient, - TestRunOperationsClientOptions, + TestRunOperationsClientOptionalParams, } from "./testRunOperationsClient.js"; +export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Test, PassFailCriteria, PassFailMetric, - KnownPFMetrics, PFMetrics, - KnownPFAgFunc, PFAgFunc, - KnownPFAction, PFAction, - KnownPFResult, PFResult, - AutoStopCriteria, Secret, - KnownSecretType, SecretType, CertificateMetadata, - KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, - RegionalConfiguration, TestInputArtifacts, - TestFileInfo, - KnownFileType, + FileInfo, FileType, - KnownFileStatus, FileStatus, - KnownTestKind, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -45,28 +34,20 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, PFTestResult, - KnownStatus, Status, - KnownRequestDataLevel, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, - KnownAggregationType, AggregationType, - KnownMetricUnit, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -74,21 +55,7 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -101,7 +68,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index 5dd83b954e..cfa3ac60f4 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -5,32 +5,20 @@ export { Test, PassFailCriteria, PassFailMetric, - KnownPFMetrics, PFMetrics, - KnownPFAgFunc, PFAgFunc, - KnownPFAction, PFAction, - KnownPFResult, PFResult, - AutoStopCriteria, Secret, - KnownSecretType, SecretType, CertificateMetadata, - KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, - RegionalConfiguration, TestInputArtifacts, - TestFileInfo, - KnownFileType, + FileInfo, FileType, - KnownFileStatus, FileStatus, - KnownTestKind, - TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -41,28 +29,20 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, - TestRunFileInfo, TestRunOutputArtifacts, - ArtifactsContainerInfo, - KnownPFTestResult, PFTestResult, - KnownStatus, Status, - KnownRequestDataLevel, - RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - KnownTimeGrain, - TimeGrain, + Interval, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, - KnownAggregationType, AggregationType, - KnownMetricUnit, MetricUnit, MetricAvailability, + TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -70,23 +50,9 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestProfile, - TargetResourceConfigurations, - FunctionFlexConsumptionTargetResourceConfigurations, - FunctionFlexConsumptionResourceConfiguration, - KnownResourceKind, - ResourceKind, - TestProfileRun, - KnownTestProfileRunStatus, - TestProfileRunStatus, - TestRunDetail, - TestProfileRunRecommendation, - KnownRecommendationCategory, - RecommendationCategory, - TargetResourceConfigurationsUnion, } from "./models.js"; export { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -99,7 +65,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index b95c47ad79..3a7491a214 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -6,12 +6,10 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, - AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, - RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -21,19 +19,12 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, - TestProfile as TestProfileRest, - TargetResourceConfigurations as TargetResourceConfigurationsRest, - FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, - FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, - TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model. */ +/** Load test model */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -42,38 +33,32 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata. */ + /** Certificates metadata */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; - /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ - baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testId: string; + /** Unique test name as identifier. */ + readonly testId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; - /** Kind of test. */ - kind?: TestKind; - /** Inject load test engines without deploying public IP for outbound access */ - publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -83,9 +68,6 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -98,12 +80,9 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), - baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], - kind: item["kind"], - publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -134,7 +113,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -169,148 +148,28 @@ export function passFailMetricSerializer( }; } -/** Known values of {@link PFMetrics} that the service accepts. */ -export enum KnownPFMetrics { - /** response_time_ms */ - response_time_ms = "response_time_ms", - /** latency */ - latency = "latency", - /** error */ - error = "error", - /** requests */ - requests = "requests", - /** requests_per_sec */ - requests_per_sec = "requests_per_sec", -} - -/** - * Metrics for pass/fail criteria. \ - * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **response_time_ms** \ - * **latency** \ - * **error** \ - * **requests** \ - * **requests_per_sec** - */ -export type PFMetrics = string; - -/** Known values of {@link PFAgFunc} that the service accepts. */ -export enum KnownPFAgFunc { - /** count */ - count = "count", - /** percentage */ - percentage = "percentage", - /** avg */ - avg = "avg", - /** p50 */ - p50 = "p50", - /** p75 */ - p75 = "p75", - /** p90 */ - p90 = "p90", - /** p95 */ - p95 = "p95", - /** p96 */ - p96 = "p96", - /** p97 */ - p97 = "p97", - /** p98 */ - p98 = "p98", - /** p99 */ - p99 = "p99", - /** p99.9 */ - "p99.9" = "p99.9", - /** p99.99 */ - "p99.99" = "p99.99", - /** min */ - min = "min", - /** max */ - max = "max", -} - -/** - * Aggregation functions for pass/fail criteria. \ - * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **count** \ - * **percentage** \ - * **avg** \ - * **p50** \ - * **p75** \ - * **p90** \ - * **p95** \ - * **p96** \ - * **p97** \ - * **p98** \ - * **p99** \ - * **p99.9** \ - * **p99.99** \ - * **min** \ - * **max** - */ -export type PFAgFunc = string; - -/** Known values of {@link PFAction} that the service accepts. */ -export enum KnownPFAction { - /** continue */ - "continue" = "continue", - /** stop */ - stop = "stop", -} - -/** - * Action to take on failure of pass/fail criteria. \ - * {@link KnownPFAction} can be used interchangeably with PFAction, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **continue** \ - * **stop** - */ -export type PFAction = string; - -/** Known values of {@link PFResult} that the service accepts. */ -export enum KnownPFResult { - /** passed */ - passed = "passed", - /** undetermined */ - undetermined = "undetermined", - /** failed */ - failed = "failed", -} - -/** - * Pass/fail criteria result. \ - * {@link KnownPFResult} can be used interchangeably with PFResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **passed** \ - * **undetermined** \ - * **failed** - */ -export type PFResult = string; - -/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ -export interface AutoStopCriteria { - /** Whether auto-stop should be disabled. The default value is false. */ - autoStopDisabled?: boolean; - /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ - errorRate?: number; - /** Time window during which the error percentage should be evaluated in seconds. */ - errorRateTimeWindowInSeconds?: number; -} - -export function autoStopCriteriaSerializer( - item: AutoStopCriteria, -): AutoStopCriteriaRest { - return { - autoStopDisabled: item["autoStopDisabled"], - errorRate: item["errorRate"], - errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], - }; -} +/** Type of PFMetrics */ +export type PFMetrics = + | "response_time_ms" + | "latency" + | "error" + | "requests" + | "requests_per_sec"; +/** Type of PFAgFunc */ +export type PFAgFunc = + | "count" + | "percentage" + | "avg" + | "p50" + | "p90" + | "p95" + | "p99" + | "min" + | "max"; +/** Type of PFAction */ +export type PFAction = "continue" | "stop"; +/** Type of PFResult */ +export type PFResult = "passed" | "undetermined" | "failed"; /** Secret */ export interface Secret { @@ -327,23 +186,8 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Known values of {@link SecretType} that the service accepts. */ -export enum KnownSecretType { - /** AKV_SECRET_URI */ - AKV_SECRET_URI = "AKV_SECRET_URI", - /** SECRET_VALUE */ - SECRET_VALUE = "SECRET_VALUE", -} - -/** - * Types of secrets supported. \ - * {@link KnownSecretType} can be used interchangeably with SecretType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_SECRET_URI** \ - * **SECRET_VALUE** - */ -export type SecretType = string; +/** Type of SecretType */ +export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; /** Certificates metadata */ export interface CertificateMetadata { @@ -365,24 +209,15 @@ export function certificateMetadataSerializer( }; } -/** Known values of {@link CertificateType} that the service accepts. */ -export enum KnownCertificateType { - /** AKV_CERT_URI */ - AKV_CERT_URI = "AKV_CERT_URI", -} - -/** - * Types of certificates supported. \ - * {@link KnownCertificateType} can be used interchangeably with CertificateType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **AKV_CERT_URI** - */ -export type CertificateType = string; +/** Type of CertificateType */ +export type CertificateType = "AKV_CERT_URI"; -/** Configurations for the load test. */ +/** The load test configuration. */ export interface LoadTestConfiguration { - /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ + /** + * The number of engine instances to execute load test. Supported values are in + * range of 1-45. Required for creating a new test. + */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -396,10 +231,8 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Configuration for quick load test */ + /** Optional load test config */ optionalLoadTestConfig?: OptionalLoadTestConfig; - /** Region distribution configuration for the load test. */ - regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -412,26 +245,21 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), - regionalLoadTestConfig: - item["regionalLoadTestConfig"] === undefined - ? item["regionalLoadTestConfig"] - : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Configuration for quick load test */ +/** Optional load test config */ export interface OptionalLoadTestConfig { - /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ + /** + * Test URL. Provide the complete HTTP URL. For example, + * http://contoso-app.azurewebsites.net/login + */ endpointUrl?: string; - /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ - requestsPerSecond?: number; - /** Maximum response time in milliseconds of the API/endpoint. */ - maxResponseTimeInMs?: number; - /** No of concurrent virtual users. */ + /** No of concurrent virtual users */ virtualUsers?: number; - /** Ramp up time in seconds. */ + /** Ramp up time */ rampUpTime?: number; - /** Test run duration in seconds. */ + /** Test run duration */ duration?: number; } @@ -440,146 +268,53 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], - requestsPerSecond: item["requestsPerSecond"], - maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } -/** Region distribution configuration for the load test. */ -export interface RegionalConfiguration { - /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ - engineInstances: number; - /** - * Azure region name. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - region: string; -} - -export function regionalConfigurationSerializer( - item: RegionalConfiguration, -): RegionalConfigurationRest { - return { - engineInstances: item["engineInstances"], - region: item["region"], - }; -} - /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: TestFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestFileInfo[]; + readonly additionalFileInfo?: FileInfo[]; } -/** Test file info. */ -export interface TestFileInfo { - /** Name of the file. */ - fileName: string; +/** File info */ +export interface FileInfo { /** File URL. */ - readonly url?: string; + url?: string; + /** Name of the file. */ + fileName?: string; /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; + fileType?: FileType; + /** Expiry time of the file (ISO 8601 literal format) */ + expireDateTime?: string; /** Validation status of the file */ - readonly validationStatus?: FileStatus; + validationStatus?: FileStatus; /** Validation failure error details */ - readonly validationFailureDetails?: string; + validationFailureDetails?: string; } -/** Known values of {@link FileType} that the service accepts. */ -export enum KnownFileType { - /** JMX_FILE */ - JMX_FILE = "JMX_FILE", - /** USER_PROPERTIES */ - USER_PROPERTIES = "USER_PROPERTIES", - /** ADDITIONAL_ARTIFACTS */ - ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", - /** ZIPPED_ARTIFACTS */ - ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", - /** URL_TEST_CONFIG */ - URL_TEST_CONFIG = "URL_TEST_CONFIG", - /** TEST_SCRIPT */ - TEST_SCRIPT = "TEST_SCRIPT", -} +/** Type of FileType */ +export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +/** Type of FileStatus */ +export type FileStatus = + | "NOT_VALIDATED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE" + | "VALIDATION_INITIATED" + | "VALIDATION_NOT_REQUIRED"; -/** - * Types of file supported. \ - * {@link KnownFileType} can be used interchangeably with FileType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **JMX_FILE** \ - * **USER_PROPERTIES** \ - * **ADDITIONAL_ARTIFACTS** \ - * **ZIPPED_ARTIFACTS** \ - * **URL_TEST_CONFIG** \ - * **TEST_SCRIPT** - */ -export type FileType = string; - -/** Known values of {@link FileStatus} that the service accepts. */ -export enum KnownFileStatus { - /** NOT_VALIDATED */ - NOT_VALIDATED = "NOT_VALIDATED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", - /** VALIDATION_INITIATED */ - VALIDATION_INITIATED = "VALIDATION_INITIATED", - /** VALIDATION_NOT_REQUIRED */ - VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", -} - -/** - * File status. \ - * {@link KnownFileStatus} can be used interchangeably with FileStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NOT_VALIDATED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** \ - * **VALIDATION_INITIATED** \ - * **VALIDATION_NOT_REQUIRED** - */ -export type FileStatus = string; - -/** Known values of {@link TestKind} that the service accepts. */ -export enum KnownTestKind { - /** URL */ - URL = "URL", - /** JMX */ - JMX = "JMX", - /** Locust */ - Locust = "Locust", -} - -/** - * Test kind \ - * {@link KnownTestKind} can be used interchangeably with TestKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **URL** \ - * **JMX** \ - * **Locust** - */ -export type TestKind = string; - -/** Test app components */ +/** Test app component */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -589,12 +324,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -610,14 +345,20 @@ export function testAppComponentsSerializer( }; } -/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ +/** + * An Azure resource object (Refer azure generic resource model : + * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) + */ export interface AppComponent { - /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ - readonly resourceId: string; + /** + * fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} + */ + readonly resourceId?: string; /** Azure resource name, required while creating the app component. */ - resourceName: string; + resourceName?: string; /** Azure resource type, required while creating the app component. */ - resourceType: string; + resourceType?: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -646,13 +387,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + metrics?: Record; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -661,10 +402,9 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: serializeRecord( - item.metrics as any, - resourceMetricSerializer, - ) as any, + metrics: !item.metrics + ? item.metrics + : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), }; } @@ -706,21 +446,31 @@ export function resourceMetricSerializer( }; } -/** Azure Load Testing API versions. */ -export type APIVersions = - | "2022-11-01" - | "2023-04-01-preview" - | "2024-03-01-preview" - | "2024-05-01-preview"; +/** Collection of files. */ +export interface _PagedFileInfo { + /** The FileInfo items on this page */ + value: FileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Collection of tests */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Type of APIVersions */ +export type APIVersions = "2022-11-01"; /** Load test run model */ export interface TestRun { - /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + /** Unique test run name as identifier */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; - /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ - autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -735,18 +485,8 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** - * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. - * The sampler name is the same as the name mentioned in the test script. - * Sampler name "Total" represents the aggregated statistics of all the samplers. - */ + /** Test run statistics. */ readonly testRunStatistics?: Record; - /** - * Regional statistics. Key is the Azure region name and value is the test run statistics. - * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". - * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. - */ - readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -763,32 +503,24 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; + /** The test run start DateTime(ISO 8601 literal format). */ + readonly startDateTime?: string; + /** The test run end DateTime(ISO 8601 literal format). */ + readonly endDateTime?: string; /** Test run initiated time. */ - readonly executedDateTime?: Date; + readonly executedDateTime?: string; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** Type of test. */ - readonly kind?: TestKind; - /** Request data collection level for test run */ - requestDataLevel?: RequestDataLevel; - /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ - debugLogsEnabled?: boolean; - /** Inject load test engines without deploying public IP for outbound access */ - readonly publicIPDisabled?: boolean; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -798,9 +530,6 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), - autoStopCriteria: !item.autoStopCriteria - ? item.autoStopCriteria - : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -816,8 +545,6 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], - requestDataLevel: item["requestDataLevel"], - debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -851,18 +578,6 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; - /** 75 percentile response time. */ - readonly pct75ResTime?: number; - /** 96 percentile response time. */ - readonly pct96ResTime?: number; - /** 97 percentile response time. */ - readonly pct97ResTime?: number; - /** 98 percentile response time. */ - readonly pct98ResTime?: number; - /** 99.9 percentile response time. */ - readonly pct999ResTime?: number; - /** 99.99 percentile response time. */ - readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -882,153 +597,45 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: TestRunFileInfo; + configFileInfo?: FileInfo; /** File info */ - testScriptFileInfo?: TestRunFileInfo; + testScriptFileInfo?: FileInfo; /** File info */ - userPropFileInfo?: TestRunFileInfo; + userPropFileInfo?: FileInfo; /** File info */ - inputArtifactsZipFileInfo?: TestRunFileInfo; - /** The config json file for url based test */ - urlTestConfigFileInfo?: TestRunFileInfo; + inputArtifactsZipFileInfo?: FileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: TestRunFileInfo[]; -} - -/** Test run file info. */ -export interface TestRunFileInfo { - /** Name of the file. */ - fileName: string; - /** File URL. */ - readonly url?: string; - /** File type */ - readonly fileType?: FileType; - /** Expiry time of the file (RFC 3339 literal format) */ - readonly expireDateTime?: Date; - /** Validation status of the file */ - readonly validationStatus?: FileStatus; - /** Validation failure error details */ - readonly validationFailureDetails?: string; + readonly additionalFileInfo?: FileInfo[]; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: TestRunFileInfo; + resultFileInfo?: FileInfo; /** File info */ - logsFileInfo?: TestRunFileInfo; - /** The container for test run artifacts. */ - artifactsContainerInfo?: ArtifactsContainerInfo; - /** The report file for the test run. */ - reportFileInfo?: TestRunFileInfo; -} - -/** Artifacts container info. */ -export interface ArtifactsContainerInfo { - /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ - url?: string; - /** Expiry time of the container (RFC 3339 literal format) */ - expireDateTime?: Date; -} - -/** Known values of {@link PFTestResult} that the service accepts. */ -export enum KnownPFTestResult { - /** PASSED */ - PASSED = "PASSED", - /** NOT_APPLICABLE */ - NOT_APPLICABLE = "NOT_APPLICABLE", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test result based on pass/fail criteria. \ - * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PASSED** \ - * **NOT_APPLICABLE** \ - * **FAILED** - */ -export type PFTestResult = string; - -/** Known values of {@link Status} that the service accepts. */ -export enum KnownStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** PROVISIONING */ - PROVISIONING = "PROVISIONING", - /** PROVISIONED */ - PROVISIONED = "PROVISIONED", - /** CONFIGURING */ - CONFIGURING = "CONFIGURING", - /** CONFIGURED */ - CONFIGURED = "CONFIGURED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** EXECUTED */ - EXECUTED = "EXECUTED", - /** DEPROVISIONING */ - DEPROVISIONING = "DEPROVISIONING", - /** DEPROVISIONED */ - DEPROVISIONED = "DEPROVISIONED", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", - /** VALIDATION_SUCCESS */ - VALIDATION_SUCCESS = "VALIDATION_SUCCESS", - /** VALIDATION_FAILURE */ - VALIDATION_FAILURE = "VALIDATION_FAILURE", -} - -/** - * Test run status. \ - * {@link KnownStatus} can be used interchangeably with Status, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **PROVISIONING** \ - * **PROVISIONED** \ - * **CONFIGURING** \ - * **CONFIGURED** \ - * **EXECUTING** \ - * **EXECUTED** \ - * **DEPROVISIONING** \ - * **DEPROVISIONED** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** \ - * **VALIDATION_SUCCESS** \ - * **VALIDATION_FAILURE** - */ -export type Status = string; - -/** Known values of {@link RequestDataLevel} that the service accepts. */ -export enum KnownRequestDataLevel { - /** NONE */ - NONE = "NONE", - /** ERRORS */ - ERRORS = "ERRORS", -} - -/** - * Request data collection level for test run \ - * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NONE** \ - * **ERRORS** - */ -export type RequestDataLevel = string; + logsFileInfo?: FileInfo; +} + +/** Type of PFTestResult */ +export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +/** Type of Status */ +export type Status = + | "ACCEPTED" + | "NOTSTARTED" + | "PROVISIONING" + | "PROVISIONED" + | "CONFIGURING" + | "CONFIGURED" + | "EXECUTING" + | "EXECUTED" + | "DEPROVISIONING" + | "DEPROVISIONED" + | "DONE" + | "CANCELLING" + | "CANCELLED" + | "FAILED" + | "VALIDATION_SUCCESS" + | "VALIDATION_FAILURE"; /** Test run app component */ export interface TestRunAppComponents { @@ -1040,12 +647,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -1071,12 +678,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; + /** The creation datetime(ISO 8601 literal format). */ + readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; + /** The last Modified datetime(ISO 8601 literal format). */ + readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -1091,41 +698,11 @@ export function testRunServerMetricConfigSerializer( }; } -/** Known values of {@link TimeGrain} that the service accepts. */ -export enum KnownTimeGrain { - /** PT5S */ - PT5S = "PT5S", - /** PT10S */ - PT10S = "PT10S", - /** PT1M */ - PT1M = "PT1M", - /** PT5M */ - PT5M = "PT5M", - /** PT1H */ - PT1H = "PT1H", -} - -/** - * Time Grain \ - * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **PT5S** \ - * **PT10S** \ - * **PT1M** \ - * **PT5M** \ - * **PT1H** - */ -export type TimeGrain = string; +/** Type of Interval */ +export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; -/** Metrics dimension values. */ export interface DimensionValueList { - /** The dimension name */ - readonly name?: string; - /** The dimension value */ - value?: string[]; - /** Link for the next set of values in case of paginated results, if applicable. */ - nextLink?: string; + value: string[]; } /** Represents collection of metric definitions. */ @@ -1165,92 +742,25 @@ export interface NameAndDesc { name?: string; } -/** Known values of {@link AggregationType} that the service accepts. */ -export enum KnownAggregationType { - /** Average */ - Average = "Average", - /** Count */ - Count = "Count", - /** None */ - None = "None", - /** Total */ - Total = "Total", - /** Percentile75 */ - Percentile75 = "Percentile75", - /** Percentile90 */ - Percentile90 = "Percentile90", - /** Percentile95 */ - Percentile95 = "Percentile95", - /** Percentile96 */ - Percentile96 = "Percentile96", - /** Percentile97 */ - Percentile97 = "Percentile97", - /** Percentile98 */ - Percentile98 = "Percentile98", - /** Percentile99 */ - Percentile99 = "Percentile99", - /** Percentile999 */ - Percentile999 = "Percentile999", - /** Percentile9999 */ - Percentile9999 = "Percentile9999", -} - -/** - * Aggregation type. \ - * {@link KnownAggregationType} can be used interchangeably with AggregationType, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **Average** \ - * **Count** \ - * **None** \ - * **Total** \ - * **Percentile75** \ - * **Percentile90** \ - * **Percentile95** \ - * **Percentile96** \ - * **Percentile97** \ - * **Percentile98** \ - * **Percentile99** \ - * **Percentile999** \ - * **Percentile9999** - */ -export type AggregationType = string; - -/** Known values of {@link MetricUnit} that the service accepts. */ -export enum KnownMetricUnit { - /** NotSpecified */ - NotSpecified = "NotSpecified", - /** Percent */ - Percent = "Percent", - /** Count */ - Count = "Count", - /** Seconds */ - Seconds = "Seconds", - /** Milliseconds */ - Milliseconds = "Milliseconds", - /** Bytes */ - Bytes = "Bytes", - /** BytesPerSecond */ - BytesPerSecond = "BytesPerSecond", - /** CountPerSecond */ - CountPerSecond = "CountPerSecond", -} - -/** - * Metric unit. \ - * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **NotSpecified** \ - * **Percent** \ - * **Count** \ - * **Seconds** \ - * **Milliseconds** \ - * **Bytes** \ - * **BytesPerSecond** \ - * **CountPerSecond** - */ -export type MetricUnit = string; +/** Type of AggregationType */ +export type AggregationType = + | "Average" + | "Count" + | "None" + | "Total" + | "Percentile90" + | "Percentile95" + | "Percentile99"; +/** Type of MetricUnit */ +export type MetricUnit = + | "NotSpecified" + | "Percent" + | "Count" + | "Seconds" + | "Milliseconds" + | "Bytes" + | "BytesPerSecond" + | "CountPerSecond"; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -1261,6 +771,9 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } +/** Type of TimeGrain */ +export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; + /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -1275,7 +788,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric. */ +/** Filters to fetch the set of metric */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -1315,7 +828,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _Metrics { +export interface _PagedTimeSeriesElement { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -1332,8 +845,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in RFC 3339 format. */ - timestamp?: Date; + /** The timestamp for the metric value in ISO 8601 format. */ + timestamp?: string; /** The metric value. */ value?: number; } @@ -1346,267 +859,7 @@ export interface DimensionValue { value?: string; } -/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ -export interface TestProfile { - /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileId: string; - /** Display name of the test profile. */ - displayName?: string; - /** Description for the test profile. */ - description?: string; - /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ - testId?: string; - /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ - targetResourceId?: string; - /** Configurations of the target resource on which testing would be done. */ - targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileSerializer(item: TestProfile): TestProfileRest { - return { - displayName: item["displayName"], - description: item["description"], - testId: item["testId"], - targetResourceId: item["targetResourceId"], - targetResourceConfigurations: !item.targetResourceConfigurations - ? item.targetResourceConfigurations - : targetResourceConfigurationsUnionSerializer( - item.targetResourceConfigurations, - ), - }; -} - -/** Configurations of a target resource. This varies with the kind of resource. */ -export interface TargetResourceConfigurations { - /** the discriminator possible values: FunctionsFlexConsumption */ - kind: ResourceKind; -} - -export function targetResourceConfigurationsUnionSerializer( - item: TargetResourceConfigurationsUnion, -) { - switch (item.kind) { - case "FunctionsFlexConsumption": - return functionFlexConsumptionTargetResourceConfigurationsSerializer( - item as FunctionFlexConsumptionTargetResourceConfigurations, - ); - - default: - return targetResourceConfigurationsSerializer(item); - } -} - -export function targetResourceConfigurationsSerializer( - item: TargetResourceConfigurationsUnion, -): TargetResourceConfigurationsRest { - return { - kind: item["kind"], - }; -} - -/** Configurations for a Function App using Flex Consumption Plan. */ -export interface FunctionFlexConsumptionTargetResourceConfigurations - extends TargetResourceConfigurations { - /** - * The kind value to use when providing configuration. - * This should typically be not changed from its value. - */ - kind: "FunctionsFlexConsumption"; - /** A map of configurations for a Function app using Flex Consumption Plan. */ - configurations?: Record; -} - -export function functionFlexConsumptionTargetResourceConfigurationsSerializer( - item: FunctionFlexConsumptionTargetResourceConfigurations, -): FunctionFlexConsumptionTargetResourceConfigurationsRest { - return { - kind: item["kind"], - configurations: !item.configurations - ? item.configurations - : (serializeRecord( - item.configurations as any, - functionFlexConsumptionResourceConfigurationSerializer, - ) as any), - }; -} - -/** Resource configuration instance for a Flex Consumption based Azure Function App. */ -export interface FunctionFlexConsumptionResourceConfiguration { - /** Memory size of the instance. Supported values are 2048, 4096. */ - instanceMemoryMB: number; - /** HTTP Concurrency for the function app. */ - httpConcurrency: number; -} - -export function functionFlexConsumptionResourceConfigurationSerializer( - item: FunctionFlexConsumptionResourceConfiguration, -): FunctionFlexConsumptionResourceConfigurationRest { - return { - instanceMemoryMB: item["instanceMemoryMB"], - httpConcurrency: item["httpConcurrency"], - }; -} - -/** Known values of {@link ResourceKind} that the service accepts. */ -export enum KnownResourceKind { - /** FunctionsFlexConsumption */ - FunctionsFlexConsumption = "FunctionsFlexConsumption", -} - -/** - * Kind of the resource on which test profile is created. \ - * {@link KnownResourceKind} can be used interchangeably with ResourceKind, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **FunctionsFlexConsumption** - */ -export type ResourceKind = string; - -/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ -export interface TestProfileRun { - /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ - readonly testProfileRunId: string; - /** Display name for the test profile run. */ - displayName?: string; - /** The test profile run description */ - description?: string; - /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ - testProfileId?: string; - /** Target resource ID on which the test profile run is created */ - readonly targetResourceId?: string; - /** Configurations of the target resource on which the test profile ran. */ - readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; - /** The test profile run status. */ - readonly status?: TestProfileRunStatus; - /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ - readonly errorDetails?: ErrorDetails[]; - /** The test profile run start DateTime(RFC 3339 literal format). */ - readonly startDateTime?: Date; - /** The test profile run end DateTime(RFC 3339 literal format). */ - readonly endDateTime?: Date; - /** Test profile run duration in seconds. */ - readonly durationInSeconds?: number; - /** - * Details of the test runs ran as part of the test profile run. - * Key is the testRunId of the corresponding testRun. - */ - readonly testRunDetails?: Record; - /** Recommendations provided based on a successful test profile run. */ - readonly recommendations?: TestProfileRunRecommendation[]; - /** The creation datetime(RFC 3339 literal format). */ - readonly createdDateTime?: Date; - /** The user that created. */ - readonly createdBy?: string; - /** The last Modified datetime(RFC 3339 literal format). */ - readonly lastModifiedDateTime?: Date; - /** The user that last modified. */ - readonly lastModifiedBy?: string; -} - -export function testProfileRunSerializer( - item: TestProfileRun, -): TestProfileRunRest { - return { - displayName: item["displayName"], - description: item["description"], - testProfileId: item["testProfileId"], - }; -} - -/** Known values of {@link TestProfileRunStatus} that the service accepts. */ -export enum KnownTestProfileRunStatus { - /** ACCEPTED */ - ACCEPTED = "ACCEPTED", - /** NOTSTARTED */ - NOTSTARTED = "NOTSTARTED", - /** EXECUTING */ - EXECUTING = "EXECUTING", - /** DONE */ - DONE = "DONE", - /** CANCELLING */ - CANCELLING = "CANCELLING", - /** CANCELLED */ - CANCELLED = "CANCELLED", - /** FAILED */ - FAILED = "FAILED", -} - -/** - * Test profile run status. \ - * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ACCEPTED** \ - * **NOTSTARTED** \ - * **EXECUTING** \ - * **DONE** \ - * **CANCELLING** \ - * **CANCELLED** \ - * **FAILED** - */ -export type TestProfileRunStatus = string; - -/** Details of a particular test run for a test profile run. */ -export interface TestRunDetail { - /** Status of the test run. */ - status: Status; - /** ID of the configuration on which the test ran. */ - configurationId: string; - /** Key value pair of extra properties associated with the test run. */ - properties: Record; -} - -/** A recommendation object that provides a list of configuration that optimizes its category. */ -export interface TestProfileRunRecommendation { - /** Category of the recommendation. */ - category: RecommendationCategory; - /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ - configurations?: string[]; -} - -/** Known values of {@link RecommendationCategory} that the service accepts. */ -export enum KnownRecommendationCategory { - /** ThroughputOptimized */ - ThroughputOptimized = "ThroughputOptimized", - /** CostOptimized */ - CostOptimized = "CostOptimized", -} - -/** - * Category of Recommendation. \ - * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, - * this enum contains the known values that the service supports. - * ### Known values supported by the service - * **ThroughputOptimized** \ - * **CostOptimized** - */ -export type RecommendationCategory = string; - -/** Paged collection of TestFileInfo items */ -export interface _PagedTestFileInfo { - /** The TestFileInfo items on this page */ - value: TestFileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of Test items */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestRun items */ +/** Collection of test runs */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -1614,23 +867,10 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of TestProfile items */ -export interface _PagedTestProfile { - /** The TestProfile items on this page */ - value: TestProfile[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Paged collection of TestProfileRun items */ -export interface _PagedTestProfileRun { - /** The TestProfileRun items on this page */ - value: TestProfileRun[]; +/** Paged collection of DimensionValueList items */ +export interface _PagedDimensionValueList { + /** The DimensionValueList items on this page */ + value: DimensionValueList[]; /** The link to the next page of items */ nextLink?: string; } - -/** Alias for TargetResourceConfigurationsUnion */ -export type TargetResourceConfigurationsUnion = - | FunctionFlexConsumptionTargetResourceConfigurations - | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index b7d2fc2c49..965a8a192f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -2,10 +2,12 @@ // Licensed under the MIT license. import { OperationOptions } from "@azure-rest/core-client"; -import { TimeGrain } from "./models.js"; +import { Interval } from "./models.js"; /** Optional parameters. */ -export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { +export interface TestRunOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; /** This request has a JSON Merge Patch body. */ contentType?: string; /** @@ -20,14 +22,12 @@ export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - /** Content type. */ contentType?: string; } @@ -51,11 +51,21 @@ export interface GetTestRunFileOptionalParams extends OperationOptions {} export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } /** Optional parameters. */ -export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} +export interface ListMetricDefinitionsOptionalParams extends OperationOptions { + /** Metric namespace to query metric definitions for. */ + metricNamespace?: string; +} /** Optional parameters. */ export interface ListMetricNamespacesOptionalParams extends OperationOptions {} @@ -65,7 +75,16 @@ export interface ListMetricsOptionalParams extends OperationOptions { /** The aggregation */ aggregation?: string; /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; + interval?: Interval; + /** Metric name */ + metricName?: string; + /** Metric namespace to query metric definitions for. */ + metricNamespace?: string; + /** + * The timespan of the query. It is a string with the following format + * 'startDateTime_ISO/endDateTime_ISO'. + */ + timespan?: string; } /** Optional parameters. */ @@ -83,10 +102,10 @@ export interface ListTestRunsOptionalParams extends OperationOptions { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionFrom?: Date; - /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionTo?: Date; + /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionFrom?: string; + /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ + executionTo?: string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -94,4 +113,4 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopOptionalParams extends OperationOptions {} +export interface StopTestRunOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts new file mode 100644 index 0000000000..a96372d9f9 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + PollerLike, + OperationState, + deserializeState, + ResourceLocationConfig, +} from "@azure/core-lro"; +import { TestRunOperationsClient } from "./testRunOperationsClient.js"; +import { getLongRunningPoller } from "./api/pollingHelpers.js"; +import { _testRunDeserialize } from "./api/operations.js"; +import { + PathUncheckedResponse, + OperationOptions, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; + +export interface RestorePollerOptions< + TResult, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +> extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** Deserialization function for raw response body */ + processResponseBody?: (result: TResponse) => Promise; +} + +/** + * Creates a poller from the serialized state of another poller. This can be + * useful when you want to create pollers on a different host or a poller + * needs to be constructed after the original one is not in scope. + */ +export function restorePoller( + client: TestRunOperationsClient, + serializedState: string, + sourceOperation: ( + ...args: any[] + ) => PollerLike, TResult>, + options?: RestorePollerOptions, +): PollerLike, TResult> { + const pollerConfig = deserializeState(serializedState).config; + const { initialRequestUrl, requestMethod, metadata } = pollerConfig; + if (!initialRequestUrl || !requestMethod) { + throw new Error( + `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, + ); + } + const resourceLocationConfig = metadata?.["resourceLocationConfig"] as + | ResourceLocationConfig + | undefined; + const deserializeHelper = + options?.processResponseBody ?? + getDeserializationHelper(initialRequestUrl, requestMethod); + if (!deserializeHelper) { + throw new Error( + `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, + ); + } + return getLongRunningPoller( + (client as any)["_client"] ?? client, + deserializeHelper as (result: TResponse) => Promise, + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + resourceLocationConfig, + restoreFrom: serializedState, + initialRequestUrl, + }, + ); +} + +const deserializeMap: Record = { + "PATCH /test-runs/{testRunId}": _testRunDeserialize, +}; + +function getDeserializationHelper( + urlStr: string, + method: string, +): ((result: unknown) => Promise) | undefined { + const path = new URL(urlStr).pathname; + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: ((result: unknown) => Promise) | undefined; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(deserializeMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value as (result: unknown) => Promise; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index a3b32aa2f3..89148e5863 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { PollerLike, OperationState } from "@azure/core-lro"; import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { + FileInfo, TestRun, - TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -15,7 +16,7 @@ import { TimeSeriesElement, } from "./models/models.js"; import { - CreateOrUpdateTestRunOptionalParams, + TestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -28,11 +29,11 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopOptionalParams, + StopTestRunOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { - createOrUpdateTestRun, + testRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -45,23 +46,23 @@ import { listMetricNamespaces, listMetrics, listTestRuns, - stop, + stopTestRun, createTestRunOperations, - TestRunOperationsClientOptions, - LoadTestServiceContext, + TestRunOperationsClientOptionalParams, + AzureLoadTestingContext, } from "./api/index.js"; -export { TestRunOperationsClientOptions } from "./api/testRunOperationsContext.js"; +export { TestRunOperationsClientOptionalParams } from "./api/testRunOperationsContext.js"; export class TestRunOperationsClient { - private _client: LoadTestServiceContext; + private _client: AzureLoadTestingContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; constructor( endpointParam: string, credential: TokenCredential, - options: TestRunOperationsClientOptions = {}, + options: TestRunOperationsClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -75,16 +76,16 @@ export class TestRunOperationsClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given test run Id. */ - createOrUpdateTestRun( + /** Create and start a new test run with the given name. */ + testRun( testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateTestRun(this._client, testRunId, body, options); + resource: TestRun, + options: TestRunOptionalParams = { requestOptions: {} }, + ): PollerLike, TestRun> { + return testRun(this._client, testRunId, resource, options); } - /** Add an app component to a test run by providing the resource Id, name and type. */ + /** Associate an app component (collection of azure resources) to a test run */ createOrUpdateAppComponents( testRunId: string, body: TestRunAppComponents, @@ -109,7 +110,7 @@ export class TestRunOperationsClient { ); } - /** Delete an existing load test run by providing the testRunId. */ + /** Delete a test run by its name. */ deleteTestRun( testRunId: string, options: DeleteTestRunOptionalParams = { requestOptions: {} }, @@ -128,7 +129,7 @@ export class TestRunOperationsClient { return getAppComponents(this._client, testRunId, options); } - /** Get associated server metrics configuration for the given test run. */ + /** List server metrics configuration for the given test run. */ getServerMetricsConfig( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, @@ -136,7 +137,7 @@ export class TestRunOperationsClient { return getServerMetricsConfig(this._client, testRunId, options); } - /** Get test run details by test run Id. */ + /** Get test run details by name. */ getTestRun( testRunId: string, options: GetTestRunOptionalParams = { requestOptions: {} }, @@ -149,7 +150,7 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -157,18 +158,14 @@ export class TestRunOperationsClient { listMetricDimensionValues( testRunId: string, name: string, - metricname: string, metricNamespace: string, - timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, - ): Promise { + ): PagedAsyncIterableIterator { return listMetricDimensionValues( this._client, testRunId, name, - metricname, metricNamespace, - timespan, options, ); } @@ -176,15 +173,9 @@ export class TestRunOperationsClient { /** List the metric definitions for a load test run. */ listMetricDefinitions( testRunId: string, - metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - return listMetricDefinitions( - this._client, - testRunId, - metricNamespace, - options, - ); + return listMetricDefinitions(this._client, testRunId, options); } /** List the metric namespaces for a load test run. */ @@ -198,35 +189,24 @@ export class TestRunOperationsClient { /** List the metric values for a load test run. */ listMetrics( testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - body?: MetricRequestPayload, + body: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { - return listMetrics( - this._client, - testRunId, - metricname, - metricNamespace, - timespan, - body, - options, - ); + return listMetrics(this._client, testRunId, body, options); } - /** Get all test runs for the given filters. */ + /** Get all test runs with given filters */ listTestRuns( options: ListTestRunsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } - /** Stop test run by test run Id. */ - stop( + /** Stop test run by name. */ + stopTestRun( testRunId: string, - options: StopOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - return stop(this._client, testRunId, options); + return stopTestRun(this._client, testRunId, options); } } From 9b91df15a073a8195635d38c338b3018d16f288c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 16 Jul 2024 19:56:51 +0800 Subject: [PATCH 17/18] update to the latest one --- .../typespec-ts/review/load-testing.api.md | 8 +- .../administrationOperationsClient.ts | 24 +- .../api/administrationOperationsContext.ts | 6 +- .../src/administrationOperations/api/index.ts | 2 +- .../api/operations.ts | 479 +++++-- .../src/administrationOperations/index.ts | 40 +- .../administrationOperations/models/index.ts | 40 +- .../administrationOperations/models/models.ts | 1154 ++++++++++++++--- .../models/options.ts | 18 +- .../generated/typespec-ts/src/index.ts | 279 +++- .../src/rest/azureLoadTestingClient.ts | 73 -- .../typespec-ts/src/rest/clientDefinitions.ts | 243 +++- .../generated/typespec-ts/src/rest/index.ts | 7 +- .../typespec-ts/src/rest/isUnexpected.ts | 194 ++- .../generated/typespec-ts/src/rest/models.ts | 329 +++-- .../typespec-ts/src/rest/outputModels.ts | 560 +++++--- .../typespec-ts/src/rest/parameters.ts | 186 ++- .../typespec-ts/src/rest/pollingHelper.ts | 223 ---- .../typespec-ts/src/rest/responses.ts | 294 ++++- .../api/index.ts | 2 +- ...tProfileAdministrationOperationsContext.ts | 4 +- .../index.ts | 2 +- ...stProfileAdministrationOperationsClient.ts | 6 +- .../src/testProfileRunOperations/api/index.ts | 2 +- .../api/testProfileRunOperationsContext.ts | 5 +- .../src/testProfileRunOperations/index.ts | 2 +- .../testProfileRunOperationsClient.ts | 6 +- .../src/testRunOperations/api/index.ts | 6 +- .../src/testRunOperations/api/operations.ts | 1123 ++++++++++++---- .../testRunOperations/api/pollingHelpers.ts | 139 -- .../api/testRunOperationsContext.ts | 6 +- .../src/testRunOperations/index.ts | 45 +- .../src/testRunOperations/models/index.ts | 44 +- .../src/testRunOperations/models/models.ts | 1154 ++++++++++++++--- .../src/testRunOperations/models/options.ts | 43 +- .../testRunOperations/restorePollerHelpers.ts | 156 --- .../testRunOperationsClient.ts | 76 +- 37 files changed, 5089 insertions(+), 1891 deletions(-) delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index 3ffb0f08e9..84814cf9a1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -679,7 +679,7 @@ export interface TestProfile { // @public (undocumented) export class TestProfileAdministrationOperationsClient { - constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileAdministrationOperationsClientOptions); + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileAdministrationOperationsClientOptionalParams); createOrUpdateTestProfile(testProfileId: string, body: TestProfileAdministrationOperationsClientTestProfile, options?: CreateOrUpdateTestProfileOptionalParams): Promise; deleteTestProfile(testProfileId: string, options?: DeleteTestProfileOptionalParams): Promise; getTestProfile(testProfileId: string, options?: GetTestProfileOptionalParams): Promise; @@ -1018,7 +1018,7 @@ export interface TestProfileAdministrationOperationsClientOptionalLoadTestConfig } // @public -export interface TestProfileAdministrationOperationsClientOptions extends ClientOptions { +export interface TestProfileAdministrationOperationsClientOptionalParams extends ClientOptions { apiVersion?: string; } @@ -1376,7 +1376,7 @@ export interface TestProfileRun { // @public (undocumented) export class TestProfileRunOperationsClient { - constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileRunOperationsClientOptions); + constructor(endpointParam: string, credential: TokenCredential, options?: TestProfileRunOperationsClientOptionalParams); createOrUpdateTestProfileRun(testProfileRunId: string, body: TestProfileRunOperationsClientTestProfileRun, options?: CreateOrUpdateTestProfileRunOptionalParams): Promise; deleteTestProfileRun(testProfileRunId: string, options?: DeleteTestProfileRunOptionalParams): Promise; getTestProfileRun(testProfileRunId: string, options?: GetTestProfileRunOptionalParams): Promise; @@ -1716,7 +1716,7 @@ export interface TestProfileRunOperationsClientOptionalLoadTestConfig { } // @public -export interface TestProfileRunOperationsClientOptions extends ClientOptions { +export interface TestProfileRunOperationsClientOptionalParams extends ClientOptions { apiVersion?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts index c6758208ac..ccb9563f38 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/administrationOperationsClient.ts @@ -5,7 +5,7 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { Test, - FileInfo, + TestFileInfo, TestAppComponents, TestServerMetricConfig, } from "./models/models.js"; @@ -27,7 +27,7 @@ import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createAdministrationOperations, AdministrationOperationsClientOptionalParams, - AzureLoadTestingContext, + LoadTestServiceContext, createOrUpdateTest, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, @@ -45,7 +45,7 @@ import { export { AdministrationOperationsClientOptionalParams } from "./api/administrationOperationsContext.js"; export class AdministrationOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -66,7 +66,7 @@ export class AdministrationOperationsClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ createOrUpdateTest( testId: string, body: Test, @@ -75,7 +75,7 @@ export class AdministrationOperationsClient { return createOrUpdateTest(this._client, testId, body, options); } - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ createOrUpdateAppComponents( testId: string, body: TestAppComponents, @@ -116,7 +116,7 @@ export class AdministrationOperationsClient { return getServerMetricsConfig(this._client, testId, options); } - /** Get load test details by test name */ + /** Get load test details by test Id */ getTest( testId: string, options: GetTestOptionalParams = { requestOptions: {} }, @@ -124,12 +124,12 @@ export class AdministrationOperationsClient { return getTest(this._client, testId, options); } - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ getTestFile( testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return getTestFile(this._client, testId, fileName, options); } @@ -137,7 +137,7 @@ export class AdministrationOperationsClient { listTestFiles( testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -152,7 +152,7 @@ export class AdministrationOperationsClient { } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -161,7 +161,7 @@ export class AdministrationOperationsClient { fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return uploadTestFile(this._client, testId, fileName, body, options); } @@ -174,7 +174,7 @@ export class AdministrationOperationsClient { return deleteTestFile(this._client, testId, fileName, options); } - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ deleteTest( testId: string, options: DeleteTestOptionalParams = { requestOptions: {} }, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts index 63ab99b143..5f3dc381d0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/administrationOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ @@ -13,13 +13,13 @@ export interface AdministrationOperationsClientOptionalParams apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createAdministrationOperations( endpointParam: string, credential: TokenCredential, options: AdministrationOperationsClientOptionalParams = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts index a19e1a4bc4..a2e6148705 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/index.ts @@ -4,7 +4,7 @@ export { createAdministrationOperations, AdministrationOperationsClientOptionalParams, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./administrationOperationsContext.js"; export { createOrUpdateTest, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts index c4e7c08c20..7dbe0f44a8 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/api/operations.ts @@ -3,23 +3,23 @@ import { passFailCriteriaSerializer, + autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, Test, - FileInfo, + TestFileInfo, TestAppComponents, TestServerMetricConfig, - _PagedFileInfo, _PagedTest, + _PagedTestFileInfo, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestAdministrationCreateOrUpdateAppComponents200Response, LoadTestAdministrationCreateOrUpdateAppComponents201Response, LoadTestAdministrationCreateOrUpdateAppComponentsDefaultResponse, @@ -47,6 +47,7 @@ import { LoadTestAdministrationListTestsDefaultResponse, LoadTestAdministrationUploadTestFile201Response, LoadTestAdministrationUploadTestFileDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -89,6 +90,9 @@ export function _createOrUpdateTestSend( passFailCriteria: !body.passFailCriteria ? body.passFailCriteria : passFailCriteriaSerializer(body.passFailCriteria), + autoStopCriteria: !body.autoStopCriteria + ? body.autoStopCriteria + : autoStopCriteriaSerializer(body.autoStopCriteria), secrets: !body.secrets ? body.secrets : (serializeRecord(body.secrets as any, secretSerializer) as any), @@ -101,9 +105,12 @@ export function _createOrUpdateTestSend( loadTestConfiguration: !body.loadTestConfiguration ? body.loadTestConfiguration : loadTestConfigurationSerializer(body.loadTestConfiguration), + baselineTestRunId: body["baselineTestRunId"], description: body["description"], displayName: body["displayName"], subnetId: body["subnetId"], + kind: body["kind"], + publicIPDisabled: body["publicIPDisabled"], keyvaultReferenceIdentityType: body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: body["keyvaultReferenceIdentityId"], }, @@ -124,6 +131,14 @@ export async function _createOrUpdateTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -148,6 +163,14 @@ export async function _createOrUpdateTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -161,22 +184,41 @@ export async function _createOrUpdateTestDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -189,15 +231,21 @@ export async function _createOrUpdateTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -210,15 +258,21 @@ export async function _createOrUpdateTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -232,13 +286,13 @@ export async function _createOrUpdateTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -246,7 +300,13 @@ export async function _createOrUpdateTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -256,15 +316,50 @@ export async function _createOrUpdateTestDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" + ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -274,16 +369,24 @@ export async function _createOrUpdateTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create a new test or update an existing test. */ +/** Create a new test or update an existing test by providing the test Id. */ export async function createOrUpdateTest( context: Client, testId: string, @@ -332,14 +435,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test */ +/** Add an app component to a test by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testId: string, @@ -374,12 +483,10 @@ export function _createOrUpdateServerMetricsConfigSend( contentType: (options.contentType as any) ?? "application/merge-patch+json", body: { - metrics: !body.metrics - ? body.metrics - : (serializeRecord( - body.metrics as any, - resourceMetricSerializer, - ) as any), + metrics: serializeRecord( + body.metrics as any, + resourceMetricSerializer, + ) as any, }, }); } @@ -397,9 +504,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -447,9 +560,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testId: result.body["testId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -489,9 +608,15 @@ export async function _getServerMetricsConfigDeserialize( return { testId: result.body["testId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -532,6 +657,14 @@ export async function _getTestDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -556,6 +689,14 @@ export async function _getTestDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -569,22 +710,41 @@ export async function _getTestDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, + baselineTestRunId: result.body["baselineTestRunId"], inputArtifacts: !result.body.inputArtifacts ? undefined : { configFileInfo: !result.body.inputArtifacts?.configFileInfo ? undefined : { - url: result.body.inputArtifacts?.configFileInfo?.["url"], fileName: result.body.inputArtifacts?.configFileInfo?.["fileName"], + url: result.body.inputArtifacts?.configFileInfo?.["url"], fileType: result.body.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -597,15 +757,21 @@ export async function _getTestDeserialize( testScriptFileInfo: !result.body.inputArtifacts?.testScriptFileInfo ? undefined : { - url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileName: result.body.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: result.body.inputArtifacts?.testScriptFileInfo?.["url"], fileType: result.body.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.testScriptFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -618,15 +784,21 @@ export async function _getTestDeserialize( userPropFileInfo: !result.body.inputArtifacts?.userPropFileInfo ? undefined : { - url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileName: result.body.inputArtifacts?.userPropFileInfo?.["fileName"], + url: result.body.inputArtifacts?.userPropFileInfo?.["url"], fileType: result.body.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: result.body.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -640,13 +812,13 @@ export async function _getTestDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ - "url" - ], fileName: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileName" ], + url: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "url" + ], fileType: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "fileType" @@ -654,7 +826,13 @@ export async function _getTestDeserialize( expireDateTime: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: result.body.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -664,15 +842,50 @@ export async function _getTestDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileName" + ], + url: result.body.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "fileType" + ], + expireDateTime: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + result.body.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: result.body.inputArtifacts?.["additionalFileInfo"] === undefined ? result.body.inputArtifacts?.["additionalFileInfo"] : result.body.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -682,16 +895,24 @@ export async function _getTestDeserialize( description: result.body["description"], displayName: result.body["displayName"], subnetId: result.body["subnetId"], + kind: result.body["kind"], + publicIPDisabled: result.body["publicIPDisabled"], keyvaultReferenceIdentityType: result.body["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: result.body["keyvaultReferenceIdentityId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get load test details by test name */ +/** Get load test details by test Id */ export async function getTest( context: Client, testId: string, @@ -719,28 +940,31 @@ export async function _getTestFileDeserialize( result: | LoadTestAdministrationGetTestFile200Response | LoadTestAdministrationGetTestFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - url: result.body["url"], fileName: result.body["fileName"], + url: result.body["url"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } -/** Get test file by the file name. */ +/** Get all the files that are associated with a test. */ export async function getTestFile( context: Client, testId: string, fileName: string, options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _getTestFileSend(context, testId, fileName, options); return _getTestFileDeserialize(result); } @@ -762,7 +986,7 @@ export async function _listTestFilesDeserialize( result: | LoadTestAdministrationListTestFiles200Response | LoadTestAdministrationListTestFilesDefaultResponse, -): Promise<_PagedFileInfo> { +): Promise<_PagedTestFileInfo> { if (isUnexpected(result)) { throw createRestError(result); } @@ -770,10 +994,13 @@ export async function _listTestFilesDeserialize( return { value: result.body["value"].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -787,7 +1014,7 @@ export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), @@ -810,8 +1037,8 @@ export function _listTestsSend( queryParameters: { orderby: options?.orderby, search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime, - lastModifiedEndTime: options?.lastModifiedEndTime, + lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), + lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), maxpagesize: options?.maxpagesize, }, }); @@ -832,6 +1059,14 @@ export async function _listTestsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -855,6 +1090,14 @@ export async function _listTestsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -868,18 +1111,38 @@ export async function _listTestsDeserialize( "duration" ], }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }, + ), }, + baselineTestRunId: p["baselineTestRunId"], inputArtifacts: !p.inputArtifacts ? undefined : { configFileInfo: !p.inputArtifacts?.configFileInfo ? undefined : { - url: p.inputArtifacts?.configFileInfo?.["url"], fileName: p.inputArtifacts?.configFileInfo?.["fileName"], + url: p.inputArtifacts?.configFileInfo?.["url"], fileType: p.inputArtifacts?.configFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.configFileInfo?.["expireDateTime"], + p.inputArtifacts?.configFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.configFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.configFileInfo?.["validationStatus"], validationFailureDetails: @@ -890,13 +1153,21 @@ export async function _listTestsDeserialize( testScriptFileInfo: !p.inputArtifacts?.testScriptFileInfo ? undefined : { - url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileName: p.inputArtifacts?.testScriptFileInfo?.["fileName"], + url: p.inputArtifacts?.testScriptFileInfo?.["url"], fileType: p.inputArtifacts?.testScriptFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.testScriptFileInfo?.["expireDateTime"], + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.testScriptFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.testScriptFileInfo?.[ "validationStatus" @@ -909,11 +1180,18 @@ export async function _listTestsDeserialize( userPropFileInfo: !p.inputArtifacts?.userPropFileInfo ? undefined : { - url: p.inputArtifacts?.userPropFileInfo?.["url"], fileName: p.inputArtifacts?.userPropFileInfo?.["fileName"], + url: p.inputArtifacts?.userPropFileInfo?.["url"], fileType: p.inputArtifacts?.userPropFileInfo?.["fileType"], expireDateTime: - p.inputArtifacts?.userPropFileInfo?.["expireDateTime"], + p.inputArtifacts?.userPropFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.inputArtifacts?.userPropFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.userPropFileInfo?.["validationStatus"], validationFailureDetails: @@ -925,15 +1203,21 @@ export async function _listTestsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileName: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileName"], + url: p.inputArtifacts?.inputArtifactsZipFileInfo?.["url"], fileType: p.inputArtifacts?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.inputArtifacts?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.inputArtifacts?.inputArtifactsZipFileInfo?.[ "validationStatus" @@ -943,15 +1227,45 @@ export async function _listTestsDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !p.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileName"], + url: p.inputArtifacts?.urlTestConfigFileInfo?.["url"], + fileType: + p.inputArtifacts?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, + validationStatus: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + p.inputArtifacts?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: p.inputArtifacts?.["additionalFileInfo"] === undefined ? p.inputArtifacts?.["additionalFileInfo"] : p.inputArtifacts?.["additionalFileInfo"].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], }; @@ -961,11 +1275,19 @@ export async function _listTestsDeserialize( description: p["description"], displayName: p["displayName"], subnetId: p["subnetId"], + kind: p["kind"], + publicIPDisabled: p["publicIPDisabled"], keyvaultReferenceIdentityType: p["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: p["keyvaultReferenceIdentityId"], - createdDateTime: p["createdDateTime"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], }; }), @@ -1013,23 +1335,26 @@ export async function _uploadTestFileDeserialize( result: | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - url: result.body["url"], fileName: result.body["fileName"], + url: result.body["url"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; } /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -1039,7 +1364,7 @@ export async function uploadTestFile( fileName: string, body: Uint8Array, options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _uploadTestFileSend( context, testId, @@ -1112,7 +1437,7 @@ export async function _deleteTestDeserialize( return; } -/** Delete a test by its name. */ +/** Delete a test by its test Id. */ export async function deleteTest( context: Client, testId: string, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts index 23a819ab77..dee5083a2d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/index.ts @@ -9,20 +9,32 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, + AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -33,20 +45,28 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + KnownTimeGrain, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -54,6 +74,20 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, + ResourceKind, + TestProfileRun, + KnownTestProfileRunStatus, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + KnownRecommendationCategory, + RecommendationCategory, + TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts index 8385d30729..5968849e35 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/index.ts @@ -5,20 +5,32 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, + AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -29,20 +41,28 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + KnownTimeGrain, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -50,6 +70,20 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, + ResourceKind, + TestProfileRun, + KnownTestProfileRunStatus, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + KnownRecommendationCategory, + RecommendationCategory, + TargetResourceConfigurationsUnion, } from "./models.js"; export { CreateOrUpdateTestOptionalParams, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts index 3a7491a214..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/models.ts @@ -6,10 +6,12 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -19,12 +21,19 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -33,32 +42,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -68,6 +83,9 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -80,9 +98,12 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -113,7 +134,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -148,28 +169,148 @@ export function passFailMetricSerializer( }; } -/** Type of PFMetrics */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Type of PFAgFunc */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; -/** Type of PFAction */ -export type PFAction = "continue" | "stop"; -/** Type of PFResult */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} /** Secret */ export interface Secret { @@ -186,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Type of SecretType */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -209,15 +365,24 @@ export function certificateMetadataSerializer( }; } -/** Type of CertificateType */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -231,8 +396,10 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -245,21 +412,26 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } @@ -268,53 +440,146 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Type of FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** Type of FileStatus */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} -/** Test app component */ +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -324,12 +589,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -345,20 +610,14 @@ export function testAppComponentsSerializer( }; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -387,13 +646,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -402,9 +661,10 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, }; } @@ -446,31 +706,21 @@ export function resourceMetricSerializer( }; } -/** Collection of files. */ -export interface _PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Type of APIVersions */ -export type APIVersions = "2022-11-01"; +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -485,8 +735,18 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -503,24 +763,32 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -530,6 +798,9 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -545,6 +816,8 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -578,6 +851,18 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -597,45 +882,153 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; -} - -/** Type of PFTestResult */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Type of Status */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -647,12 +1040,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -678,12 +1071,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -698,11 +1091,41 @@ export function testRunServerMetricConfigSerializer( }; } -/** Type of Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -742,25 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Type of AggregationType */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; -/** Type of MetricUnit */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -771,9 +1261,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** Type of TimeGrain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -788,7 +1275,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -828,7 +1315,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _PagedTimeSeriesElement { +export interface _Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -845,8 +1332,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -859,7 +1346,267 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 2048, 4096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -867,10 +1614,23 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface _PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; /** The link to the next page of items */ nextLink?: string; } + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts index f6d6da0948..4a2f18723c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/administrationOperations/models/options.ts @@ -6,18 +6,21 @@ import { FileType } from "./models.js"; /** Optional parameters. */ export interface CreateOrUpdateTestOptionalParams extends OperationOptions { + /** This request has a JSON Merge Patch body. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -50,22 +53,17 @@ export interface ListTestsOptionalParams extends OperationOptions { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date; /** Number of results in response. */ maxpagesize?: number; } /** Optional parameters. */ export interface UploadTestFileOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; /** File type */ fileType?: FileType; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index d2d938a6f2..ab86cd7792 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -9,20 +9,32 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, + AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -33,20 +45,28 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + KnownTimeGrain, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -54,6 +74,20 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, + ResourceKind, + TestProfileRun, + KnownTestProfileRunStatus, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + KnownRecommendationCategory, + RecommendationCategory, + TargetResourceConfigurationsUnion, CreateOrUpdateTestOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, @@ -74,28 +108,36 @@ export { TestRunOperationsClient, TestRunOperationsClientOptionalParams, } from "./testRunOperations/testRunOperationsClient.js"; -export { - restorePoller, - RestorePollerOptions, -} from "./testRunOperations/restorePollerHelpers.js"; export { Test as TestRunOperationsClientTest, PassFailCriteria as TestRunOperationsClientPassFailCriteria, PassFailMetric as TestRunOperationsClientPassFailMetric, + KnownPFMetrics as TestRunOperationsClientKnownPFMetrics, PFMetrics as TestRunOperationsClientPFMetrics, + KnownPFAgFunc as TestRunOperationsClientKnownPFAgFunc, PFAgFunc as TestRunOperationsClientPFAgFunc, + KnownPFAction as TestRunOperationsClientKnownPFAction, PFAction as TestRunOperationsClientPFAction, + KnownPFResult as TestRunOperationsClientKnownPFResult, PFResult as TestRunOperationsClientPFResult, + AutoStopCriteria as TestRunOperationsClientAutoStopCriteria, Secret as TestRunOperationsClientSecret, + KnownSecretType as TestRunOperationsClientKnownSecretType, SecretType as TestRunOperationsClientSecretType, CertificateMetadata as TestRunOperationsClientCertificateMetadata, + KnownCertificateType as TestRunOperationsClientKnownCertificateType, CertificateType as TestRunOperationsClientCertificateType, LoadTestConfiguration as TestRunOperationsClientLoadTestConfiguration, OptionalLoadTestConfig as TestRunOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestRunOperationsClientRegionalConfiguration, TestInputArtifacts as TestRunOperationsClientTestInputArtifacts, - FileInfo as TestRunOperationsClientFileInfo, + TestFileInfo as TestRunOperationsClientTestFileInfo, + KnownFileType as TestRunOperationsClientKnownFileType, FileType as TestRunOperationsClientFileType, + KnownFileStatus as TestRunOperationsClientKnownFileStatus, FileStatus as TestRunOperationsClientFileStatus, + KnownTestKind as TestRunOperationsClientKnownTestKind, + TestKind as TestRunOperationsClientTestKind, TestAppComponents as TestRunOperationsClientTestAppComponents, AppComponent as TestRunOperationsClientAppComponent, TestServerMetricConfig as TestRunOperationsClientTestServerMetricConfig, @@ -106,20 +148,28 @@ export { TestRunStatistics as TestRunOperationsClientTestRunStatistics, TestRunArtifacts as TestRunOperationsClientTestRunArtifacts, TestRunInputArtifacts as TestRunOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestRunOperationsClientTestRunFileInfo, TestRunOutputArtifacts as TestRunOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestRunOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestRunOperationsClientKnownPFTestResult, PFTestResult as TestRunOperationsClientPFTestResult, + KnownStatus as TestRunOperationsClientKnownStatus, Status as TestRunOperationsClientStatus, + KnownRequestDataLevel as TestRunOperationsClientKnownRequestDataLevel, + RequestDataLevel as TestRunOperationsClientRequestDataLevel, TestRunAppComponents as TestRunOperationsClientTestRunAppComponents, TestRunServerMetricConfig as TestRunOperationsClientTestRunServerMetricConfig, - Interval as TestRunOperationsClientInterval, + KnownTimeGrain as TestRunOperationsClientKnownTimeGrain, + TimeGrain as TestRunOperationsClientTimeGrain, DimensionValueList as TestRunOperationsClientDimensionValueList, MetricDefinitionCollection as TestRunOperationsClientMetricDefinitionCollection, MetricDefinition as TestRunOperationsClientMetricDefinition, NameAndDesc as TestRunOperationsClientNameAndDesc, + KnownAggregationType as TestRunOperationsClientKnownAggregationType, AggregationType as TestRunOperationsClientAggregationType, + KnownMetricUnit as TestRunOperationsClientKnownMetricUnit, MetricUnit as TestRunOperationsClientMetricUnit, MetricAvailability as TestRunOperationsClientMetricAvailability, - TimeGrain as TestRunOperationsClientTimeGrain, MetricNamespaceCollection as TestRunOperationsClientMetricNamespaceCollection, MetricNamespace as TestRunOperationsClientMetricNamespace, MetricRequestPayload as TestRunOperationsClientMetricRequestPayload, @@ -127,7 +177,21 @@ export { TimeSeriesElement as TestRunOperationsClientTimeSeriesElement, MetricValue as TestRunOperationsClientMetricValue, DimensionValue as TestRunOperationsClientDimensionValue, - TestRunOptionalParams, + TestProfile as TestRunOperationsClientTestProfile, + TargetResourceConfigurations as TestRunOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestRunOperationsClientKnownResourceKind, + ResourceKind as TestRunOperationsClientResourceKind, + TestProfileRun as TestRunOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestRunOperationsClientKnownTestProfileRunStatus, + TestProfileRunStatus as TestRunOperationsClientTestProfileRunStatus, + TestRunDetail as TestRunOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestRunOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestRunOperationsClientKnownRecommendationCategory, + RecommendationCategory as TestRunOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestRunOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams as TestRunOperationsClientCreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams as TestRunOperationsClientCreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -140,8 +204,199 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings as TestRunOperationsClientPageSettings, ContinuablePage as TestRunOperationsClientContinuablePage, PagedAsyncIterableIterator as TestRunOperationsClientPagedAsyncIterableIterator, } from "./testRunOperations/models/index.js"; +export { + TestProfileAdministrationOperationsClient, + TestProfileAdministrationOperationsClientOptionalParams, +} from "./testProfileAdministrationOperations/testProfileAdministrationOperationsClient.js"; +export { + Test as TestProfileAdministrationOperationsClientTest, + PassFailCriteria as TestProfileAdministrationOperationsClientPassFailCriteria, + PassFailMetric as TestProfileAdministrationOperationsClientPassFailMetric, + KnownPFMetrics as TestProfileAdministrationOperationsClientKnownPFMetrics, + PFMetrics as TestProfileAdministrationOperationsClientPFMetrics, + KnownPFAgFunc as TestProfileAdministrationOperationsClientKnownPFAgFunc, + PFAgFunc as TestProfileAdministrationOperationsClientPFAgFunc, + KnownPFAction as TestProfileAdministrationOperationsClientKnownPFAction, + PFAction as TestProfileAdministrationOperationsClientPFAction, + KnownPFResult as TestProfileAdministrationOperationsClientKnownPFResult, + PFResult as TestProfileAdministrationOperationsClientPFResult, + AutoStopCriteria as TestProfileAdministrationOperationsClientAutoStopCriteria, + Secret as TestProfileAdministrationOperationsClientSecret, + KnownSecretType as TestProfileAdministrationOperationsClientKnownSecretType, + SecretType as TestProfileAdministrationOperationsClientSecretType, + CertificateMetadata as TestProfileAdministrationOperationsClientCertificateMetadata, + KnownCertificateType as TestProfileAdministrationOperationsClientKnownCertificateType, + CertificateType as TestProfileAdministrationOperationsClientCertificateType, + LoadTestConfiguration as TestProfileAdministrationOperationsClientLoadTestConfiguration, + OptionalLoadTestConfig as TestProfileAdministrationOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestProfileAdministrationOperationsClientRegionalConfiguration, + TestInputArtifacts as TestProfileAdministrationOperationsClientTestInputArtifacts, + TestFileInfo as TestProfileAdministrationOperationsClientTestFileInfo, + KnownFileType as TestProfileAdministrationOperationsClientKnownFileType, + FileType as TestProfileAdministrationOperationsClientFileType, + KnownFileStatus as TestProfileAdministrationOperationsClientKnownFileStatus, + FileStatus as TestProfileAdministrationOperationsClientFileStatus, + KnownTestKind as TestProfileAdministrationOperationsClientKnownTestKind, + TestKind as TestProfileAdministrationOperationsClientTestKind, + TestAppComponents as TestProfileAdministrationOperationsClientTestAppComponents, + AppComponent as TestProfileAdministrationOperationsClientAppComponent, + TestServerMetricConfig as TestProfileAdministrationOperationsClientTestServerMetricConfig, + ResourceMetric as TestProfileAdministrationOperationsClientResourceMetric, + APIVersions as TestProfileAdministrationOperationsClientAPIVersions, + TestRun as TestProfileAdministrationOperationsClientTestRun, + ErrorDetails as TestProfileAdministrationOperationsClientErrorDetails, + TestRunStatistics as TestProfileAdministrationOperationsClientTestRunStatistics, + TestRunArtifacts as TestProfileAdministrationOperationsClientTestRunArtifacts, + TestRunInputArtifacts as TestProfileAdministrationOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestProfileAdministrationOperationsClientTestRunFileInfo, + TestRunOutputArtifacts as TestProfileAdministrationOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestProfileAdministrationOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestProfileAdministrationOperationsClientKnownPFTestResult, + PFTestResult as TestProfileAdministrationOperationsClientPFTestResult, + KnownStatus as TestProfileAdministrationOperationsClientKnownStatus, + Status as TestProfileAdministrationOperationsClientStatus, + KnownRequestDataLevel as TestProfileAdministrationOperationsClientKnownRequestDataLevel, + RequestDataLevel as TestProfileAdministrationOperationsClientRequestDataLevel, + TestRunAppComponents as TestProfileAdministrationOperationsClientTestRunAppComponents, + TestRunServerMetricConfig as TestProfileAdministrationOperationsClientTestRunServerMetricConfig, + KnownTimeGrain as TestProfileAdministrationOperationsClientKnownTimeGrain, + TimeGrain as TestProfileAdministrationOperationsClientTimeGrain, + DimensionValueList as TestProfileAdministrationOperationsClientDimensionValueList, + MetricDefinitionCollection as TestProfileAdministrationOperationsClientMetricDefinitionCollection, + MetricDefinition as TestProfileAdministrationOperationsClientMetricDefinition, + NameAndDesc as TestProfileAdministrationOperationsClientNameAndDesc, + KnownAggregationType as TestProfileAdministrationOperationsClientKnownAggregationType, + AggregationType as TestProfileAdministrationOperationsClientAggregationType, + KnownMetricUnit as TestProfileAdministrationOperationsClientKnownMetricUnit, + MetricUnit as TestProfileAdministrationOperationsClientMetricUnit, + MetricAvailability as TestProfileAdministrationOperationsClientMetricAvailability, + MetricNamespaceCollection as TestProfileAdministrationOperationsClientMetricNamespaceCollection, + MetricNamespace as TestProfileAdministrationOperationsClientMetricNamespace, + MetricRequestPayload as TestProfileAdministrationOperationsClientMetricRequestPayload, + DimensionFilter as TestProfileAdministrationOperationsClientDimensionFilter, + TimeSeriesElement as TestProfileAdministrationOperationsClientTimeSeriesElement, + MetricValue as TestProfileAdministrationOperationsClientMetricValue, + DimensionValue as TestProfileAdministrationOperationsClientDimensionValue, + TestProfile as TestProfileAdministrationOperationsClientTestProfile, + TargetResourceConfigurations as TestProfileAdministrationOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestProfileAdministrationOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestProfileAdministrationOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestProfileAdministrationOperationsClientKnownResourceKind, + ResourceKind as TestProfileAdministrationOperationsClientResourceKind, + TestProfileRun as TestProfileAdministrationOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestProfileAdministrationOperationsClientKnownTestProfileRunStatus, + TestProfileRunStatus as TestProfileAdministrationOperationsClientTestProfileRunStatus, + TestRunDetail as TestProfileAdministrationOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestProfileAdministrationOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestProfileAdministrationOperationsClientKnownRecommendationCategory, + RecommendationCategory as TestProfileAdministrationOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestProfileAdministrationOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + GetTestProfileOptionalParams, + ListTestProfilesOptionalParams, + PageSettings as TestProfileAdministrationOperationsClientPageSettings, + ContinuablePage as TestProfileAdministrationOperationsClientContinuablePage, + PagedAsyncIterableIterator as TestProfileAdministrationOperationsClientPagedAsyncIterableIterator, +} from "./testProfileAdministrationOperations/models/index.js"; +export { + TestProfileRunOperationsClient, + TestProfileRunOperationsClientOptionalParams, +} from "./testProfileRunOperations/testProfileRunOperationsClient.js"; +export { + Test as TestProfileRunOperationsClientTest, + PassFailCriteria as TestProfileRunOperationsClientPassFailCriteria, + PassFailMetric as TestProfileRunOperationsClientPassFailMetric, + KnownPFMetrics as TestProfileRunOperationsClientKnownPFMetrics, + PFMetrics as TestProfileRunOperationsClientPFMetrics, + KnownPFAgFunc as TestProfileRunOperationsClientKnownPFAgFunc, + PFAgFunc as TestProfileRunOperationsClientPFAgFunc, + KnownPFAction as TestProfileRunOperationsClientKnownPFAction, + PFAction as TestProfileRunOperationsClientPFAction, + KnownPFResult as TestProfileRunOperationsClientKnownPFResult, + PFResult as TestProfileRunOperationsClientPFResult, + AutoStopCriteria as TestProfileRunOperationsClientAutoStopCriteria, + Secret as TestProfileRunOperationsClientSecret, + KnownSecretType as TestProfileRunOperationsClientKnownSecretType, + SecretType as TestProfileRunOperationsClientSecretType, + CertificateMetadata as TestProfileRunOperationsClientCertificateMetadata, + KnownCertificateType as TestProfileRunOperationsClientKnownCertificateType, + CertificateType as TestProfileRunOperationsClientCertificateType, + LoadTestConfiguration as TestProfileRunOperationsClientLoadTestConfiguration, + OptionalLoadTestConfig as TestProfileRunOperationsClientOptionalLoadTestConfig, + RegionalConfiguration as TestProfileRunOperationsClientRegionalConfiguration, + TestInputArtifacts as TestProfileRunOperationsClientTestInputArtifacts, + TestFileInfo as TestProfileRunOperationsClientTestFileInfo, + KnownFileType as TestProfileRunOperationsClientKnownFileType, + FileType as TestProfileRunOperationsClientFileType, + KnownFileStatus as TestProfileRunOperationsClientKnownFileStatus, + FileStatus as TestProfileRunOperationsClientFileStatus, + KnownTestKind as TestProfileRunOperationsClientKnownTestKind, + TestKind as TestProfileRunOperationsClientTestKind, + TestAppComponents as TestProfileRunOperationsClientTestAppComponents, + AppComponent as TestProfileRunOperationsClientAppComponent, + TestServerMetricConfig as TestProfileRunOperationsClientTestServerMetricConfig, + ResourceMetric as TestProfileRunOperationsClientResourceMetric, + APIVersions as TestProfileRunOperationsClientAPIVersions, + TestRun as TestProfileRunOperationsClientTestRun, + ErrorDetails as TestProfileRunOperationsClientErrorDetails, + TestRunStatistics as TestProfileRunOperationsClientTestRunStatistics, + TestRunArtifacts as TestProfileRunOperationsClientTestRunArtifacts, + TestRunInputArtifacts as TestProfileRunOperationsClientTestRunInputArtifacts, + TestRunFileInfo as TestProfileRunOperationsClientTestRunFileInfo, + TestRunOutputArtifacts as TestProfileRunOperationsClientTestRunOutputArtifacts, + ArtifactsContainerInfo as TestProfileRunOperationsClientArtifactsContainerInfo, + KnownPFTestResult as TestProfileRunOperationsClientKnownPFTestResult, + PFTestResult as TestProfileRunOperationsClientPFTestResult, + KnownStatus as TestProfileRunOperationsClientKnownStatus, + Status as TestProfileRunOperationsClientStatus, + KnownRequestDataLevel as TestProfileRunOperationsClientKnownRequestDataLevel, + RequestDataLevel as TestProfileRunOperationsClientRequestDataLevel, + TestRunAppComponents as TestProfileRunOperationsClientTestRunAppComponents, + TestRunServerMetricConfig as TestProfileRunOperationsClientTestRunServerMetricConfig, + KnownTimeGrain as TestProfileRunOperationsClientKnownTimeGrain, + TimeGrain as TestProfileRunOperationsClientTimeGrain, + DimensionValueList as TestProfileRunOperationsClientDimensionValueList, + MetricDefinitionCollection as TestProfileRunOperationsClientMetricDefinitionCollection, + MetricDefinition as TestProfileRunOperationsClientMetricDefinition, + NameAndDesc as TestProfileRunOperationsClientNameAndDesc, + KnownAggregationType as TestProfileRunOperationsClientKnownAggregationType, + AggregationType as TestProfileRunOperationsClientAggregationType, + KnownMetricUnit as TestProfileRunOperationsClientKnownMetricUnit, + MetricUnit as TestProfileRunOperationsClientMetricUnit, + MetricAvailability as TestProfileRunOperationsClientMetricAvailability, + MetricNamespaceCollection as TestProfileRunOperationsClientMetricNamespaceCollection, + MetricNamespace as TestProfileRunOperationsClientMetricNamespace, + MetricRequestPayload as TestProfileRunOperationsClientMetricRequestPayload, + DimensionFilter as TestProfileRunOperationsClientDimensionFilter, + TimeSeriesElement as TestProfileRunOperationsClientTimeSeriesElement, + MetricValue as TestProfileRunOperationsClientMetricValue, + DimensionValue as TestProfileRunOperationsClientDimensionValue, + TestProfile as TestProfileRunOperationsClientTestProfile, + TargetResourceConfigurations as TestProfileRunOperationsClientTargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations as TestProfileRunOperationsClientFunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration as TestProfileRunOperationsClientFunctionFlexConsumptionResourceConfiguration, + KnownResourceKind as TestProfileRunOperationsClientKnownResourceKind, + ResourceKind as TestProfileRunOperationsClientResourceKind, + TestProfileRun as TestProfileRunOperationsClientTestProfileRun, + KnownTestProfileRunStatus as TestProfileRunOperationsClientKnownTestProfileRunStatus, + TestProfileRunStatus as TestProfileRunOperationsClientTestProfileRunStatus, + TestRunDetail as TestProfileRunOperationsClientTestRunDetail, + TestProfileRunRecommendation as TestProfileRunOperationsClientTestProfileRunRecommendation, + KnownRecommendationCategory as TestProfileRunOperationsClientKnownRecommendationCategory, + RecommendationCategory as TestProfileRunOperationsClientRecommendationCategory, + TargetResourceConfigurationsUnion as TestProfileRunOperationsClientTargetResourceConfigurationsUnion, + CreateOrUpdateTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + GetTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + StopOptionalParams as TestProfileRunOperationsClientStopOptionalParams, + PageSettings as TestProfileRunOperationsClientPageSettings, + ContinuablePage as TestProfileRunOperationsClientContinuablePage, + PagedAsyncIterableIterator as TestProfileRunOperationsClientPagedAsyncIterableIterator, +} from "./testProfileRunOperations/models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts deleted file mode 100644 index fb04796c1d..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/azureLoadTestingClient.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { getClient, ClientOptions } from "@azure-rest/core-client"; -import { logger } from "../logger.js"; -import { TokenCredential } from "@azure/core-auth"; -import { AzureLoadTestingContext } from "./clientDefinitions.js"; - -/** The optional parameters for the client */ -export interface AzureLoadTestingContextOptions extends ClientOptions { - /** The api version option of the client */ - apiVersion?: string; -} - -/** - * Initialize a new instance of `AzureLoadTestingContext` - * @param endpointParam - A sequence of textual characters. - * @param credentials - uniquely identify client credential - * @param options - the parameter for all optional parameters - */ -export default function createClient( - endpointParam: string, - credentials: TokenCredential, - { - apiVersion = "2022-11-01", - ...options - }: AzureLoadTestingContextOptions = {}, -): AzureLoadTestingContext { - const endpointUrl = - options.endpoint ?? options.baseUrl ?? `https://${endpointParam}`; - const userAgentInfo = `azsdk-js-load-testing/1.0.1`; - const userAgentPrefix = - options.userAgentOptions && options.userAgentOptions.userAgentPrefix - ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` - : `${userAgentInfo}`; - options = { - ...options, - userAgentOptions: { - userAgentPrefix, - }, - loggingOptions: { - logger: options.loggingOptions?.logger ?? logger.info, - }, - credentials: { - scopes: options.credentials?.scopes ?? [ - "https://cnt-prod.loadtesting.azure.com/.default", - ], - }, - }; - const client = getClient( - endpointUrl, - credentials, - options, - ) as AzureLoadTestingContext; - - client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - client.pipeline.addPolicy({ - name: "ClientApiVersionPolicy", - sendRequest: (req, next) => { - // Use the apiVersion defined in request url directly - // Append one if there is no apiVersion and we have one at client options - const url = new URL(req.url); - if (!url.searchParams.get("api-version") && apiVersion) { - req.url = `${req.url}${ - Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" - }api-version=${apiVersion}`; - } - - return next(req); - }, - }); - return client; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts index 2d1d85129a..fa2d60737c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -14,12 +14,12 @@ import { LoadTestAdministrationGetAppComponentsParameters, LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters, LoadTestAdministrationGetServerMetricsConfigParameters, - LoadTestRunDeleteTestRunParameters, - LoadTestRunCreateOrUpdateTestRunParameters, LoadTestRunGetTestRunParameters, - LoadTestRunGetTestRunFileParameters, + LoadTestRunCreateOrUpdateTestRunParameters, + LoadTestRunDeleteTestRunParameters, LoadTestRunListTestRunsParameters, - LoadTestRunStopTestRunParameters, + LoadTestRunGetTestRunFileParameters, + LoadTestRunStopParameters, LoadTestRunListMetricNamespacesParameters, LoadTestRunListMetricDefinitionsParameters, LoadTestRunListMetricsParameters, @@ -27,7 +27,16 @@ import { LoadTestRunCreateOrUpdateAppComponentsParameters, LoadTestRunGetAppComponentsParameters, LoadTestRunCreateOrUpdateServerMetricsConfigParameters, - LoadTestRunTestRunListServerMetricsConfigParameters, + LoadTestRunGetServerMetricsConfigParameters, + TestProfileAdministrationCreateOrUpdateTestProfileParameters, + TestProfileAdministrationDeleteTestProfileParameters, + TestProfileAdministrationGetTestProfileParameters, + TestProfileAdministrationListTestProfilesParameters, + TestProfileRunAdministrationGetTestProfileRunParameters, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, + TestProfileRunAdministrationDeleteTestProfileRunParameters, + TestProfileRunAdministrationStopParameters, + TestProfileRunAdministrationListTestProfileRunsParameters, } from "./parameters.js"; import { LoadTestAdministrationCreateOrUpdateTest200Response, @@ -57,19 +66,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -86,13 +95,33 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, + TestProfileAdministrationCreateOrUpdateTestProfile200Response, + TestProfileAdministrationCreateOrUpdateTestProfile201Response, + TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, + TestProfileAdministrationDeleteTestProfile204Response, + TestProfileAdministrationDeleteTestProfileDefaultResponse, + TestProfileAdministrationGetTestProfile200Response, + TestProfileAdministrationGetTestProfileDefaultResponse, + TestProfileAdministrationListTestProfiles200Response, + TestProfileAdministrationListTestProfilesDefaultResponse, + TestProfileRunAdministrationGetTestProfileRun200Response, + TestProfileRunAdministrationGetTestProfileRunDefaultResponse, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, + TestProfileRunAdministrationDeleteTestProfileRun204Response, + TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, + TestProfileRunAdministrationStop200Response, + TestProfileRunAdministrationStopDefaultResponse, + TestProfileRunAdministrationListTestProfileRuns200Response, + TestProfileRunAdministrationListTestProfileRunsDefaultResponse, } from "./responses.js"; import { Client, StreamableMethod } from "@azure-rest/core-client"; export interface LoadTestAdministrationCreateOrUpdateTest { - /** Create a new test or update an existing test. */ + /** Create a new test or update an existing test by providing the test Id. */ patch( options: LoadTestAdministrationCreateOrUpdateTestParameters, ): StreamableMethod< @@ -100,14 +129,14 @@ export interface LoadTestAdministrationCreateOrUpdateTest { | LoadTestAdministrationCreateOrUpdateTest201Response | LoadTestAdministrationCreateOrUpdateTestDefaultResponse >; - /** Delete a test by its name. */ + /** Delete a test by its test Id. */ delete( options?: LoadTestAdministrationDeleteTestParameters, ): StreamableMethod< | LoadTestAdministrationDeleteTest204Response | LoadTestAdministrationDeleteTestDefaultResponse >; - /** Get load test details by test name */ + /** Get load test details by test Id */ get( options?: LoadTestAdministrationGetTestParameters, ): StreamableMethod< @@ -131,7 +160,7 @@ export interface LoadTestAdministrationListTests { export interface LoadTestAdministrationUploadTestFile { /** - * Upload input file for a given test name. File size can't be more than 50 MB. + * Upload input file for a given test Id. File size can't be more than 50 MB. * Existing file with same name for the given test will be overwritten. File * should be provided in the request body as application/octet-stream. */ @@ -141,7 +170,7 @@ export interface LoadTestAdministrationUploadTestFile { | LoadTestAdministrationUploadTestFile201Response | LoadTestAdministrationUploadTestFileDefaultResponse >; - /** Get test file by the file name. */ + /** Get all the files that are associated with a test. */ get( options?: LoadTestAdministrationGetTestFileParameters, ): StreamableMethod< @@ -168,7 +197,7 @@ export interface LoadTestAdministrationListTestFiles { } export interface LoadTestAdministrationCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test */ + /** Add an app component to a test by providing the resource Id, name and type. */ patch( options: LoadTestAdministrationCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -203,15 +232,14 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfig { >; } -export interface LoadTestRunDeleteTestRun { - /** Delete a test run by its name. */ - delete( - options?: LoadTestRunDeleteTestRunParameters, +export interface LoadTestRunGetTestRun { + /** Get test run details by test run Id. */ + get( + options?: LoadTestRunGetTestRunParameters, ): StreamableMethod< - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse >; - /** Create and start a new test run with the given name. */ + /** Create and start a new test run with the given test run Id. */ patch( options: LoadTestRunCreateOrUpdateTestRunParameters, ): StreamableMethod< @@ -219,11 +247,21 @@ export interface LoadTestRunDeleteTestRun { | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse >; - /** Get test run details by name. */ + /** Delete an existing load test run by providing the testRunId. */ + delete( + options?: LoadTestRunDeleteTestRunParameters, + ): StreamableMethod< + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse + >; +} + +export interface LoadTestRunListTestRuns { + /** Get all test runs for the given filters. */ get( - options?: LoadTestRunGetTestRunParameters, + options?: LoadTestRunListTestRunsParameters, ): StreamableMethod< - LoadTestRunGetTestRun200Response | LoadTestRunGetTestRunDefaultResponse + LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse >; } @@ -237,21 +275,12 @@ export interface LoadTestRunGetTestRunFile { >; } -export interface LoadTestRunListTestRuns { - /** Get all test runs with given filters */ - get( - options?: LoadTestRunListTestRunsParameters, - ): StreamableMethod< - LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - >; -} - -export interface LoadTestRunStopTestRun { - /** Stop test run by name. */ +export interface LoadTestRunStop { + /** Stop test run by test run Id. */ post( - options?: LoadTestRunStopTestRunParameters, + options?: LoadTestRunStopParameters, ): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse + LoadTestRunStop200Response | LoadTestRunStopDefaultResponse >; } @@ -268,7 +297,7 @@ export interface LoadTestRunListMetricNamespaces { export interface LoadTestRunListMetricDefinitions { /** List the metric definitions for a load test run. */ get( - options?: LoadTestRunListMetricDefinitionsParameters, + options: LoadTestRunListMetricDefinitionsParameters, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response | LoadTestRunListMetricDefinitionsDefaultResponse @@ -295,7 +324,7 @@ export interface LoadTestRunListMetricDimensionValues { } export interface LoadTestRunCreateOrUpdateAppComponents { - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ patch( options: LoadTestRunCreateOrUpdateAppComponentsParameters, ): StreamableMethod< @@ -324,12 +353,92 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfig { | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse >; - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ get( - options?: LoadTestRunTestRunListServerMetricsConfigParameters, + options?: LoadTestRunGetServerMetricsConfigParameters, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse + >; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfile { + /** Create a new test profile or update an existing test profile by providing the test profile Id. */ + patch( + options: TestProfileAdministrationCreateOrUpdateTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + >; + /** Delete a test profile by its test profile Id. */ + delete( + options?: TestProfileAdministrationDeleteTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse + >; + /** Get load test profile details by test profile Id. */ + get( + options?: TestProfileAdministrationGetTestProfileParameters, + ): StreamableMethod< + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse + >; +} + +export interface TestProfileAdministrationListTestProfiles { + /** Get all test profiles for the given filters. */ + get( + options?: TestProfileAdministrationListTestProfilesParameters, + ): StreamableMethod< + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse + >; +} + +export interface TestProfileRunAdministrationGetTestProfileRun { + /** Get test profile run details by test profile run Id. */ + get( + options?: TestProfileRunAdministrationGetTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + >; + /** Create and start a new test profile run with the given test profile run Id. */ + patch( + options: TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + >; + /** Delete an existing load test profile run by providing the test profile run Id. */ + delete( + options?: TestProfileRunAdministrationDeleteTestProfileRunParameters, + ): StreamableMethod< + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + >; +} + +export interface TestProfileRunAdministrationStop { + /** Stop test profile run for the given test profile run Id. */ + post( + options?: TestProfileRunAdministrationStopParameters, + ): StreamableMethod< + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse + >; +} + +export interface TestProfileRunAdministrationListTestProfileRuns { + /** Get all test profile runs for the given filters. */ + get( + options?: TestProfileRunAdministrationListTestProfileRunsParameters, + ): StreamableMethod< + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse >; } @@ -362,21 +471,18 @@ export interface Routes { path: "/tests/{testId}/server-metrics-config", testId: string, ): LoadTestAdministrationCreateOrUpdateServerMetricsConfig; - /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: delete, patch, get */ - (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunDeleteTestRun; + /** Resource for '/test-runs/\{testRunId\}' has methods for the following verbs: get, patch, delete */ + (path: "/test-runs/{testRunId}", testRunId: string): LoadTestRunGetTestRun; + /** Resource for '/test-runs' has methods for the following verbs: get */ + (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}/files/\{fileName\}' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/files/{fileName}", testRunId: string, fileName: string, ): LoadTestRunGetTestRunFile; - /** Resource for '/test-runs' has methods for the following verbs: get */ - (path: "/test-runs"): LoadTestRunListTestRuns; /** Resource for '/test-runs/\{testRunId\}:stop' has methods for the following verbs: post */ - ( - path: "/test-runs/{testRunId}:stop", - testRunId: string, - ): LoadTestRunStopTestRun; + (path: "/test-runs/{testRunId}:stop", testRunId: string): LoadTestRunStop; /** Resource for '/test-runs/\{testRunId\}/metric-namespaces' has methods for the following verbs: get */ ( path: "/test-runs/{testRunId}/metric-namespaces", @@ -408,8 +514,27 @@ export interface Routes { path: "/test-runs/{testRunId}/server-metrics-config", testRunId: string, ): LoadTestRunCreateOrUpdateServerMetricsConfig; + /** Resource for '/test-profiles/\{testProfileId\}' has methods for the following verbs: patch, delete, get */ + ( + path: "/test-profiles/{testProfileId}", + testProfileId: string, + ): TestProfileAdministrationCreateOrUpdateTestProfile; + /** Resource for '/test-profiles' has methods for the following verbs: get */ + (path: "/test-profiles"): TestProfileAdministrationListTestProfiles; + /** Resource for '/test-profile-runs/\{testProfileRunId\}' has methods for the following verbs: get, patch, delete */ + ( + path: "/test-profile-runs/{testProfileRunId}", + testProfileRunId: string, + ): TestProfileRunAdministrationGetTestProfileRun; + /** Resource for '/test-profile-runs/\{testProfileRunId\}:stop' has methods for the following verbs: post */ + ( + path: "/test-profile-runs/{testProfileRunId}:stop", + testProfileRunId: string, + ): TestProfileRunAdministrationStop; + /** Resource for '/test-profile-runs' has methods for the following verbs: get */ + (path: "/test-profile-runs"): TestProfileRunAdministrationListTestProfileRuns; } -export type AzureLoadTestingContext = Client & { +export type LoadTestServiceContext = Client & { path: Routes; }; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts index a22d574c4f..b57cb81db2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/index.ts @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import AzureLoadTestingClient from "./azureLoadTestingClient.js"; +import LoadTestServiceClient from "./loadTestServiceClient.js"; -export * from "./azureLoadTestingClient.js"; +export * from "./loadTestServiceClient.js"; export * from "./parameters.js"; export * from "./responses.js"; export * from "./clientDefinitions.js"; @@ -11,6 +11,5 @@ export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; export * from "./paginateHelper.js"; -export * from "./pollingHelper.js"; -export default AzureLoadTestingClient; +export default LoadTestServiceClient; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts index e02ac644d2..fdb24b329f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/isUnexpected.ts @@ -29,20 +29,19 @@ import { LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse, LoadTestAdministrationGetServerMetricsConfig200Response, LoadTestAdministrationGetServerMetricsConfigDefaultResponse, - LoadTestRunDeleteTestRun204Response, - LoadTestRunDeleteTestRunDefaultResponse, + LoadTestRunGetTestRun200Response, + LoadTestRunGetTestRunDefaultResponse, LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunGetTestRun200Response, - LoadTestRunGetTestRunDefaultResponse, - LoadTestRunGetTestRunFile200Response, - LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunDeleteTestRun204Response, + LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, + LoadTestRunGetTestRunFile200Response, + LoadTestRunGetTestRunFileDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, LoadTestRunListMetricNamespaces200Response, LoadTestRunListMetricNamespacesDefaultResponse, LoadTestRunListMetricDefinitions200Response, @@ -59,8 +58,28 @@ import { LoadTestRunCreateOrUpdateServerMetricsConfig200Response, LoadTestRunCreateOrUpdateServerMetricsConfig201Response, LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, + TestProfileAdministrationCreateOrUpdateTestProfile200Response, + TestProfileAdministrationCreateOrUpdateTestProfile201Response, + TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, + TestProfileAdministrationDeleteTestProfile204Response, + TestProfileAdministrationDeleteTestProfileDefaultResponse, + TestProfileAdministrationGetTestProfile200Response, + TestProfileAdministrationGetTestProfileDefaultResponse, + TestProfileAdministrationListTestProfiles200Response, + TestProfileAdministrationListTestProfilesDefaultResponse, + TestProfileRunAdministrationGetTestProfileRun200Response, + TestProfileRunAdministrationGetTestProfileRunDefaultResponse, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response, + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, + TestProfileRunAdministrationDeleteTestProfileRun204Response, + TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, + TestProfileRunAdministrationStop200Response, + TestProfileRunAdministrationStopDefaultResponse, + TestProfileRunAdministrationListTestProfileRuns200Response, + TestProfileRunAdministrationListTestProfileRunsDefaultResponse, } from "./responses.js"; const responseMap: Record = { @@ -76,11 +95,11 @@ const responseMap: Record = { "GET /tests/{testId}/app-components": ["200"], "PATCH /tests/{testId}/server-metrics-config": ["200", "201"], "GET /tests/{testId}/server-metrics-config": ["200"], - "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs/{testRunId}": ["200"], "PATCH /test-runs/{testRunId}": ["200", "201"], - "GET /test-runs/{testRunId}/files/{fileName}": ["200"], + "DELETE /test-runs/{testRunId}": ["204"], "GET /test-runs": ["200"], + "GET /test-runs/{testRunId}/files/{fileName}": ["200"], "POST /test-runs/{testRunId}:stop": ["200"], "GET /test-runs/{testRunId}/metric-namespaces": ["200"], "GET /test-runs/{testRunId}/metric-definitions": ["200"], @@ -90,6 +109,15 @@ const responseMap: Record = { "GET /test-runs/{testRunId}/app-components": ["200"], "PATCH /test-runs/{testRunId}/server-metrics-config": ["200", "201"], "GET /test-runs/{testRunId}/server-metrics-config": ["200"], + "PATCH /test-profiles/{testProfileId}": ["200", "201"], + "DELETE /test-profiles/{testProfileId}": ["204"], + "GET /test-profiles/{testProfileId}": ["200"], + "GET /test-profiles": ["200"], + "GET /test-profile-runs/{testProfileRunId}": ["200"], + "PATCH /test-profile-runs/{testProfileRunId}": ["200", "201"], + "DELETE /test-profile-runs/{testProfileRunId}": ["204"], + "POST /test-profile-runs/{testProfileRunId}:stop": ["200"], + "GET /test-profile-runs": ["200"], }; export function isUnexpected( @@ -157,26 +185,20 @@ export function isUnexpected( ): response is LoadTestAdministrationGetServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse, -): response is LoadTestRunDeleteTestRunDefaultResponse; + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse, +): response is LoadTestRunGetTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): response is LoadTestRunCreateOrUpdateTestRunDefaultResponse; export function isUnexpected( response: - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse, -): response is LoadTestRunGetTestRunDefaultResponse; -export function isUnexpected( - response: - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse, -): response is LoadTestRunGetTestRunFileDefaultResponse; + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse, +): response is LoadTestRunDeleteTestRunDefaultResponse; export function isUnexpected( response: | LoadTestRunListTestRuns200Response @@ -184,9 +206,12 @@ export function isUnexpected( ): response is LoadTestRunListTestRunsDefaultResponse; export function isUnexpected( response: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, -): response is LoadTestRunStopTestRunDefaultResponse; + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse, +): response is LoadTestRunGetTestRunFileDefaultResponse; +export function isUnexpected( + response: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, +): response is LoadTestRunStopDefaultResponse; export function isUnexpected( response: | LoadTestRunListMetricNamespaces200Response @@ -226,9 +251,56 @@ export function isUnexpected( ): response is LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse; export function isUnexpected( response: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, -): response is LoadTestRunTestRunListServerMetricsConfigDefaultResponse; + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, +): response is LoadTestRunGetServerMetricsConfigDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse, +): response is TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse, +): response is TestProfileAdministrationDeleteTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse, +): response is TestProfileAdministrationGetTestProfileDefaultResponse; +export function isUnexpected( + response: + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse, +): response is TestProfileAdministrationListTestProfilesDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationGetTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse, +): response is TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse, +): response is TestProfileRunAdministrationStopDefaultResponse; +export function isUnexpected( + response: + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, +): response is TestProfileRunAdministrationListTestProfileRunsDefaultResponse; export function isUnexpected( response: | LoadTestAdministrationCreateOrUpdateTest200Response @@ -258,20 +330,19 @@ export function isUnexpected( | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfig200Response | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRun204Response - | LoadTestRunDeleteTestRunDefaultResponse + | LoadTestRunGetTestRun200Response + | LoadTestRunGetTestRunDefaultResponse | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunLogicalResponse | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunGetTestRun200Response - | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFile200Response - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunDeleteTestRun204Response + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRuns200Response | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFile200Response + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStop200Response + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespaces200Response | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitions200Response @@ -288,8 +359,28 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateServerMetricsConfig200Response | LoadTestRunCreateOrUpdateServerMetricsConfig201Response | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse + | TestProfileAdministrationCreateOrUpdateTestProfile200Response + | TestProfileAdministrationCreateOrUpdateTestProfile201Response + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + | TestProfileAdministrationDeleteTestProfile204Response + | TestProfileAdministrationDeleteTestProfileDefaultResponse + | TestProfileAdministrationGetTestProfile200Response + | TestProfileAdministrationGetTestProfileDefaultResponse + | TestProfileAdministrationListTestProfiles200Response + | TestProfileAdministrationListTestProfilesDefaultResponse + | TestProfileRunAdministrationGetTestProfileRun200Response + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + | TestProfileRunAdministrationDeleteTestProfileRun204Response + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + | TestProfileRunAdministrationStop200Response + | TestProfileRunAdministrationStopDefaultResponse + | TestProfileRunAdministrationListTestProfileRuns200Response + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse, ): response is | LoadTestAdministrationCreateOrUpdateTestDefaultResponse | LoadTestAdministrationDeleteTestDefaultResponse @@ -303,12 +394,12 @@ export function isUnexpected( | LoadTestAdministrationGetAppComponentsDefaultResponse | LoadTestAdministrationCreateOrUpdateServerMetricsConfigDefaultResponse | LoadTestAdministrationGetServerMetricsConfigDefaultResponse - | LoadTestRunDeleteTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse | LoadTestRunGetTestRunDefaultResponse - | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunCreateOrUpdateTestRunDefaultResponse + | LoadTestRunDeleteTestRunDefaultResponse | LoadTestRunListTestRunsDefaultResponse - | LoadTestRunStopTestRunDefaultResponse + | LoadTestRunGetTestRunFileDefaultResponse + | LoadTestRunStopDefaultResponse | LoadTestRunListMetricNamespacesDefaultResponse | LoadTestRunListMetricDefinitionsDefaultResponse | LoadTestRunListMetricsDefaultResponse @@ -316,7 +407,16 @@ export function isUnexpected( | LoadTestRunCreateOrUpdateAppComponentsDefaultResponse | LoadTestRunGetAppComponentsDefaultResponse | LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse { + | LoadTestRunGetServerMetricsConfigDefaultResponse + | TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + | TestProfileAdministrationDeleteTestProfileDefaultResponse + | TestProfileAdministrationGetTestProfileDefaultResponse + | TestProfileAdministrationListTestProfilesDefaultResponse + | TestProfileRunAdministrationGetTestProfileRunDefaultResponse + | TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + | TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + | TestProfileRunAdministrationStopDefaultResponse + | TestProfileRunAdministrationListTestProfileRunsDefaultResponse { const lroOriginal = response.headers["x-ms-original-url"]; const url = new URL(lroOriginal ?? response.request.url); const method = response.request.method; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts index a102d07cb8..c44491cdab 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/models.ts @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -13,18 +15,28 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** + * Kind of test. + * + * Possible values: "URL", "JMX", "Locust" + */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ @@ -39,13 +51,19 @@ export interface PassFailCriteria { /** Pass fail metric */ export interface PassFailMetric { - /** The client metric on which the criteria should be applied. */ + /** + * The client metric on which the criteria should be applied. + * + * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" + */ clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests + * + * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFunc; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -57,15 +75,33 @@ export interface PassFailMetric { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ + /** + * Action taken after the threshold is met. Default is ‘continue’. + * + * Possible values: "continue", "stop" + */ action?: PFAction; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface Secret { /** The value of the secret for the respective type */ value?: string; - /** Type of secret */ + /** + * Type of secret + * + * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" + */ type?: SecretType; } @@ -73,18 +109,19 @@ export interface Secret { export interface CertificateMetadata { /** The value of the certificate for respective type */ value?: string; - /** Type of certificate */ + /** + * Type of certificate + * + * Possible values: "AKV_CERT_URI" + */ type?: CertificateType; /** Name of the certificate. */ name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -98,54 +135,61 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: Array; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; - /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; - /** Validation status of the file */ - validationStatus?: FileStatus; - /** Validation failure error details */ - validationFailureDetails?: string; -} - -/** Test app component */ + fileName: string; +} + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -155,15 +199,12 @@ export interface TestAppComponents { components: Record; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Kind of Azure resource type */ @@ -177,7 +218,7 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; + metrics: Record; } /** @@ -206,6 +247,8 @@ export interface ResourceMetric { export interface TestRun { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -226,6 +269,14 @@ export interface TestRun { testId?: string; /** The test run description. */ description?: string; + /** + * Request data collection level for test run + * + * Possible values: "NONE", "ERRORS" + */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; } /** Error details if there is any failure in load test run */ @@ -243,24 +294,44 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date | string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -299,60 +370,114 @@ export interface TestRunServerMetricConfig { metrics?: Record; } +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurations; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurationsParent { + kind: ResourceKind; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurationsParent { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 2048, 4096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; +} + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** + * Status of the test run. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** + * Category of the recommendation. + * + * Possible values: "ThroughputOptimized", "CostOptimized" + */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export type TargetResourceConfigurations = + | TargetResourceConfigurationsParent + | FunctionFlexConsumptionTargetResourceConfigurations; /** Alias for PFMetrics */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; +export type PFMetrics = string; /** Alias for PFAgFunc */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; +export type PFAgFunc = string; /** Alias for PFAction */ -export type PFAction = "continue" | "stop"; +export type PFAction = string; /** Alias for PFResult */ -export type PFResult = "passed" | "undetermined" | "failed"; +export type PFResult = string; /** Alias for SecretType */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretType = string; /** Alias for CertificateType */ -export type CertificateType = "AKV_CERT_URI"; +export type CertificateType = string; /** Alias for FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; +export type FileType = string; /** Alias for FileStatus */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; +export type FileStatus = string; +/** Alias for TestKind */ +export type TestKind = string; /** Alias for PFTestResult */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResult = string; /** Alias for Status */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Alias for Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type Status = string; +/** Alias for RequestDataLevel */ +export type RequestDataLevel = string; +/** Alias for TimeGrain */ +export type TimeGrain = string; +/** Alias for ResourceKind */ +export type ResourceKind = string; +/** Alias for TestProfileRunStatus */ +export type TestProfileRunStatus = string; +/** Alias for RecommendationCategory */ +export type RecommendationCategory = string; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts index 392e850e81..1d62e9319d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/outputModels.ts @@ -3,10 +3,12 @@ import { Paged } from "@azure/core-paging"; -/** Load test model */ +/** Load test model. */ export interface TestOutput { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -15,31 +17,41 @@ export interface TestOutput { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadataOutput; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifactsOutput; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** + * Kind of test. + * + * Possible values: "URL", "JMX", "Locust" + */ + kind?: TestKindOutput; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -53,13 +65,19 @@ export interface PassFailCriteriaOutput { /** Pass fail metric */ export interface PassFailMetricOutput { - /** The client metric on which the criteria should be applied. */ + /** + * The client metric on which the criteria should be applied. + * + * Possible values: "response_time_ms", "latency", "error", "requests", "requests_per_sec" + */ clientMetric?: PFMetricsOutput; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests + * + * Possible values: "count", "percentage", "avg", "p50", "p75", "p90", "p95", "p96", "p97", "p98", "p99", "p99.9", "p99.99", "min", "max" */ aggregate?: PFAgFuncOutput; /** The comparison operator. Supported types ‘>’, ‘<’ */ @@ -71,19 +89,41 @@ export interface PassFailMetricOutput { * 100.0] unit- % ’, response_time_ms and latency : any integer value unit- ms. */ value?: number; - /** Action taken after the threshold is met. Default is ‘continue’. */ + /** + * Action taken after the threshold is met. Default is ‘continue’. + * + * Possible values: "continue", "stop" + */ action?: PFActionOutput; /** The actual value of the client metric for the test run. */ readonly actualValue?: number; - /** Outcome of the test run. */ + /** + * Outcome of the test run. + * + * Possible values: "passed", "undetermined", "failed" + */ readonly result?: PFResultOutput; } +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteriaOutput { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + /** Secret */ export interface SecretOutput { /** The value of the secret for the respective type */ value?: string; - /** Type of secret */ + /** + * Type of secret + * + * Possible values: "AKV_SECRET_URI", "SECRET_VALUE" + */ type?: SecretTypeOutput; } @@ -91,18 +131,19 @@ export interface SecretOutput { export interface CertificateMetadataOutput { /** The value of the certificate for respective type */ value?: string; - /** Type of certificate */ + /** + * Type of certificate + * + * Possible values: "AKV_CERT_URI" + */ type?: CertificateTypeOutput; /** Name of the certificate. */ name?: string; } -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfigurationOutput { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -116,56 +157,81 @@ export interface LoadTestConfigurationOutput { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfigOutput; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: Array; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfigOutput { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfigurationOutput { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + /** The input artifacts for the test. */ export interface TestInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; } -/** File info */ -export interface FileInfoOutput { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfoOutput { /** Name of the file. */ - fileName?: string; - /** File type */ - fileType?: FileTypeOutput; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; - /** Validation status of the file */ - validationStatus?: FileStatusOutput; + fileName: string; + /** File URL. */ + readonly url?: string; + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; + /** + * Validation status of the file + * + * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" + */ + readonly validationStatus?: FileStatusOutput; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Test app component */ +/** Test app components */ export interface TestAppComponentsOutput { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -175,30 +241,24 @@ export interface TestAppComponentsOutput { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponentOutput { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -218,12 +278,12 @@ export interface TestServerMetricConfigOutput { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -255,10 +315,12 @@ export interface ResourceMetricOutput { /** Load test run model */ export interface TestRunOutput { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteriaOutput; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteriaOutput; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -273,13 +335,27 @@ export interface TestRunOutput { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: Array; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfigurationOutput; /** Collection of test run artifacts */ readonly testArtifacts?: TestRunArtifactsOutput; - /** Test result for pass/Fail criteria used during the test run. */ + /** + * Test result for pass/Fail criteria used during the test run. + * + * Possible values: "PASSED", "NOT_APPLICABLE", "FAILED" + */ readonly testResult?: PFTestResultOutput; /** Number of virtual users, for which test has been run. */ readonly virtualUsers?: number; @@ -289,11 +365,15 @@ export interface TestRunOutput { testId?: string; /** The test run description. */ description?: string; - /** The test run status. */ + /** + * The test run status. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ readonly status?: StatusOutput; - /** The test run start DateTime(ISO 8601 literal format). */ + /** The test run start DateTime(RFC 3339 literal format). */ readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ + /** The test run end DateTime(RFC 3339 literal format). */ readonly endDateTime?: string; /** Test run initiated time. */ readonly executedDateTime?: string; @@ -303,11 +383,27 @@ export interface TestRunOutput { readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** + * Type of test. + * + * Possible values: "URL", "JMX", "Locust" + */ + readonly kind?: TestKindOutput; + /** + * Request data collection level for test run + * + * Possible values: "NONE", "ERRORS" + */ + requestDataLevel?: RequestDataLevelOutput; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -343,6 +439,18 @@ export interface TestRunStatisticsOutput { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -362,23 +470,61 @@ export interface TestRunArtifactsOutput { /** The input artifacts for the test run. */ export interface TestRunInputArtifactsOutput { /** File info */ - configFileInfo?: FileInfoOutput; + configFileInfo?: TestRunFileInfoOutput; /** File info */ - testScriptFileInfo?: FileInfoOutput; + testScriptFileInfo?: TestRunFileInfoOutput; /** File info */ - userPropFileInfo?: FileInfoOutput; + userPropFileInfo?: TestRunFileInfoOutput; /** File info */ - inputArtifactsZipFileInfo?: FileInfoOutput; + inputArtifactsZipFileInfo?: TestRunFileInfoOutput; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfoOutput; /** Additional supported files for the test run */ - readonly additionalFileInfo?: Array; + readonly additionalFileInfo?: Array; +} + +/** Test run file info. */ +export interface TestRunFileInfoOutput { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ + readonly fileType?: FileTypeOutput; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: string; + /** + * Validation status of the file + * + * Possible values: "NOT_VALIDATED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE", "VALIDATION_INITIATED", "VALIDATION_NOT_REQUIRED" + */ + readonly validationStatus?: FileStatusOutput; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifactsOutput { /** File info */ - resultFileInfo?: FileInfoOutput; + resultFileInfo?: TestRunFileInfoOutput; /** File info */ - logsFileInfo?: FileInfoOutput; + logsFileInfo?: TestRunFileInfoOutput; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfoOutput; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfoOutput; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfoOutput { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: string; } /** Represents collection of metric namespaces. */ @@ -411,11 +557,19 @@ export interface MetricDefinitionOutput { name?: string; /** The namespace the metric belongs to. */ namespace?: string; - /** The primary aggregation type value defining how to use the values for display. */ + /** + * The primary aggregation type value defining how to use the values for display. + * + * Possible values: "Average", "Count", "None", "Total", "Percentile75", "Percentile90", "Percentile95", "Percentile96", "Percentile97", "Percentile98", "Percentile99", "Percentile999", "Percentile9999" + */ primaryAggregationType?: AggregationTypeOutput; /** The collection of what all aggregation types are supported. */ supportedAggregationTypes?: string[]; - /** The unit of the metric. */ + /** + * The unit of the metric. + * + * Possible values: "NotSpecified", "Percent", "Count", "Seconds", "Milliseconds", "Bytes", "BytesPerSecond", "CountPerSecond" + */ unit?: MetricUnitOutput; /** * Metric availability specifies the time grain (aggregation interval or @@ -437,6 +591,8 @@ export interface MetricAvailabilityOutput { /** * The time grain specifies the aggregation interval for the metric. Expressed as * a duration 'PT1M', 'PT1H', etc. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ timeGrain?: TimeGrainOutput; } @@ -451,7 +607,7 @@ export interface TimeSeriesElementOutput { /** Represents a metric value. */ export interface MetricValueOutput { - /** The timestamp for the metric value in ISO 8601 format. */ + /** The timestamp for the metric value in RFC 3339 format. */ timestamp?: string; /** The metric value. */ value?: number; @@ -465,8 +621,14 @@ export interface DimensionValueOutput { value?: string; } +/** Metrics dimension values. */ export interface DimensionValueListOutput { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Test run app component */ @@ -479,11 +641,11 @@ export interface TestRunAppComponentsOutput { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; @@ -499,102 +661,188 @@ export interface TestRunServerMetricConfigOutput { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: string; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: string; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfileOutput { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsOutput; + /** The creation datetime(RFC 3339 literal format). */ readonly createdDateTime?: string; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ + /** The last Modified datetime(RFC 3339 literal format). */ readonly lastModifiedDateTime?: string; /** The user that last modified. */ readonly lastModifiedBy?: string; } +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurationsOutputParent { + kind: ResourceKindOutput; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurationsOutput + extends TargetResourceConfigurationsOutputParent { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record< + string, + FunctionFlexConsumptionResourceConfigurationOutput + >; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfigurationOutput { + /** Memory size of the instance. Supported values are 2048, 4096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRunOutput { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsOutput; + /** + * The test profile run status. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "EXECUTING", "DONE", "CANCELLING", "CANCELLED", "FAILED" + */ + readonly status?: TestProfileRunStatusOutput; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: Array; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: string; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: string; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: Array; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: string; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: string; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetailOutput { + /** + * Status of the test run. + * + * Possible values: "ACCEPTED", "NOTSTARTED", "PROVISIONING", "PROVISIONED", "CONFIGURING", "CONFIGURED", "EXECUTING", "EXECUTED", "DEPROVISIONING", "DEPROVISIONED", "DONE", "CANCELLING", "CANCELLED", "FAILED", "VALIDATION_SUCCESS", "VALIDATION_FAILURE" + */ + status: StatusOutput; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendationOutput { + /** + * Category of the recommendation. + * + * Possible values: "ThroughputOptimized", "CostOptimized" + */ + category: RecommendationCategoryOutput; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export type TargetResourceConfigurationsOutput = + | TargetResourceConfigurationsOutputParent + | FunctionFlexConsumptionTargetResourceConfigurationsOutput; /** Alias for PFMetricsOutput */ -export type PFMetricsOutput = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; +export type PFMetricsOutput = string; /** Alias for PFAgFuncOutput */ -export type PFAgFuncOutput = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; +export type PFAgFuncOutput = string; /** Alias for PFActionOutput */ -export type PFActionOutput = "continue" | "stop"; +export type PFActionOutput = string; /** Alias for PFResultOutput */ -export type PFResultOutput = "passed" | "undetermined" | "failed"; +export type PFResultOutput = string; /** Alias for SecretTypeOutput */ -export type SecretTypeOutput = "AKV_SECRET_URI" | "SECRET_VALUE"; +export type SecretTypeOutput = string; /** Alias for CertificateTypeOutput */ -export type CertificateTypeOutput = "AKV_CERT_URI"; +export type CertificateTypeOutput = string; /** Alias for FileTypeOutput */ -export type FileTypeOutput = - | "JMX_FILE" - | "USER_PROPERTIES" - | "ADDITIONAL_ARTIFACTS"; +export type FileTypeOutput = string; /** Alias for FileStatusOutput */ -export type FileStatusOutput = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; -/** Collection of tests */ +export type FileStatusOutput = string; +/** Alias for TestKindOutput */ +export type TestKindOutput = string; +/** Paged collection of Test items */ export type PagedTestOutput = Paged; -/** Collection of files. */ -export type PagedFileInfoOutput = Paged; +/** Paged collection of TestFileInfo items */ +export type PagedTestFileInfoOutput = Paged; /** Alias for PFTestResultOutput */ -export type PFTestResultOutput = "PASSED" | "NOT_APPLICABLE" | "FAILED"; +export type PFTestResultOutput = string; /** Alias for StatusOutput */ -export type StatusOutput = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; -/** Collection of test runs */ +export type StatusOutput = string; +/** Alias for RequestDataLevelOutput */ +export type RequestDataLevelOutput = string; +/** Paged collection of TestRun items */ export type PagedTestRunOutput = Paged; /** Alias for AggregationTypeOutput */ -export type AggregationTypeOutput = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; +export type AggregationTypeOutput = string; /** Alias for MetricUnitOutput */ -export type MetricUnitOutput = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +export type MetricUnitOutput = string; /** Alias for TimeGrainOutput */ -export type TimeGrainOutput = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +export type TimeGrainOutput = string; /** The response to a metrics query. */ -export type PagedTimeSeriesElementOutput = Paged; -/** Paged collection of DimensionValueList items */ -export type PagedDimensionValueListOutput = Paged; +export type MetricsOutput = Paged; +/** Alias for ResourceKindOutput */ +export type ResourceKindOutput = string; +/** Paged collection of TestProfile items */ +export type PagedTestProfileOutput = Paged; +/** Alias for TestProfileRunStatusOutput */ +export type TestProfileRunStatusOutput = string; +/** Alias for RecommendationCategoryOutput */ +export type RecommendationCategoryOutput = string; +/** Paged collection of TestProfileRun items */ +export type PagedTestProfileRunOutput = Paged; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts index 9437426616..72c1d3b8d0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/parameters.ts @@ -8,21 +8,24 @@ import { TestAppComponents, TestServerMetricConfig, TestRun, - Interval, + TimeGrain, MetricRequestPayload, TestRunAppComponents, TestRunServerMetricConfig, + TestProfile, + TestProfileRun, } from "./models.js"; -/** Load test model */ +/** The resource instance. */ export type TestResourceMergeAndPatch = Partial; export interface LoadTestAdministrationCreateOrUpdateTestBodyParam { - /** Load test model */ + /** The resource instance. */ body: TestResourceMergeAndPatch; } export interface LoadTestAdministrationCreateOrUpdateTestMediaTypesParam { + /** This request has a JSON Merge Patch body. */ contentType: "application/merge-patch+json"; } @@ -45,16 +48,10 @@ export interface LoadTestAdministrationListTestsQueryParamProperties { * the search parameter can be Login. */ search?: string; - /** - * Start DateTime(ISO 8601 literal format) of the last updated time range to - * filter tests. - */ - lastModifiedStartTime?: string; - /** - * End DateTime(ISO 8601 literal format) of the last updated time range to filter - * tests. - */ - lastModifiedEndTime?: string; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter tests. */ + lastModifiedEndTime?: Date | string; /** Number of results in response. */ maxpagesize?: number; } @@ -80,7 +77,11 @@ export interface LoadTestAdministrationUploadTestFileBodyParam { } export interface LoadTestAdministrationUploadTestFileQueryParamProperties { - /** File type */ + /** + * File type + * + * Possible values: "JMX_FILE", "USER_PROPERTIES", "ADDITIONAL_ARTIFACTS", "ZIPPED_ARTIFACTS", "URL_TEST_CONFIG", "TEST_SCRIPT" + */ fileType?: FileType; } @@ -89,6 +90,7 @@ export interface LoadTestAdministrationUploadTestFileQueryParam { } export interface LoadTestAdministrationUploadTestFileMediaTypesParam { + /** Content type. */ contentType: "application/octet-stream"; } @@ -109,6 +111,7 @@ export interface LoadTestAdministrationCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestAdministrationCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -128,6 +131,7 @@ export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigBodyPara } export interface LoadTestAdministrationCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -137,7 +141,7 @@ export type LoadTestAdministrationCreateOrUpdateServerMetricsConfigParameters = RequestParameters; export type LoadTestAdministrationGetServerMetricsConfigParameters = RequestParameters; -export type LoadTestRunDeleteTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunParameters = RequestParameters; /** The resource instance. */ export type TestRunResourceMergeAndPatch = Partial; @@ -170,8 +174,7 @@ export type LoadTestRunCreateOrUpdateTestRunParameters = LoadTestRunCreateOrUpdateTestRunMediaTypesParam & LoadTestRunCreateOrUpdateTestRunBodyParam & RequestParameters; -export type LoadTestRunGetTestRunParameters = RequestParameters; -export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunDeleteTestRunParameters = RequestParameters; export interface LoadTestRunListTestRunsQueryParamProperties { /** @@ -187,10 +190,10 @@ export interface LoadTestRunListTestRunsQueryParamProperties { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date | string; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date | string; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -203,16 +206,17 @@ export interface LoadTestRunListTestRunsQueryParam { export type LoadTestRunListTestRunsParameters = LoadTestRunListTestRunsQueryParam & RequestParameters; -export type LoadTestRunStopTestRunParameters = RequestParameters; +export type LoadTestRunGetTestRunFileParameters = RequestParameters; +export type LoadTestRunStopParameters = RequestParameters; export type LoadTestRunListMetricNamespacesParameters = RequestParameters; export interface LoadTestRunListMetricDefinitionsQueryParamProperties { /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; + metricNamespace: string; } export interface LoadTestRunListMetricDefinitionsQueryParam { - queryParameters?: LoadTestRunListMetricDefinitionsQueryParamProperties; + queryParameters: LoadTestRunListMetricDefinitionsQueryParamProperties; } export type LoadTestRunListMetricDefinitionsParameters = @@ -220,27 +224,28 @@ export type LoadTestRunListMetricDefinitionsParameters = export interface LoadTestRunListMetricsBodyParam { /** Metric dimension filter */ - body: MetricRequestPayload; + body?: MetricRequestPayload; } export interface LoadTestRunListMetricsQueryParamProperties { /** The aggregation */ aggregation?: string; - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; + metricname: string; /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. + * The interval (i.e. timegrain) of the query. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ - timespan?: string; + interval?: TimeGrain; + /** Metric namespace to query metric definitions for. */ + metricNamespace: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricsQueryParam { - queryParameters?: LoadTestRunListMetricsQueryParamProperties; + queryParameters: LoadTestRunListMetricsQueryParamProperties; } export type LoadTestRunListMetricsParameters = @@ -249,17 +254,18 @@ export type LoadTestRunListMetricsParameters = RequestParameters; export interface LoadTestRunListMetricDimensionValuesQueryParamProperties { - /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; /** Metric name */ - metricName?: string; - /** Metric namespace to query metric definitions for. */ - metricNamespace: string; + metricname: string; /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. + * The interval (i.e. timegrain) of the query. + * + * Possible values: "PT5S", "PT10S", "PT1M", "PT5M", "PT1H" */ - timespan?: string; + interval?: TimeGrain; + /** Metric namespace to query metric definitions for. */ + metricNamespace: string; + /** The timespan of the query. It is a string with the following format 'startDateTime_ISO/endDateTime_ISO'. */ + timespan: string; } export interface LoadTestRunListMetricDimensionValuesQueryParam { @@ -278,6 +284,7 @@ export interface LoadTestRunCreateOrUpdateAppComponentsBodyParam { } export interface LoadTestRunCreateOrUpdateAppComponentsMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -296,6 +303,7 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam { } export interface LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam { + /** Content type. */ contentType: "application/merge-patch+json"; } @@ -303,5 +311,97 @@ export type LoadTestRunCreateOrUpdateServerMetricsConfigParameters = LoadTestRunCreateOrUpdateServerMetricsConfigMediaTypesParam & LoadTestRunCreateOrUpdateServerMetricsConfigBodyParam & RequestParameters; -export type LoadTestRunTestRunListServerMetricsConfigParameters = +export type LoadTestRunGetServerMetricsConfigParameters = RequestParameters; +/** The resource instance. */ +export type TestProfileResourceMergeAndPatch = Partial; + +export interface TestProfileAdministrationCreateOrUpdateTestProfileBodyParam { + /** The resource instance. */ + body: TestProfileResourceMergeAndPatch; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type TestProfileAdministrationCreateOrUpdateTestProfileParameters = + TestProfileAdministrationCreateOrUpdateTestProfileMediaTypesParam & + TestProfileAdministrationCreateOrUpdateTestProfileBodyParam & + RequestParameters; +export type TestProfileAdministrationDeleteTestProfileParameters = + RequestParameters; +export type TestProfileAdministrationGetTestProfileParameters = + RequestParameters; + +export interface TestProfileAdministrationListTestProfilesQueryParamProperties { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Start DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the last updated time range to filter test profiles. */ + lastModifiedEndTime?: Date | string; + /** Comma separated list of IDs of the test profiles to filter. */ + testProfileIds?: string; + /** Comma separated list IDs of the tests which should be associated with the test profiles to fetch. */ + testIds?: string; +} + +export interface TestProfileAdministrationListTestProfilesQueryParam { + queryParameters?: TestProfileAdministrationListTestProfilesQueryParamProperties; +} + +export type TestProfileAdministrationListTestProfilesParameters = + TestProfileAdministrationListTestProfilesQueryParam & RequestParameters; +export type TestProfileRunAdministrationGetTestProfileRunParameters = + RequestParameters; +/** The resource instance. */ +export type TestProfileRunResourceMergeAndPatch = Partial; + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam { + /** The resource instance. */ + body: TestProfileRunResourceMergeAndPatch; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type TestProfileRunAdministrationCreateOrUpdateTestProfileRunParameters = + TestProfileRunAdministrationCreateOrUpdateTestProfileRunMediaTypesParam & + TestProfileRunAdministrationCreateOrUpdateTestProfileRunBodyParam & + RequestParameters; +export type TestProfileRunAdministrationDeleteTestProfileRunParameters = RequestParameters; +export type TestProfileRunAdministrationStopParameters = RequestParameters; + +export interface TestProfileRunAdministrationListTestProfileRunsQueryParamProperties { + /** Maximum number of results to include in a single response. */ + maxpagesize?: number; + /** Minimum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minStartDateTime?: Date | string; + /** Maximum Start DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxStartDateTime?: Date | string; + /** Minimum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + minEndDateTime?: Date | string; + /** Maximum End DateTime(RFC 3339 literal format) of the test profile runs to filter on. */ + maxEndDateTime?: Date | string; + /** Start DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateStartTime?: Date | string; + /** End DateTime(RFC 3339 literal format) of the created time range to filter test profile runs. */ + createdDateEndTime?: Date | string; + /** Comma separated list of IDs of the test profile runs to filter. */ + testProfileRunIds?: string; + /** Comma separated IDs of the test profiles which should be associated with the test profile runs to fetch. */ + testProfileIds?: string; + /** Comma separated list of Statuses of the test profile runs to filter. */ + statuses?: string; +} + +export interface TestProfileRunAdministrationListTestProfileRunsQueryParam { + queryParameters?: TestProfileRunAdministrationListTestProfileRunsQueryParamProperties; +} + +export type TestProfileRunAdministrationListTestProfileRunsParameters = + TestProfileRunAdministrationListTestProfileRunsQueryParam & RequestParameters; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts deleted file mode 100644 index 19a90195ba..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/pollingHelper.ts +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { Client, HttpResponse } from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { - CancelOnProgress, - CreateHttpPollerOptions, - RunningOperation, - OperationResponse, - OperationState, - createHttpPoller, -} from "@azure/core-lro"; -import { - LoadTestRunCreateOrUpdateTestRun200Response, - LoadTestRunCreateOrUpdateTestRun201Response, - LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, -} from "./responses.js"; - -/** - * A simple poller that can be used to poll a long running operation. - */ -export interface SimplePollerLike< - TState extends OperationState, - TResult, -> { - /** - * Returns true if the poller has finished polling. - */ - isDone(): boolean; - /** - * Returns the state of the operation. - */ - getOperationState(): TState; - /** - * Returns the result value of the operation, - * regardless of the state of the poller. - * It can return undefined or an incomplete form of the final TResult value - * depending on the implementation. - */ - getResult(): TResult | undefined; - /** - * Returns a promise that will resolve once a single polling request finishes. - * It does this by calling the update method of the Poller's operation. - */ - poll(options?: { abortSignal?: AbortSignalLike }): Promise; - /** - * Returns a promise that will resolve once the underlying operation is completed. - */ - pollUntilDone(pollOptions?: { - abortSignal?: AbortSignalLike; - }): Promise; - /** - * Invokes the provided callback after each polling is completed, - * sending the current state of the poller's operation. - * - * It returns a method that can be used to stop receiving updates on the given callback function. - */ - onProgress(callback: (state: TState) => void): CancelOnProgress; - - /** - * Returns a promise that could be used for serialized version of the poller's operation - * by invoking the operation's serialize method. - */ - serialize(): Promise; - - /** - * Wait the poller to be submitted. - */ - submitted(): Promise; - - /** - * Returns a string representation of the poller's operation. Similar to serialize but returns a string. - * @deprecated Use serialize() instead. - */ - toString(): string; - - /** - * Stops the poller from continuing to poll. Please note this will only stop the client-side polling - * @deprecated Use abortSignal to stop polling instead. - */ - stopPolling(): void; - - /** - * Returns true if the poller is stopped. - * @deprecated Use abortSignal status to track this instead. - */ - isStopped(): boolean; -} - -/** - * Helper function that builds a Poller object to help polling a long running operation. - * @param client - Client to use for sending the request to get additional pages. - * @param initialResponse - The initial response. - * @param options - Options to set a resume state or custom polling interval. - * @returns - A poller object to poll for operation state updates and eventually get the final response. - */ -export async function getLongRunningPoller< - TResult extends - | LoadTestRunCreateOrUpdateTestRunLogicalResponse - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ->( - client: Client, - initialResponse: - | LoadTestRunCreateOrUpdateTestRun200Response - | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse, - options?: CreateHttpPollerOptions>, -): Promise, TResult>>; -export async function getLongRunningPoller( - client: Client, - initialResponse: TResult, - options: CreateHttpPollerOptions> = {}, -): Promise, TResult>> { - const abortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - // In the case of Rest Clients we are building the LRO poller object from a response that's the reason - // we are not triggering the initial request here, just extracting the information from the - // response we were provided. - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - pollOptions?: { abortSignal?: AbortSignalLike }, - ) => { - // This is the callback that is going to be called to poll the service - // to get the latest status. We use the client provided and the polling path - // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location - // depending on the lro pattern that the service implements. If non is provided we default to the initial path. - function abortListener(): void { - abortController.abort(); - } - const inputAbortSignal = pollOptions?.abortSignal; - const abortSignal = abortController.signal; - if (inputAbortSignal?.aborted) { - abortController.abort(); - } else if (!abortSignal.aborted) { - inputAbortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client - .pathUnchecked(path ?? initialResponse.request.url) - .get({ abortSignal }); - } finally { - inputAbortSignal?.removeEventListener("abort", abortListener); - } - const lroResponse = getLroResponse(response as TResult); - lroResponse.rawResponse.headers["x-ms-original-url"] = - initialResponse.request.url; - return lroResponse; - }, - }; - - options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; - const httpPoller = createHttpPoller(poller, options); - const simplePoller: SimplePollerLike, TResult> = { - isDone() { - return httpPoller.isDone; - }, - isStopped() { - return abortController.signal.aborted; - }, - getOperationState() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return httpPoller.operationState; - }, - getResult() { - return httpPoller.result; - }, - toString() { - if (!httpPoller.operationState) { - throw new Error( - "Operation state is not available. The poller may not have been started and you could await submitted() before calling getOperationState().", - ); - } - return JSON.stringify({ - state: httpPoller.operationState, - }); - }, - stopPolling() { - abortController.abort(); - }, - onProgress: httpPoller.onProgress, - poll: httpPoller.poll, - pollUntilDone: httpPoller.pollUntilDone, - serialize: httpPoller.serialize, - submitted: httpPoller.submitted, - }; - return simplePoller; -} - -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResult, -): OperationResponse { - if (Number.isNaN(response.status)) { - throw new TypeError( - `Status code of the response is not a number. Value: ${response.status}`, - ); - } - - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts index 2c79e0b52c..65d9fbf613 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/rest/responses.ts @@ -6,18 +6,23 @@ import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { TestOutput, PagedTestOutput, - FileInfoOutput, - PagedFileInfoOutput, + TestFileInfoOutput, + PagedTestFileInfoOutput, TestAppComponentsOutput, TestServerMetricConfigOutput, TestRunOutput, PagedTestRunOutput, + TestRunFileInfoOutput, MetricNamespaceCollectionOutput, MetricDefinitionCollectionOutput, - PagedTimeSeriesElementOutput, - PagedDimensionValueListOutput, + MetricsOutput, + DimensionValueListOutput, TestRunAppComponentsOutput, TestRunServerMetricConfigOutput, + TestProfileOutput, + PagedTestProfileOutput, + TestProfileRunOutput, + PagedTestProfileRunOutput, } from "./outputModels.js"; /** The request has succeeded. */ @@ -106,7 +111,7 @@ export interface LoadTestAdministrationListTestsDefaultResponse export interface LoadTestAdministrationUploadTestFile201Response extends HttpResponse { status: "201"; - body: FileInfoOutput; + body: TestFileInfoOutput; } export interface LoadTestAdministrationUploadTestFileDefaultHeaders { @@ -125,7 +130,7 @@ export interface LoadTestAdministrationUploadTestFileDefaultResponse export interface LoadTestAdministrationGetTestFile200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: TestFileInfoOutput; } export interface LoadTestAdministrationGetTestFileDefaultHeaders { @@ -162,7 +167,7 @@ export interface LoadTestAdministrationDeleteTestFileDefaultResponse export interface LoadTestAdministrationListTestFiles200Response extends HttpResponse { status: "200"; - body: PagedFileInfoOutput; + body: PagedTestFileInfoOutput; } export interface LoadTestAdministrationListTestFilesDefaultHeaders { @@ -271,25 +276,21 @@ export interface LoadTestAdministrationGetServerMetricsConfigDefaultResponse LoadTestAdministrationGetServerMetricsConfigDefaultHeaders; } -/** There is no content to send for this request, but the headers may be useful. */ -export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { - status: "204"; +/** The request has succeeded. */ +export interface LoadTestRunGetTestRun200Response extends HttpResponse { + status: "200"; + body: TestRunOutput; } -export interface LoadTestRunDeleteTestRunDefaultHeaders { +export interface LoadTestRunGetTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; -} - -export interface LoadTestRunCreateOrUpdateTestRun200Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; + headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; } /** The request has succeeded. */ @@ -297,12 +298,6 @@ export interface LoadTestRunCreateOrUpdateTestRun200Response extends HttpResponse { status: "200"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun200Headers; -} - -export interface LoadTestRunCreateOrUpdateTestRun201Headers { - /** The location for monitoring the operation state. */ - "operation-location": string; } /** The request has succeeded and a new resource has been created as a result. */ @@ -310,7 +305,6 @@ export interface LoadTestRunCreateOrUpdateTestRun201Response extends HttpResponse { status: "201"; body: TestRunOutput; - headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRun201Headers; } export interface LoadTestRunCreateOrUpdateTestRunDefaultHeaders { @@ -325,79 +319,71 @@ export interface LoadTestRunCreateOrUpdateTestRunDefaultResponse headers: RawHttpHeaders & LoadTestRunCreateOrUpdateTestRunDefaultHeaders; } -/** The final response for long-running CreateOrUpdateTestRun operation */ -export interface LoadTestRunCreateOrUpdateTestRunLogicalResponse - extends HttpResponse { - status: "200"; - body: TestRunOutput; -} - -/** The request has succeeded. */ -export interface LoadTestRunGetTestRun200Response extends HttpResponse { - status: "200"; - body: TestRunOutput; +/** There is no content to send for this request, but the headers may be useful. */ +export interface LoadTestRunDeleteTestRun204Response extends HttpResponse { + status: "204"; } -export interface LoadTestRunGetTestRunDefaultHeaders { +export interface LoadTestRunDeleteTestRunDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunDeleteTestRunDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunDeleteTestRunDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { +export interface LoadTestRunListTestRuns200Response extends HttpResponse { status: "200"; - body: FileInfoOutput; + body: PagedTestRunOutput; } -export interface LoadTestRunGetTestRunFileDefaultHeaders { +export interface LoadTestRunListTestRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { +export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunListTestRuns200Response extends HttpResponse { +export interface LoadTestRunGetTestRunFile200Response extends HttpResponse { status: "200"; - body: PagedTestRunOutput; + body: TestRunFileInfoOutput; } -export interface LoadTestRunListTestRunsDefaultHeaders { +export interface LoadTestRunGetTestRunFileDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunListTestRunsDefaultResponse extends HttpResponse { +export interface LoadTestRunGetTestRunFileDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunListTestRunsDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunGetTestRunFileDefaultHeaders; } /** The request has succeeded. */ -export interface LoadTestRunStopTestRun200Response extends HttpResponse { +export interface LoadTestRunStop200Response extends HttpResponse { status: "200"; body: TestRunOutput; } -export interface LoadTestRunStopTestRunDefaultHeaders { +export interface LoadTestRunStopDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunStopTestRunDefaultResponse extends HttpResponse { +export interface LoadTestRunStopDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & LoadTestRunStopTestRunDefaultHeaders; + headers: RawHttpHeaders & LoadTestRunStopDefaultHeaders; } /** The request has succeeded. */ @@ -441,7 +427,7 @@ export interface LoadTestRunListMetricDefinitionsDefaultResponse /** The request has succeeded. */ export interface LoadTestRunListMetrics200Response extends HttpResponse { status: "200"; - body: PagedTimeSeriesElementOutput; + body: MetricsOutput; } export interface LoadTestRunListMetricsDefaultHeaders { @@ -459,7 +445,7 @@ export interface LoadTestRunListMetricsDefaultResponse extends HttpResponse { export interface LoadTestRunListMetricDimensionValues200Response extends HttpResponse { status: "200"; - body: PagedDimensionValueListOutput; + body: DimensionValueListOutput; } export interface LoadTestRunListMetricDimensionValuesDefaultHeaders { @@ -547,21 +533,211 @@ export interface LoadTestRunCreateOrUpdateServerMetricsConfigDefaultResponse } /** The request has succeeded. */ -export interface LoadTestRunTestRunListServerMetricsConfig200Response +export interface LoadTestRunGetServerMetricsConfig200Response extends HttpResponse { status: "200"; body: TestRunServerMetricConfigOutput; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultHeaders { +export interface LoadTestRunGetServerMetricsConfigDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface LoadTestRunGetServerMetricsConfigDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & LoadTestRunGetServerMetricsConfigDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationCreateOrUpdateTestProfile200Response + extends HttpResponse { + status: "200"; + body: TestProfileOutput; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface TestProfileAdministrationCreateOrUpdateTestProfile201Response + extends HttpResponse { + status: "201"; + body: TestProfileOutput; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationCreateOrUpdateTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationCreateOrUpdateTestProfileDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface TestProfileAdministrationDeleteTestProfile204Response + extends HttpResponse { + status: "204"; +} + +export interface TestProfileAdministrationDeleteTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationDeleteTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationDeleteTestProfileDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationGetTestProfile200Response + extends HttpResponse { + status: "200"; + body: TestProfileOutput; +} + +export interface TestProfileAdministrationGetTestProfileDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationGetTestProfileDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationGetTestProfileDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileAdministrationListTestProfiles200Response + extends HttpResponse { + status: "200"; + body: PagedTestProfileOutput; +} + +export interface TestProfileAdministrationListTestProfilesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileAdministrationListTestProfilesDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileAdministrationListTestProfilesDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationGetTestProfileRun200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationGetTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationGetTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationGetTestProfileRunDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRun201Response + extends HttpResponse { + status: "201"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationCreateOrUpdateTestProfileRunDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface TestProfileRunAdministrationDeleteTestProfileRun204Response + extends HttpResponse { + status: "204"; +} + +export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationDeleteTestProfileRunDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & + TestProfileRunAdministrationDeleteTestProfileRunDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationStop200Response + extends HttpResponse { + status: "200"; + body: TestProfileRunOutput; +} + +export interface TestProfileRunAdministrationStopDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface TestProfileRunAdministrationStopDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & TestProfileRunAdministrationStopDefaultHeaders; +} + +/** The request has succeeded. */ +export interface TestProfileRunAdministrationListTestProfileRuns200Response + extends HttpResponse { + status: "200"; + body: PagedTestProfileRunOutput; +} + +export interface TestProfileRunAdministrationListTestProfileRunsDefaultHeaders { /** String error code indicating what went wrong. */ "x-ms-error-code"?: string; } -export interface LoadTestRunTestRunListServerMetricsConfigDefaultResponse +export interface TestProfileRunAdministrationListTestProfileRunsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & - LoadTestRunTestRunListServerMetricsConfigDefaultHeaders; + TestProfileRunAdministrationListTestProfileRunsDefaultHeaders; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts index d9fc4ff2ea..7332f1d3cc 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/index.ts @@ -9,6 +9,6 @@ export { } from "./operations.js"; export { createTestProfileAdministrationOperations, - TestProfileAdministrationOperationsClientOptions, + TestProfileAdministrationOperationsClientOptionalParams, LoadTestServiceContext, } from "./testProfileAdministrationOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts index 2f72fd93a3..800f8f4b82 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/api/testProfileAdministrationOperationsContext.ts @@ -7,7 +7,7 @@ import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ -export interface TestProfileAdministrationOperationsClientOptions +export interface TestProfileAdministrationOperationsClientOptionalParams extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; @@ -18,7 +18,7 @@ export { LoadTestServiceContext } from "../../rest/index.js"; export function createTestProfileAdministrationOperations( endpointParam: string, credential: TokenCredential, - options: TestProfileAdministrationOperationsClientOptions = {}, + options: TestProfileAdministrationOperationsClientOptionalParams = {}, ): LoadTestServiceContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts index 3068dc1e80..e380cf9d16 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/index.ts @@ -3,7 +3,7 @@ export { TestProfileAdministrationOperationsClient, - TestProfileAdministrationOperationsClientOptions, + TestProfileAdministrationOperationsClientOptionalParams, } from "./testProfileAdministrationOperationsClient.js"; export { Test, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts index 031cfd6334..610eca3007 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministrationOperations/testProfileAdministrationOperationsClient.ts @@ -17,11 +17,11 @@ import { getTestProfile, listTestProfiles, createTestProfileAdministrationOperations, - TestProfileAdministrationOperationsClientOptions, + TestProfileAdministrationOperationsClientOptionalParams, LoadTestServiceContext, } from "./api/index.js"; -export { TestProfileAdministrationOperationsClientOptions } from "./api/testProfileAdministrationOperationsContext.js"; +export { TestProfileAdministrationOperationsClientOptionalParams } from "./api/testProfileAdministrationOperationsContext.js"; export class TestProfileAdministrationOperationsClient { private _client: LoadTestServiceContext; @@ -31,7 +31,7 @@ export class TestProfileAdministrationOperationsClient { constructor( endpointParam: string, credential: TokenCredential, - options: TestProfileAdministrationOperationsClientOptions = {}, + options: TestProfileAdministrationOperationsClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts index 5acd70fe5d..f8235271a6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/index.ts @@ -10,6 +10,6 @@ export { } from "./operations.js"; export { createTestProfileRunOperations, - TestProfileRunOperationsClientOptions, + TestProfileRunOperationsClientOptionalParams, LoadTestServiceContext, } from "./testProfileRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts index ae4e5f3036..c55e1f96b2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/api/testProfileRunOperationsContext.ts @@ -7,7 +7,8 @@ import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ -export interface TestProfileRunOperationsClientOptions extends ClientOptions { +export interface TestProfileRunOperationsClientOptionalParams + extends ClientOptions { /** The API version to use for this operation. */ apiVersion?: string; } @@ -17,7 +18,7 @@ export { LoadTestServiceContext } from "../../rest/index.js"; export function createTestProfileRunOperations( endpointParam: string, credential: TokenCredential, - options: TestProfileRunOperationsClientOptions = {}, + options: TestProfileRunOperationsClientOptionalParams = {}, ): LoadTestServiceContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts index 72b3603320..340d0257c3 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/index.ts @@ -3,7 +3,7 @@ export { TestProfileRunOperationsClient, - TestProfileRunOperationsClientOptions, + TestProfileRunOperationsClientOptionalParams, } from "./testProfileRunOperationsClient.js"; export { Test, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts index 21bd8823dd..f6957bbfe2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRunOperations/testProfileRunOperationsClient.ts @@ -19,11 +19,11 @@ import { listTestProfileRuns, stop, createTestProfileRunOperations, - TestProfileRunOperationsClientOptions, + TestProfileRunOperationsClientOptionalParams, LoadTestServiceContext, } from "./api/index.js"; -export { TestProfileRunOperationsClientOptions } from "./api/testProfileRunOperationsContext.js"; +export { TestProfileRunOperationsClientOptionalParams } from "./api/testProfileRunOperationsContext.js"; export class TestProfileRunOperationsClient { private _client: LoadTestServiceContext; @@ -33,7 +33,7 @@ export class TestProfileRunOperationsClient { constructor( endpointParam: string, credential: TokenCredential, - options: TestProfileRunOperationsClientOptions = {}, + options: TestProfileRunOperationsClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts index 4822ef0017..175c9deb90 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. export { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -15,10 +15,10 @@ export { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, } from "./operations.js"; export { createTestRunOperations, TestRunOperationsClientOptionalParams, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./testRunOperationsContext.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts index 728e5a3ad8..ffd48f173b 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/operations.ts @@ -1,18 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { getLongRunningPoller } from "./pollingHelpers.js"; -import { PollerLike, OperationState } from "@azure/core-lro"; import { passFailCriteriaSerializer, + autoStopCriteriaSerializer, secretSerializer, certificateMetadataSerializer, loadTestConfigurationSerializer, appComponentSerializer, resourceMetricSerializer, dimensionFilterSerializer, - FileInfo, TestRun, + TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -20,15 +19,13 @@ import { MetricNamespaceCollection, MetricRequestPayload, TimeSeriesElement, - _PagedDimensionValueList, + _Metrics, _PagedTestRun, - _PagedTimeSeriesElement, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, - AzureLoadTestingContext as Client, LoadTestRunCreateOrUpdateAppComponents200Response, LoadTestRunCreateOrUpdateAppComponents201Response, LoadTestRunCreateOrUpdateAppComponentsDefaultResponse, @@ -38,11 +35,12 @@ import { LoadTestRunCreateOrUpdateTestRun200Response, LoadTestRunCreateOrUpdateTestRun201Response, LoadTestRunCreateOrUpdateTestRunDefaultResponse, - LoadTestRunCreateOrUpdateTestRunLogicalResponse, LoadTestRunDeleteTestRun204Response, LoadTestRunDeleteTestRunDefaultResponse, LoadTestRunGetAppComponents200Response, LoadTestRunGetAppComponentsDefaultResponse, + LoadTestRunGetServerMetricsConfig200Response, + LoadTestRunGetServerMetricsConfigDefaultResponse, LoadTestRunGetTestRun200Response, LoadTestRunGetTestRunDefaultResponse, LoadTestRunGetTestRunFile200Response, @@ -57,10 +55,9 @@ import { LoadTestRunListMetricsDefaultResponse, LoadTestRunListTestRuns200Response, LoadTestRunListTestRunsDefaultResponse, - LoadTestRunStopTestRun200Response, - LoadTestRunStopTestRunDefaultResponse, - LoadTestRunTestRunListServerMetricsConfig200Response, - LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + LoadTestRunStop200Response, + LoadTestRunStopDefaultResponse, + LoadTestServiceContext as Client, } from "../../rest/index.js"; import { StreamableMethod, @@ -69,7 +66,7 @@ import { } from "@azure-rest/core-client"; import { serializeRecord } from "../../helpers/serializerHelpers.js"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -82,19 +79,18 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "../models/options.js"; -export function _testRunSend( +export function _createOrUpdateTestRunSend( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse > { return context .path("/test-runs/{testRunId}", testRunId) @@ -104,45 +100,56 @@ export function _testRunSend( (options.contentType as any) ?? "application/merge-patch+json", queryParameters: { oldTestRunId: options?.oldTestRunId }, body: { - passFailCriteria: !resource.passFailCriteria - ? resource.passFailCriteria - : passFailCriteriaSerializer(resource.passFailCriteria), - secrets: !resource.secrets - ? resource.secrets - : (serializeRecord(resource.secrets as any, secretSerializer) as any), - certificate: !resource.certificate - ? resource.certificate - : certificateMetadataSerializer(resource.certificate), - environmentVariables: !resource.environmentVariables - ? resource.environmentVariables - : (serializeRecord(resource.environmentVariables as any) as any), - loadTestConfiguration: !resource.loadTestConfiguration - ? resource.loadTestConfiguration - : loadTestConfigurationSerializer(resource.loadTestConfiguration), - displayName: resource["displayName"], - testId: resource["testId"], - description: resource["description"], + passFailCriteria: !body.passFailCriteria + ? body.passFailCriteria + : passFailCriteriaSerializer(body.passFailCriteria), + autoStopCriteria: !body.autoStopCriteria + ? body.autoStopCriteria + : autoStopCriteriaSerializer(body.autoStopCriteria), + secrets: !body.secrets + ? body.secrets + : (serializeRecord(body.secrets as any, secretSerializer) as any), + certificate: !body.certificate + ? body.certificate + : certificateMetadataSerializer(body.certificate), + environmentVariables: !body.environmentVariables + ? body.environmentVariables + : (serializeRecord(body.environmentVariables as any) as any), + loadTestConfiguration: !body.loadTestConfiguration + ? body.loadTestConfiguration + : loadTestConfigurationSerializer(body.loadTestConfiguration), + displayName: body["displayName"], + testId: body["testId"], + description: body["description"], + requestDataLevel: body["requestDataLevel"], + debugLogsEnabled: body["debugLogsEnabled"], }, }); } -export async function _testRunDeserialize( +export async function _createOrUpdateTestRunDeserialize( result: | LoadTestRunCreateOrUpdateTestRun200Response | LoadTestRunCreateOrUpdateTestRun201Response - | LoadTestRunCreateOrUpdateTestRunDefaultResponse - | LoadTestRunCreateOrUpdateTestRunLogicalResponse, + | LoadTestRunCreateOrUpdateTestRunDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); } - result = result as LoadTestRunCreateOrUpdateTestRunLogicalResponse; return { testRunId: result.body["testRunId"], passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -159,6 +166,7 @@ export async function _testRunDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -174,6 +182,14 @@ export async function _testRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -187,6 +203,18 @@ export async function _testRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -198,17 +226,22 @@ export async function _testRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -220,17 +253,22 @@ export async function _testRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -242,17 +280,22 @@ export async function _testRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -264,17 +307,23 @@ export async function _testRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -284,6 +333,34 @@ export async function _testRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -295,10 +372,13 @@ export async function _testRunDeserialize( "additionalFileInfo" ].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -312,17 +392,22 @@ export async function _testRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -334,17 +419,22 @@ export async function _testRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -352,6 +442,49 @@ export async function _testRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationFailureDetails"], + }, }, }, testResult: result.body["testResult"], @@ -360,32 +493,52 @@ export async function _testRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Create and start a new test run with the given name. */ -export function testRun( +/** Create and start a new test run with the given test run Id. */ +export async function createOrUpdateTestRun( context: Client, testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, -): PollerLike, TestRun> { - return getLongRunningPoller(context, _testRunDeserialize, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _testRunSend(context, testRunId, resource, options), - }) as PollerLike, TestRun>; + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestRunSend( + context, + testRunId, + body, + options, + ); + return _createOrUpdateTestRunDeserialize(result); } export function _createOrUpdateAppComponentsSend( @@ -426,14 +579,20 @@ export async function _createOrUpdateAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Associate an app component (collection of azure resources) to a test run */ +/** Add an app component to a test run by providing the resource Id, name and type. */ export async function createOrUpdateAppComponents( context: Client, testRunId: string, @@ -491,9 +650,15 @@ export async function _createOrUpdateServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -540,7 +705,7 @@ export async function _deleteTestRunDeserialize( return; } -/** Delete a test run by its name. */ +/** Delete an existing load test run by providing the testRunId. */ export async function deleteTestRun( context: Client, testRunId: string, @@ -575,9 +740,15 @@ export async function _getAppComponentsDeserialize( return { components: result.body["components"], testRunId: result.body["testRunId"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } @@ -600,8 +771,8 @@ export function _getServerMetricsConfigSend( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod< - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse > { return context .path("/test-runs/{testRunId}/server-metrics-config", testRunId) @@ -610,8 +781,8 @@ export function _getServerMetricsConfigSend( export async function _getServerMetricsConfigDeserialize( result: - | LoadTestRunTestRunListServerMetricsConfig200Response - | LoadTestRunTestRunListServerMetricsConfigDefaultResponse, + | LoadTestRunGetServerMetricsConfig200Response + | LoadTestRunGetServerMetricsConfigDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -620,14 +791,20 @@ export async function _getServerMetricsConfigDeserialize( return { testRunId: result.body["testRunId"], metrics: result.body["metrics"], - createdDateTime: result.body["createdDateTime"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** List server metrics configuration for the given test run. */ +/** Get associated server metrics configuration for the given test run. */ export async function getServerMetricsConfig( context: Client, testRunId: string, @@ -663,6 +840,14 @@ export async function _getTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -679,6 +864,7 @@ export async function _getTestRunDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -694,6 +880,14 @@ export async function _getTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -707,6 +901,18 @@ export async function _getTestRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -718,17 +924,22 @@ export async function _getTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -740,17 +951,22 @@ export async function _getTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -762,17 +978,22 @@ export async function _getTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -784,17 +1005,23 @@ export async function _getTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -804,6 +1031,34 @@ export async function _getTestRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -815,10 +1070,13 @@ export async function _getTestRunDeserialize( "additionalFileInfo" ].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -832,17 +1090,22 @@ export async function _getTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -854,17 +1117,22 @@ export async function _getTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -872,6 +1140,49 @@ export async function _getTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationFailureDetails"], + }, }, }, testResult: result.body["testResult"], @@ -880,20 +1191,39 @@ export async function _getTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Get test run details by name. */ +/** Get test run details by test run Id. */ export async function getTestRun( context: Client, testRunId: string, @@ -921,16 +1251,19 @@ export async function _getTestRunFileDeserialize( result: | LoadTestRunGetTestRunFile200Response | LoadTestRunGetTestRunFileDefaultResponse, -): Promise { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - url: result.body["url"], fileName: result.body["fileName"], + url: result.body["url"], fileType: result.body["fileType"], - expireDateTime: result.body["expireDateTime"], + expireDateTime: + result.body["expireDateTime"] !== undefined + ? new Date(result.body["expireDateTime"]) + : undefined, validationStatus: result.body["validationStatus"], validationFailureDetails: result.body["validationFailureDetails"], }; @@ -942,7 +1275,7 @@ export async function getTestRunFile( testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, -): Promise { +): Promise { const result = await _getTestRunFileSend( context, testRunId, @@ -956,7 +1289,9 @@ export function _listMetricDimensionValuesSend( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDimensionValues200Response @@ -971,10 +1306,10 @@ export function _listMetricDimensionValuesSend( .get({ ...operationOptionsToRequestParameters(options), queryParameters: { + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, metricNamespace: metricNamespace, - timespan: options?.timespan, + timespan: timespan, }, }); } @@ -983,45 +1318,44 @@ export async function _listMetricDimensionValuesDeserialize( result: | LoadTestRunListMetricDimensionValues200Response | LoadTestRunListMetricDimensionValuesDefaultResponse, -): Promise<_PagedDimensionValueList> { +): Promise { if (isUnexpected(result)) { throw createRestError(result); } return { - value: result.body["value"].map((p) => { - return { value: p["value"] }; - }), + name: result.body["name"], + value: result.body["value"], nextLink: result.body["nextLink"], }; } /** List the dimension values for the given metric dimension name. */ -export function listMetricDimensionValues( +export async function listMetricDimensionValues( context: Client, testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( +): Promise { + const result = await _listMetricDimensionValuesSend( context, - () => - _listMetricDimensionValuesSend( - context, - testRunId, - name, - metricNamespace, - options, - ), - _listMetricDimensionValuesDeserialize, - { itemName: "value", nextLinkName: "nextLink" }, + testRunId, + name, + metricname, + metricNamespace, + timespan, + options, ); + return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod< | LoadTestRunListMetricDefinitions200Response @@ -1031,7 +1365,7 @@ export function _listMetricDefinitionsSend( .path("/test-runs/{testRunId}/metric-definitions", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: options?.metricNamespace }, + queryParameters: { metricNamespace: metricNamespace }, }); } @@ -1074,9 +1408,15 @@ export async function _listMetricDefinitionsDeserialize( export async function listMetricDefinitions( context: Client, testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _listMetricDefinitionsSend(context, testRunId, options); + const result = await _listMetricDefinitionsSend( + context, + testRunId, + metricNamespace, + options, + ); return _listMetricDefinitionsDeserialize(result); } @@ -1122,7 +1462,10 @@ export async function listMetricNamespaces( export function _listMetricsSend( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod< LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse @@ -1133,17 +1476,20 @@ export function _listMetricsSend( ...operationOptionsToRequestParameters(options), queryParameters: { aggregation: options?.aggregation, + metricname: metricname, interval: options?.interval, - metricName: options?.metricName, - metricNamespace: options?.metricNamespace, - timespan: options?.timespan, - }, - body: { - filters: - body["filters"] === undefined - ? body["filters"] - : body["filters"].map(dimensionFilterSerializer), + metricNamespace: metricNamespace, + timespan: timespan, }, + body: + body === undefined + ? body + : { + filters: + body["filters"] === undefined + ? body["filters"] + : body["filters"].map(dimensionFilterSerializer), + }, }); } @@ -1151,7 +1497,7 @@ export async function _listMetricsDeserialize( result: | LoadTestRunListMetrics200Response | LoadTestRunListMetricsDefaultResponse, -): Promise<_PagedTimeSeriesElement> { +): Promise<_Metrics> { if (isUnexpected(result)) { throw createRestError(result); } @@ -1163,7 +1509,13 @@ export async function _listMetricsDeserialize( p["data"] === undefined ? p["data"] : p["data"].map((p) => { - return { timestamp: p["timestamp"], value: p["value"] }; + return { + timestamp: + p["timestamp"] !== undefined + ? new Date(p["timestamp"]) + : undefined, + value: p["value"], + }; }), dimensionValues: p["dimensionValues"] === undefined @@ -1181,12 +1533,24 @@ export async function _listMetricsDeserialize( export function listMetrics( context: Client, testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listMetricsSend(context, testRunId, body, options), + () => + _listMetricsSend( + context, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ), _listMetricsDeserialize, { itemName: "value", nextLinkName: "nextLink" }, ); @@ -1206,8 +1570,8 @@ export function _listTestRunsSend( orderby: options?.orderby, search: options?.search, testId: options?.testId, - executionFrom: options?.executionFrom, - executionTo: options?.executionTo, + executionFrom: options?.executionFrom?.toISOString(), + executionTo: options?.executionTo?.toISOString(), status: options?.status, maxpagesize: options?.maxpagesize, }, @@ -1230,6 +1594,14 @@ export async function _listTestRunsDeserialize( passFailCriteria: !p.passFailCriteria ? undefined : { passFailMetrics: p.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !p.autoStopCriteria + ? undefined + : { + autoStopDisabled: p.autoStopCriteria?.["autoStopDisabled"], + errorRate: p.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + p.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: p["secrets"], certificate: !p.certificate ? undefined @@ -1246,6 +1618,7 @@ export async function _listTestRunsDeserialize( return { message: p["message"] }; }), testRunStatistics: p["testRunStatistics"], + regionalStatistics: p["regionalStatistics"], loadTestConfiguration: !p.loadTestConfiguration ? undefined : { @@ -1260,6 +1633,14 @@ export async function _listTestRunsDeserialize( p.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + p.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: p.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1273,6 +1654,18 @@ export async function _listTestRunsDeserialize( "duration" ], }, + regionalLoadTestConfig: + p.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? p.loadTestConfiguration?.["regionalLoadTestConfig"] + : p.loadTestConfiguration?.["regionalLoadTestConfig"].map( + (p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }, + ), }, testArtifacts: !p.testArtifacts ? undefined @@ -1284,12 +1677,12 @@ export async function _listTestRunsDeserialize( ?.configFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileName" ], + url: p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "fileType" @@ -1297,7 +1690,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.configFileInfo?.[ "validationStatus" @@ -1311,17 +1709,23 @@ export async function _listTestRunsDeserialize( ?.testScriptFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1335,12 +1739,12 @@ export async function _listTestRunsDeserialize( ?.userPropFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileName" ], + url: p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "fileType" @@ -1348,7 +1752,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts?.userPropFileInfo?.[ "validationStatus" @@ -1362,17 +1771,26 @@ export async function _listTestRunsDeserialize( ?.inputArtifactsZipFileInfo ? undefined : { - url: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: p.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.[ + "expireDateTime" + ], + ) + : undefined, validationStatus: p.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1382,6 +1800,36 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + p.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.[ + "validationFailureDetails" + ], + }, additionalFileInfo: p.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1393,10 +1841,13 @@ export async function _listTestRunsDeserialize( "additionalFileInfo" ].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1410,12 +1861,12 @@ export async function _listTestRunsDeserialize( ?.resultFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileName" ], + url: p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "fileType" @@ -1423,7 +1874,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.resultFileInfo?.[ "validationStatus" @@ -1437,13 +1893,13 @@ export async function _listTestRunsDeserialize( ?.logsFileInfo ? undefined : { - url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ - "url" - ], fileName: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileName" ], + url: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ + "url" + ], fileType: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "fileType" @@ -1451,7 +1907,12 @@ export async function _listTestRunsDeserialize( expireDateTime: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "expireDateTime" - ], + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: p.testArtifacts?.outputArtifacts?.logsFileInfo?.[ "validationStatus" @@ -1461,6 +1922,56 @@ export async function _listTestRunsDeserialize( "validationFailureDetails" ], }, + artifactsContainerInfo: !p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo + ? undefined + : { + url: p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.[ + "expireDateTime" + ], + ) + : undefined, + }, + reportFileInfo: !p.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "fileName" + ], + url: p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "fileType" + ], + expireDateTime: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "expireDateTime" + ] !== undefined + ? new Date( + p.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "validationStatus" + ], + validationFailureDetails: + p.testArtifacts?.outputArtifacts?.reportFileInfo?.[ + "validationFailureDetails" + ], + }, }, }, testResult: p["testResult"], @@ -1469,15 +1980,34 @@ export async function _listTestRunsDeserialize( testId: p["testId"], description: p["description"], status: p["status"], - startDateTime: p["startDateTime"], - endDateTime: p["endDateTime"], - executedDateTime: p["executedDateTime"], + startDateTime: + p["startDateTime"] !== undefined + ? new Date(p["startDateTime"]) + : undefined, + endDateTime: + p["endDateTime"] !== undefined + ? new Date(p["endDateTime"]) + : undefined, + executedDateTime: + p["executedDateTime"] !== undefined + ? new Date(p["executedDateTime"]) + : undefined, portalUrl: p["portalUrl"], duration: p["duration"], subnetId: p["subnetId"], - createdDateTime: p["createdDateTime"], + kind: p["kind"], + requestDataLevel: p["requestDataLevel"], + debugLogsEnabled: p["debugLogsEnabled"], + publicIPDisabled: p["publicIPDisabled"], + createdDateTime: + p["createdDateTime"] !== undefined + ? new Date(p["createdDateTime"]) + : undefined, createdBy: p["createdBy"], - lastModifiedDateTime: p["lastModifiedDateTime"], + lastModifiedDateTime: + p["lastModifiedDateTime"] !== undefined + ? new Date(p["lastModifiedDateTime"]) + : undefined, lastModifiedBy: p["lastModifiedBy"], }; }), @@ -1485,7 +2015,7 @@ export async function _listTestRunsDeserialize( }; } -/** Get all test runs with given filters */ +/** Get all test runs for the given filters. */ export function listTestRuns( context: Client, options: ListTestRunsOptionalParams = { requestOptions: {} }, @@ -1498,22 +2028,20 @@ export function listTestRuns( ); } -export function _stopTestRunSend( +export function _stopSend( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): StreamableMethod< - LoadTestRunStopTestRun200Response | LoadTestRunStopTestRunDefaultResponse + LoadTestRunStop200Response | LoadTestRunStopDefaultResponse > { return context .path("/test-runs/{testRunId}:stop", testRunId) .post({ ...operationOptionsToRequestParameters(options) }); } -export async function _stopTestRunDeserialize( - result: - | LoadTestRunStopTestRun200Response - | LoadTestRunStopTestRunDefaultResponse, +export async function _stopDeserialize( + result: LoadTestRunStop200Response | LoadTestRunStopDefaultResponse, ): Promise { if (isUnexpected(result)) { throw createRestError(result); @@ -1524,6 +2052,14 @@ export async function _stopTestRunDeserialize( passFailCriteria: !result.body.passFailCriteria ? undefined : { passFailMetrics: result.body.passFailCriteria?.["passFailMetrics"] }, + autoStopCriteria: !result.body.autoStopCriteria + ? undefined + : { + autoStopDisabled: result.body.autoStopCriteria?.["autoStopDisabled"], + errorRate: result.body.autoStopCriteria?.["errorRate"], + errorRateTimeWindowInSeconds: + result.body.autoStopCriteria?.["errorRateTimeWindowInSeconds"], + }, secrets: result.body["secrets"], certificate: !result.body.certificate ? undefined @@ -1540,6 +2076,7 @@ export async function _stopTestRunDeserialize( return { message: p["message"] }; }), testRunStatistics: result.body["testRunStatistics"], + regionalStatistics: result.body["regionalStatistics"], loadTestConfiguration: !result.body.loadTestConfiguration ? undefined : { @@ -1555,6 +2092,14 @@ export async function _stopTestRunDeserialize( result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "endpointUrl" ], + requestsPerSecond: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "requestsPerSecond" + ], + maxResponseTimeInMs: + result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ + "maxResponseTimeInMs" + ], virtualUsers: result.body.loadTestConfiguration?.optionalLoadTestConfig?.[ "virtualUsers" @@ -1568,6 +2113,18 @@ export async function _stopTestRunDeserialize( "duration" ], }, + regionalLoadTestConfig: + result.body.loadTestConfiguration?.["regionalLoadTestConfig"] === + undefined + ? result.body.loadTestConfiguration?.["regionalLoadTestConfig"] + : result.body.loadTestConfiguration?.[ + "regionalLoadTestConfig" + ].map((p) => { + return { + engineInstances: p["engineInstances"], + region: p["region"], + }; + }), }, testArtifacts: !result.body.testArtifacts ? undefined @@ -1579,17 +2136,22 @@ export async function _stopTestRunDeserialize( ?.configFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.configFileInfo?.["expireDateTime"], + ?.configFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.configFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.configFileInfo?.["validationStatus"], @@ -1601,17 +2163,22 @@ export async function _stopTestRunDeserialize( ?.testScriptFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.testScriptFileInfo?.["expireDateTime"], + ?.testScriptFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.testScriptFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.testScriptFileInfo?.["validationStatus"], @@ -1623,17 +2190,22 @@ export async function _stopTestRunDeserialize( ?.userPropFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.userPropFileInfo?.["expireDateTime"], + ?.userPropFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.userPropFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.userPropFileInfo?.["validationStatus"], @@ -1645,17 +2217,23 @@ export async function _stopTestRunDeserialize( ?.inputArtifacts?.inputArtifactsZipFileInfo ? undefined : { - url: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["url"], fileName: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["url"], fileType: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.inputArtifacts - ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ?.inputArtifactsZipFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.inputArtifactsZipFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.inputArtifacts ?.inputArtifactsZipFileInfo?.["validationStatus"], @@ -1665,6 +2243,34 @@ export async function _stopTestRunDeserialize( "validationFailureDetails" ], }, + urlTestConfigFileInfo: !result.body.testArtifacts + ?.inputArtifacts?.urlTestConfigFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileName"], + url: result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["url"], + fileType: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.inputArtifacts + ?.urlTestConfigFileInfo?.["validationFailureDetails"], + }, additionalFileInfo: result.body.testArtifacts?.inputArtifacts?.[ "additionalFileInfo" @@ -1676,10 +2282,13 @@ export async function _stopTestRunDeserialize( "additionalFileInfo" ].map((p) => { return { - url: p["url"], fileName: p["fileName"], + url: p["url"], fileType: p["fileType"], - expireDateTime: p["expireDateTime"], + expireDateTime: + p["expireDateTime"] !== undefined + ? new Date(p["expireDateTime"]) + : undefined, validationStatus: p["validationStatus"], validationFailureDetails: p["validationFailureDetails"], @@ -1693,17 +2302,22 @@ export async function _stopTestRunDeserialize( ?.resultFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.resultFileInfo?.["expireDateTime"], + ?.resultFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.resultFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.resultFileInfo?.["validationStatus"], @@ -1715,17 +2329,22 @@ export async function _stopTestRunDeserialize( ?.logsFileInfo ? undefined : { - url: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["url"], fileName: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["url"], fileType: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["fileType"], expireDateTime: result.body.testArtifacts?.outputArtifacts - ?.logsFileInfo?.["expireDateTime"], + ?.logsFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.logsFileInfo?.["expireDateTime"], + ) + : undefined, validationStatus: result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationStatus"], @@ -1733,6 +2352,49 @@ export async function _stopTestRunDeserialize( result.body.testArtifacts?.outputArtifacts ?.logsFileInfo?.["validationFailureDetails"], }, + artifactsContainerInfo: !result.body.testArtifacts + ?.outputArtifacts?.artifactsContainerInfo + ? undefined + : { + url: result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["url"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"] !== + undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.artifactsContainerInfo?.["expireDateTime"], + ) + : undefined, + }, + reportFileInfo: !result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo + ? undefined + : { + fileName: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileName"], + url: result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["url"], + fileType: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["fileType"], + expireDateTime: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"] !== undefined + ? new Date( + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["expireDateTime"], + ) + : undefined, + validationStatus: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationStatus"], + validationFailureDetails: + result.body.testArtifacts?.outputArtifacts + ?.reportFileInfo?.["validationFailureDetails"], + }, }, }, testResult: result.body["testResult"], @@ -1741,25 +2403,44 @@ export async function _stopTestRunDeserialize( testId: result.body["testId"], description: result.body["description"], status: result.body["status"], - startDateTime: result.body["startDateTime"], - endDateTime: result.body["endDateTime"], - executedDateTime: result.body["executedDateTime"], + startDateTime: + result.body["startDateTime"] !== undefined + ? new Date(result.body["startDateTime"]) + : undefined, + endDateTime: + result.body["endDateTime"] !== undefined + ? new Date(result.body["endDateTime"]) + : undefined, + executedDateTime: + result.body["executedDateTime"] !== undefined + ? new Date(result.body["executedDateTime"]) + : undefined, portalUrl: result.body["portalUrl"], duration: result.body["duration"], subnetId: result.body["subnetId"], - createdDateTime: result.body["createdDateTime"], + kind: result.body["kind"], + requestDataLevel: result.body["requestDataLevel"], + debugLogsEnabled: result.body["debugLogsEnabled"], + publicIPDisabled: result.body["publicIPDisabled"], + createdDateTime: + result.body["createdDateTime"] !== undefined + ? new Date(result.body["createdDateTime"]) + : undefined, createdBy: result.body["createdBy"], - lastModifiedDateTime: result.body["lastModifiedDateTime"], + lastModifiedDateTime: + result.body["lastModifiedDateTime"] !== undefined + ? new Date(result.body["lastModifiedDateTime"]) + : undefined, lastModifiedBy: result.body["lastModifiedBy"], }; } -/** Stop test run by name. */ -export async function stopTestRun( +/** Stop test run by test run Id. */ +export async function stop( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestRunSend(context, testRunId, options); - return _stopTestRunDeserialize(result); + const result = await _stopSend(context, testRunId, options); + return _stopDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts deleted file mode 100644 index d4d54d4e32..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/pollingHelpers.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - ResourceLocationConfig, - RunningOperation, - createHttpPoller, - OperationResponse, -} from "@azure/core-lro"; - -import { - Client, - PathUncheckedResponse, - createRestError, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; -import { isUnexpected } from "../../rest/index.js"; - -export interface GetLongRunningPollerOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** - * The potential location of the result of the LRO if specified by the LRO extension in the swagger. - */ - resourceLocationConfig?: ResourceLocationConfig; - /** - * The original url of the LRO - * Should not be null when restoreFrom is set - */ - initialRequestUrl?: string; - /** - * A serialized poller which can be used to resume an existing paused Long-Running-Operation. - */ - restoreFrom?: string; - /** - * The function to get the initial response - */ - getInitialResponse?: () => PromiseLike; -} -export function getLongRunningPoller< - TResponse extends PathUncheckedResponse, - TResult = void, ->( - client: Client, - processResponseBody: (result: TResponse) => Promise, - options: GetLongRunningPollerOptions, -): PollerLike, TResult> { - const { restoreFrom, getInitialResponse } = options; - if (!restoreFrom && !getInitialResponse) { - throw new Error( - "Either restoreFrom or getInitialResponse must be specified", - ); - } - let initialResponse: TResponse | undefined = undefined; - const pollAbortController = new AbortController(); - const poller: RunningOperation = { - sendInitialRequest: async () => { - if (!getInitialResponse) { - throw new Error( - "getInitialResponse is required when initializing a new poller", - ); - } - initialResponse = await getInitialResponse(); - return getLroResponse(initialResponse); - }, - sendPollRequest: async ( - path: string, - pollOptions?: { - abortSignal?: AbortSignalLike; - }, - ) => { - // The poll request would both listen to the user provided abort signal and the poller's own abort signal - function abortListener(): void { - pollAbortController.abort(); - } - const abortSignal = pollAbortController.signal; - if (options.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (pollOptions?.abortSignal?.aborted) { - pollAbortController.abort(); - } else if (!abortSignal.aborted) { - options.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - pollOptions?.abortSignal?.addEventListener("abort", abortListener, { - once: true, - }); - } - let response; - try { - response = await client.pathUnchecked(path).get({ abortSignal }); - } finally { - options.abortSignal?.removeEventListener("abort", abortListener); - pollOptions?.abortSignal?.removeEventListener("abort", abortListener); - } - if (options.initialRequestUrl || initialResponse) { - response.headers["x-ms-original-url"] = - options.initialRequestUrl ?? initialResponse!.request.url; - } - - return getLroResponse(response as TResponse); - }, - }; - return createHttpPoller(poller, { - intervalInMs: options?.updateIntervalInMs, - resourceLocationConfig: options?.resourceLocationConfig, - restoreFrom: options?.restoreFrom, - processResult: (result: unknown) => { - return processResponseBody(result as TResponse); - }, - }); -} -/** - * Converts a Rest Client response to a response that the LRO implementation understands - * @param response - a rest client http response - * @param deserializeFn - deserialize function to convert Rest response to modular output - * @returns - An LRO response that the LRO implementation understands - */ -function getLroResponse( - response: TResponse, -): OperationResponse { - if (isUnexpected(response as PathUncheckedResponse)) { - throw createRestError(response); - } - return { - flatResponse: response, - rawResponse: { - ...response, - statusCode: Number.parseInt(response.status), - body: response.body, - }, - }; -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts index 8ed47fc3e2..e7185f6423 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/api/testRunOperationsContext.ts @@ -3,7 +3,7 @@ import { TokenCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; -import { AzureLoadTestingContext } from "../../rest/index.js"; +import { LoadTestServiceContext } from "../../rest/index.js"; import getClient from "../../rest/index.js"; /** Optional parameters for the client. */ @@ -12,13 +12,13 @@ export interface TestRunOperationsClientOptionalParams extends ClientOptions { apiVersion?: string; } -export { AzureLoadTestingContext } from "../../rest/index.js"; +export { LoadTestServiceContext } from "../../rest/index.js"; export function createTestRunOperations( endpointParam: string, credential: TokenCredential, options: TestRunOperationsClientOptionalParams = {}, -): AzureLoadTestingContext { +): LoadTestServiceContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts index 03b74076da..b77a0ab498 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/index.ts @@ -5,25 +5,36 @@ export { TestRunOperationsClient, TestRunOperationsClientOptionalParams, } from "./testRunOperationsClient.js"; -export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, + AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -34,20 +45,28 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + KnownTimeGrain, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -55,7 +74,21 @@ export { TimeSeriesElement, MetricValue, DimensionValue, - TestRunOptionalParams, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, + ResourceKind, + TestProfileRun, + KnownTestProfileRunStatus, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + KnownRecommendationCategory, + RecommendationCategory, + TargetResourceConfigurationsUnion, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -68,7 +101,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, PageSettings, ContinuablePage, PagedAsyncIterableIterator, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts index cfa3ac60f4..5dd83b954e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/index.ts @@ -5,20 +5,32 @@ export { Test, PassFailCriteria, PassFailMetric, + KnownPFMetrics, PFMetrics, + KnownPFAgFunc, PFAgFunc, + KnownPFAction, PFAction, + KnownPFResult, PFResult, + AutoStopCriteria, Secret, + KnownSecretType, SecretType, CertificateMetadata, + KnownCertificateType, CertificateType, LoadTestConfiguration, OptionalLoadTestConfig, + RegionalConfiguration, TestInputArtifacts, - FileInfo, + TestFileInfo, + KnownFileType, FileType, + KnownFileStatus, FileStatus, + KnownTestKind, + TestKind, TestAppComponents, AppComponent, TestServerMetricConfig, @@ -29,20 +41,28 @@ export { TestRunStatistics, TestRunArtifacts, TestRunInputArtifacts, + TestRunFileInfo, TestRunOutputArtifacts, + ArtifactsContainerInfo, + KnownPFTestResult, PFTestResult, + KnownStatus, Status, + KnownRequestDataLevel, + RequestDataLevel, TestRunAppComponents, TestRunServerMetricConfig, - Interval, + KnownTimeGrain, + TimeGrain, DimensionValueList, MetricDefinitionCollection, MetricDefinition, NameAndDesc, + KnownAggregationType, AggregationType, + KnownMetricUnit, MetricUnit, MetricAvailability, - TimeGrain, MetricNamespaceCollection, MetricNamespace, MetricRequestPayload, @@ -50,9 +70,23 @@ export { TimeSeriesElement, MetricValue, DimensionValue, + TestProfile, + TargetResourceConfigurations, + FunctionFlexConsumptionTargetResourceConfigurations, + FunctionFlexConsumptionResourceConfiguration, + KnownResourceKind, + ResourceKind, + TestProfileRun, + KnownTestProfileRunStatus, + TestProfileRunStatus, + TestRunDetail, + TestProfileRunRecommendation, + KnownRecommendationCategory, + RecommendationCategory, + TargetResourceConfigurationsUnion, } from "./models.js"; export { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -65,7 +99,7 @@ export { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./options.js"; export { PageSettings, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts index 3a7491a214..b95c47ad79 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/models.ts @@ -6,10 +6,12 @@ import { Test as TestRest, PassFailCriteria as PassFailCriteriaRest, PassFailMetric as PassFailMetricRest, + AutoStopCriteria as AutoStopCriteriaRest, Secret as SecretRest, CertificateMetadata as CertificateMetadataRest, LoadTestConfiguration as LoadTestConfigurationRest, OptionalLoadTestConfig as OptionalLoadTestConfigRest, + RegionalConfiguration as RegionalConfigurationRest, TestAppComponents as TestAppComponentsRest, AppComponent as AppComponentRest, TestServerMetricConfig as TestServerMetricConfigRest, @@ -19,12 +21,19 @@ import { TestRunServerMetricConfig as TestRunServerMetricConfigRest, MetricRequestPayload as MetricRequestPayloadRest, DimensionFilter as DimensionFilterRest, + TestProfile as TestProfileRest, + TargetResourceConfigurations as TargetResourceConfigurationsRest, + FunctionFlexConsumptionTargetResourceConfigurations as FunctionFlexConsumptionTargetResourceConfigurationsRest, + FunctionFlexConsumptionResourceConfiguration as FunctionFlexConsumptionResourceConfigurationRest, + TestProfileRun as TestProfileRunRest, } from "../../rest/index.js"; -/** Load test model */ +/** Load test model. */ export interface Test { /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -33,32 +42,38 @@ export interface Test { * SECRET_VALUE. */ secrets?: Record; - /** Certificates metadata */ + /** Certificates metadata. */ certificate?: CertificateMetadata; /** Environment variables which are defined as a set of pairs. */ environmentVariables?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; + /** Id of the test run to be marked as baseline to view trends of client-side metrics from recent test runs */ + baselineTestRunId?: string; /** The input artifacts for the test. */ readonly inputArtifacts?: TestInputArtifacts; - /** Unique test name as identifier. */ - readonly testId?: string; + /** Unique test identifier for the load test, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testId: string; /** The test description. */ description?: string; /** Display name of a test. */ displayName?: string; /** Subnet ID on which the load test instances should run. */ subnetId?: string; + /** Kind of test. */ + kind?: TestKind; + /** Inject load test engines without deploying public IP for outbound access */ + publicIPDisabled?: boolean; /** Type of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityType?: string; /** Resource Id of the managed identity referencing the Key vault. */ keyvaultReferenceIdentityId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -68,6 +83,9 @@ export function testSerializer(item: Test): TestRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -80,9 +98,12 @@ export function testSerializer(item: Test): TestRest { loadTestConfiguration: !item.loadTestConfiguration ? item.loadTestConfiguration : loadTestConfigurationSerializer(item.loadTestConfiguration), + baselineTestRunId: item["baselineTestRunId"], description: item["description"], displayName: item["displayName"], subnetId: item["subnetId"], + kind: item["kind"], + publicIPDisabled: item["publicIPDisabled"], keyvaultReferenceIdentityType: item["keyvaultReferenceIdentityType"], keyvaultReferenceIdentityId: item["keyvaultReferenceIdentityId"], }; @@ -113,7 +134,7 @@ export interface PassFailMetric { clientMetric?: PFMetrics; /** * The aggregation function to be applied on the client metric. Allowed functions - * - ‘percentage’ - for error metric , ‘avg’, ‘p50’, ‘p90’, ‘p95’, ‘p99’, ‘min’, + * - ‘percentage’ - for error metric , ‘avg’, percentiles like ‘p50’, ‘p90’, & so on, ‘min’, * ‘max’ - for response_time_ms and latency metric, ‘avg’ - for requests_per_sec, * ‘count’ - for requests */ @@ -148,28 +169,148 @@ export function passFailMetricSerializer( }; } -/** Type of PFMetrics */ -export type PFMetrics = - | "response_time_ms" - | "latency" - | "error" - | "requests" - | "requests_per_sec"; -/** Type of PFAgFunc */ -export type PFAgFunc = - | "count" - | "percentage" - | "avg" - | "p50" - | "p90" - | "p95" - | "p99" - | "min" - | "max"; -/** Type of PFAction */ -export type PFAction = "continue" | "stop"; -/** Type of PFResult */ -export type PFResult = "passed" | "undetermined" | "failed"; +/** Known values of {@link PFMetrics} that the service accepts. */ +export enum KnownPFMetrics { + /** response_time_ms */ + response_time_ms = "response_time_ms", + /** latency */ + latency = "latency", + /** error */ + error = "error", + /** requests */ + requests = "requests", + /** requests_per_sec */ + requests_per_sec = "requests_per_sec", +} + +/** + * Metrics for pass/fail criteria. \ + * {@link KnownPFMetrics} can be used interchangeably with PFMetrics, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **response_time_ms** \ + * **latency** \ + * **error** \ + * **requests** \ + * **requests_per_sec** + */ +export type PFMetrics = string; + +/** Known values of {@link PFAgFunc} that the service accepts. */ +export enum KnownPFAgFunc { + /** count */ + count = "count", + /** percentage */ + percentage = "percentage", + /** avg */ + avg = "avg", + /** p50 */ + p50 = "p50", + /** p75 */ + p75 = "p75", + /** p90 */ + p90 = "p90", + /** p95 */ + p95 = "p95", + /** p96 */ + p96 = "p96", + /** p97 */ + p97 = "p97", + /** p98 */ + p98 = "p98", + /** p99 */ + p99 = "p99", + /** p99.9 */ + "p99.9" = "p99.9", + /** p99.99 */ + "p99.99" = "p99.99", + /** min */ + min = "min", + /** max */ + max = "max", +} + +/** + * Aggregation functions for pass/fail criteria. \ + * {@link KnownPFAgFunc} can be used interchangeably with PFAgFunc, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **count** \ + * **percentage** \ + * **avg** \ + * **p50** \ + * **p75** \ + * **p90** \ + * **p95** \ + * **p96** \ + * **p97** \ + * **p98** \ + * **p99** \ + * **p99.9** \ + * **p99.99** \ + * **min** \ + * **max** + */ +export type PFAgFunc = string; + +/** Known values of {@link PFAction} that the service accepts. */ +export enum KnownPFAction { + /** continue */ + "continue" = "continue", + /** stop */ + stop = "stop", +} + +/** + * Action to take on failure of pass/fail criteria. \ + * {@link KnownPFAction} can be used interchangeably with PFAction, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **continue** \ + * **stop** + */ +export type PFAction = string; + +/** Known values of {@link PFResult} that the service accepts. */ +export enum KnownPFResult { + /** passed */ + passed = "passed", + /** undetermined */ + undetermined = "undetermined", + /** failed */ + failed = "failed", +} + +/** + * Pass/fail criteria result. \ + * {@link KnownPFResult} can be used interchangeably with PFResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **passed** \ + * **undetermined** \ + * **failed** + */ +export type PFResult = string; + +/** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ +export interface AutoStopCriteria { + /** Whether auto-stop should be disabled. The default value is false. */ + autoStopDisabled?: boolean; + /** Threshold percentage of errors on which test run should be automatically stopped. Allowed values are in range of 0.0-100.0 */ + errorRate?: number; + /** Time window during which the error percentage should be evaluated in seconds. */ + errorRateTimeWindowInSeconds?: number; +} + +export function autoStopCriteriaSerializer( + item: AutoStopCriteria, +): AutoStopCriteriaRest { + return { + autoStopDisabled: item["autoStopDisabled"], + errorRate: item["errorRate"], + errorRateTimeWindowInSeconds: item["errorRateTimeWindowInSeconds"], + }; +} /** Secret */ export interface Secret { @@ -186,8 +327,23 @@ export function secretSerializer(item: Secret): SecretRest { }; } -/** Type of SecretType */ -export type SecretType = "AKV_SECRET_URI" | "SECRET_VALUE"; +/** Known values of {@link SecretType} that the service accepts. */ +export enum KnownSecretType { + /** AKV_SECRET_URI */ + AKV_SECRET_URI = "AKV_SECRET_URI", + /** SECRET_VALUE */ + SECRET_VALUE = "SECRET_VALUE", +} + +/** + * Types of secrets supported. \ + * {@link KnownSecretType} can be used interchangeably with SecretType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_SECRET_URI** \ + * **SECRET_VALUE** + */ +export type SecretType = string; /** Certificates metadata */ export interface CertificateMetadata { @@ -209,15 +365,24 @@ export function certificateMetadataSerializer( }; } -/** Type of CertificateType */ -export type CertificateType = "AKV_CERT_URI"; +/** Known values of {@link CertificateType} that the service accepts. */ +export enum KnownCertificateType { + /** AKV_CERT_URI */ + AKV_CERT_URI = "AKV_CERT_URI", +} + +/** + * Types of certificates supported. \ + * {@link KnownCertificateType} can be used interchangeably with CertificateType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **AKV_CERT_URI** + */ +export type CertificateType = string; -/** The load test configuration. */ +/** Configurations for the load test. */ export interface LoadTestConfiguration { - /** - * The number of engine instances to execute load test. Supported values are in - * range of 1-45. Required for creating a new test. - */ + /** The number of engine instances to execute load test. Supported values are in range of 1-400. Required for creating a new test. */ engineInstances?: number; /** * If false, Azure Load Testing copies and processes your input files unmodified @@ -231,8 +396,10 @@ export interface LoadTestConfiguration { * not required to upload. */ quickStartTest?: boolean; - /** Optional load test config */ + /** Configuration for quick load test */ optionalLoadTestConfig?: OptionalLoadTestConfig; + /** Region distribution configuration for the load test. */ + regionalLoadTestConfig?: RegionalConfiguration[]; } export function loadTestConfigurationSerializer( @@ -245,21 +412,26 @@ export function loadTestConfigurationSerializer( optionalLoadTestConfig: !item.optionalLoadTestConfig ? item.optionalLoadTestConfig : optionalLoadTestConfigSerializer(item.optionalLoadTestConfig), + regionalLoadTestConfig: + item["regionalLoadTestConfig"] === undefined + ? item["regionalLoadTestConfig"] + : item["regionalLoadTestConfig"].map(regionalConfigurationSerializer), }; } -/** Optional load test config */ +/** Configuration for quick load test */ export interface OptionalLoadTestConfig { - /** - * Test URL. Provide the complete HTTP URL. For example, - * http://contoso-app.azurewebsites.net/login - */ + /** Test URL. Provide the complete HTTP URL. For example, https://contoso-app.azurewebsites.net/login */ endpointUrl?: string; - /** No of concurrent virtual users */ + /** Target throughput (requests per second). This may not be necessarily achieved. The actual throughput will be lower if the application is not capable of handling it. */ + requestsPerSecond?: number; + /** Maximum response time in milliseconds of the API/endpoint. */ + maxResponseTimeInMs?: number; + /** No of concurrent virtual users. */ virtualUsers?: number; - /** Ramp up time */ + /** Ramp up time in seconds. */ rampUpTime?: number; - /** Test run duration */ + /** Test run duration in seconds. */ duration?: number; } @@ -268,53 +440,146 @@ export function optionalLoadTestConfigSerializer( ): OptionalLoadTestConfigRest { return { endpointUrl: item["endpointUrl"], + requestsPerSecond: item["requestsPerSecond"], + maxResponseTimeInMs: item["maxResponseTimeInMs"], virtualUsers: item["virtualUsers"], rampUpTime: item["rampUpTime"], duration: item["duration"], }; } +/** Region distribution configuration for the load test. */ +export interface RegionalConfiguration { + /** The number of engine instances to execute load test in specified region. Supported values are in range of 1-400. */ + engineInstances: number; + /** + * Azure region name. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + region: string; +} + +export function regionalConfigurationSerializer( + item: RegionalConfiguration, +): RegionalConfigurationRest { + return { + engineInstances: item["engineInstances"], + region: item["region"], + }; +} + /** The input artifacts for the test. */ export interface TestInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestFileInfo[]; } -/** File info */ -export interface FileInfo { - /** File URL. */ - url?: string; +/** Test file info. */ +export interface TestFileInfo { /** Name of the file. */ - fileName?: string; + fileName: string; + /** File URL. */ + readonly url?: string; /** File type */ - fileType?: FileType; - /** Expiry time of the file (ISO 8601 literal format) */ - expireDateTime?: string; + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; /** Validation status of the file */ - validationStatus?: FileStatus; + readonly validationStatus?: FileStatus; /** Validation failure error details */ - validationFailureDetails?: string; + readonly validationFailureDetails?: string; } -/** Type of FileType */ -export type FileType = "JMX_FILE" | "USER_PROPERTIES" | "ADDITIONAL_ARTIFACTS"; -/** Type of FileStatus */ -export type FileStatus = - | "NOT_VALIDATED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE" - | "VALIDATION_INITIATED" - | "VALIDATION_NOT_REQUIRED"; +/** Known values of {@link FileType} that the service accepts. */ +export enum KnownFileType { + /** JMX_FILE */ + JMX_FILE = "JMX_FILE", + /** USER_PROPERTIES */ + USER_PROPERTIES = "USER_PROPERTIES", + /** ADDITIONAL_ARTIFACTS */ + ADDITIONAL_ARTIFACTS = "ADDITIONAL_ARTIFACTS", + /** ZIPPED_ARTIFACTS */ + ZIPPED_ARTIFACTS = "ZIPPED_ARTIFACTS", + /** URL_TEST_CONFIG */ + URL_TEST_CONFIG = "URL_TEST_CONFIG", + /** TEST_SCRIPT */ + TEST_SCRIPT = "TEST_SCRIPT", +} -/** Test app component */ +/** + * Types of file supported. \ + * {@link KnownFileType} can be used interchangeably with FileType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **JMX_FILE** \ + * **USER_PROPERTIES** \ + * **ADDITIONAL_ARTIFACTS** \ + * **ZIPPED_ARTIFACTS** \ + * **URL_TEST_CONFIG** \ + * **TEST_SCRIPT** + */ +export type FileType = string; + +/** Known values of {@link FileStatus} that the service accepts. */ +export enum KnownFileStatus { + /** NOT_VALIDATED */ + NOT_VALIDATED = "NOT_VALIDATED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", + /** VALIDATION_INITIATED */ + VALIDATION_INITIATED = "VALIDATION_INITIATED", + /** VALIDATION_NOT_REQUIRED */ + VALIDATION_NOT_REQUIRED = "VALIDATION_NOT_REQUIRED", +} + +/** + * File status. \ + * {@link KnownFileStatus} can be used interchangeably with FileStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NOT_VALIDATED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** \ + * **VALIDATION_INITIATED** \ + * **VALIDATION_NOT_REQUIRED** + */ +export type FileStatus = string; + +/** Known values of {@link TestKind} that the service accepts. */ +export enum KnownTestKind { + /** URL */ + URL = "URL", + /** JMX */ + JMX = "JMX", + /** Locust */ + Locust = "Locust", +} + +/** + * Test kind \ + * {@link KnownTestKind} can be used interchangeably with TestKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **URL** \ + * **JMX** \ + * **Locust** + */ +export type TestKind = string; + +/** Test app components */ export interface TestAppComponents { /** * Azure resource collection { resource id (fully qualified resource Id e.g @@ -324,12 +589,12 @@ export interface TestAppComponents { components: Record; /** Test identifier */ readonly testId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -345,20 +610,14 @@ export function testAppComponentsSerializer( }; } -/** - * An Azure resource object (Refer azure generic resource model : - * https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) - */ +/** An Azure resource object (Refer azure generic resource model :https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id#genericresource) */ export interface AppComponent { - /** - * fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} - */ - readonly resourceId?: string; + /** fully qualified resource Id e.g subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName} */ + readonly resourceId: string; /** Azure resource name, required while creating the app component. */ - resourceName?: string; + resourceName: string; /** Azure resource type, required while creating the app component. */ - resourceType?: string; + resourceType: string; /** Azure resource display name */ displayName?: string; /** Resource group name of the Azure resource */ @@ -387,13 +646,13 @@ export interface TestServerMetricConfig { * https://docs.microsoft.com/en-us/rest/api/monitor/metric-definitions/list#metricdefinition * for metric id). */ - metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + metrics: Record; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -402,9 +661,10 @@ export function testServerMetricConfigSerializer( item: TestServerMetricConfig, ): TestServerMetricConfigRest { return { - metrics: !item.metrics - ? item.metrics - : (serializeRecord(item.metrics as any, resourceMetricSerializer) as any), + metrics: serializeRecord( + item.metrics as any, + resourceMetricSerializer, + ) as any, }; } @@ -446,31 +706,21 @@ export function resourceMetricSerializer( }; } -/** Collection of files. */ -export interface _PagedFileInfo { - /** The FileInfo items on this page */ - value: FileInfo[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Collection of tests */ -export interface _PagedTest { - /** The Test items on this page */ - value: Test[]; - /** The link to the next page of items */ - nextLink?: string; -} - -/** Type of APIVersions */ -export type APIVersions = "2022-11-01"; +/** Azure Load Testing API versions. */ +export type APIVersions = + | "2022-11-01" + | "2023-04-01-preview" + | "2024-03-01-preview" + | "2024-05-01-preview"; /** Load test run model */ export interface TestRun { - /** Unique test run name as identifier */ + /** Unique test run identifier for the load test run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ readonly testRunId: string; /** Pass fail criteria for a test. */ passFailCriteria?: PassFailCriteria; + /** Auto stop criteria for a test. This will automatically stop a load test if the error percentage is high for a certain time window. */ + autoStopCriteria?: AutoStopCriteria; /** * Secrets can be stored in an Azure Key Vault or any other secret store. If the * secret is stored in an Azure Key Vault, the value should be the secret @@ -485,8 +735,18 @@ export interface TestRun { environmentVariables?: Record; /** Error details if there is any failure in load test run */ readonly errorDetails?: ErrorDetails[]; - /** Test run statistics. */ + /** + * Test run statistics. Key is the sampler name and value is the set of statistics for performance metrics like response time, throughput, etc. from the load test run. + * The sampler name is the same as the name mentioned in the test script. + * Sampler name "Total" represents the aggregated statistics of all the samplers. + */ readonly testRunStatistics?: Record; + /** + * Regional statistics. Key is the Azure region name and value is the test run statistics. + * The region name should of format accepted by ARM, and should be a region supported by Azure Load Testing. For example, East US should be passed as "eastus". + * The region name must match one of the strings in the "Name" column returned from running the "az account list-locations -o table" Azure CLI command. + */ + readonly regionalStatistics?: Record; /** The load test configuration. */ loadTestConfiguration?: LoadTestConfiguration; /** Collection of test run artifacts */ @@ -503,24 +763,32 @@ export interface TestRun { description?: string; /** The test run status. */ readonly status?: Status; - /** The test run start DateTime(ISO 8601 literal format). */ - readonly startDateTime?: string; - /** The test run end DateTime(ISO 8601 literal format). */ - readonly endDateTime?: string; + /** The test run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; /** Test run initiated time. */ - readonly executedDateTime?: string; + readonly executedDateTime?: Date; /** Portal url. */ readonly portalUrl?: string; /** Test run duration in milliseconds. */ readonly duration?: number; /** Subnet ID on which the load test instances should run. */ readonly subnetId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** Type of test. */ + readonly kind?: TestKind; + /** Request data collection level for test run */ + requestDataLevel?: RequestDataLevel; + /** Enable or disable debug level logging. True if debug logs are enabled for the test run. False otherwise */ + debugLogsEnabled?: boolean; + /** Inject load test engines without deploying public IP for outbound access */ + readonly publicIPDisabled?: boolean; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -530,6 +798,9 @@ export function testRunSerializer(item: TestRun): TestRunRest { passFailCriteria: !item.passFailCriteria ? item.passFailCriteria : passFailCriteriaSerializer(item.passFailCriteria), + autoStopCriteria: !item.autoStopCriteria + ? item.autoStopCriteria + : autoStopCriteriaSerializer(item.autoStopCriteria), secrets: !item.secrets ? item.secrets : (serializeRecord(item.secrets as any, secretSerializer) as any), @@ -545,6 +816,8 @@ export function testRunSerializer(item: TestRun): TestRunRest { displayName: item["displayName"], testId: item["testId"], description: item["description"], + requestDataLevel: item["requestDataLevel"], + debugLogsEnabled: item["debugLogsEnabled"], }; } @@ -578,6 +851,18 @@ export interface TestRunStatistics { readonly pct2ResTime?: number; /** 99 percentile response time. */ readonly pct3ResTime?: number; + /** 75 percentile response time. */ + readonly pct75ResTime?: number; + /** 96 percentile response time. */ + readonly pct96ResTime?: number; + /** 97 percentile response time. */ + readonly pct97ResTime?: number; + /** 98 percentile response time. */ + readonly pct98ResTime?: number; + /** 99.9 percentile response time. */ + readonly pct999ResTime?: number; + /** 99.99 percentile response time. */ + readonly pct9999ResTime?: number; /** Throughput. */ readonly throughput?: number; /** Received network bytes. */ @@ -597,45 +882,153 @@ export interface TestRunArtifacts { /** The input artifacts for the test run. */ export interface TestRunInputArtifacts { /** File info */ - configFileInfo?: FileInfo; + configFileInfo?: TestRunFileInfo; /** File info */ - testScriptFileInfo?: FileInfo; + testScriptFileInfo?: TestRunFileInfo; /** File info */ - userPropFileInfo?: FileInfo; + userPropFileInfo?: TestRunFileInfo; /** File info */ - inputArtifactsZipFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: TestRunFileInfo; + /** The config json file for url based test */ + urlTestConfigFileInfo?: TestRunFileInfo; /** Additional supported files for the test run */ - readonly additionalFileInfo?: FileInfo[]; + readonly additionalFileInfo?: TestRunFileInfo[]; +} + +/** Test run file info. */ +export interface TestRunFileInfo { + /** Name of the file. */ + fileName: string; + /** File URL. */ + readonly url?: string; + /** File type */ + readonly fileType?: FileType; + /** Expiry time of the file (RFC 3339 literal format) */ + readonly expireDateTime?: Date; + /** Validation status of the file */ + readonly validationStatus?: FileStatus; + /** Validation failure error details */ + readonly validationFailureDetails?: string; } /** The output artifacts for the test run. */ export interface TestRunOutputArtifacts { /** File info */ - resultFileInfo?: FileInfo; + resultFileInfo?: TestRunFileInfo; /** File info */ - logsFileInfo?: FileInfo; -} - -/** Type of PFTestResult */ -export type PFTestResult = "PASSED" | "NOT_APPLICABLE" | "FAILED"; -/** Type of Status */ -export type Status = - | "ACCEPTED" - | "NOTSTARTED" - | "PROVISIONING" - | "PROVISIONED" - | "CONFIGURING" - | "CONFIGURED" - | "EXECUTING" - | "EXECUTED" - | "DEPROVISIONING" - | "DEPROVISIONED" - | "DONE" - | "CANCELLING" - | "CANCELLED" - | "FAILED" - | "VALIDATION_SUCCESS" - | "VALIDATION_FAILURE"; + logsFileInfo?: TestRunFileInfo; + /** The container for test run artifacts. */ + artifactsContainerInfo?: ArtifactsContainerInfo; + /** The report file for the test run. */ + reportFileInfo?: TestRunFileInfo; +} + +/** Artifacts container info. */ +export interface ArtifactsContainerInfo { + /** This is a SAS URI to an Azure Storage Container that contains the test run artifacts. */ + url?: string; + /** Expiry time of the container (RFC 3339 literal format) */ + expireDateTime?: Date; +} + +/** Known values of {@link PFTestResult} that the service accepts. */ +export enum KnownPFTestResult { + /** PASSED */ + PASSED = "PASSED", + /** NOT_APPLICABLE */ + NOT_APPLICABLE = "NOT_APPLICABLE", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test result based on pass/fail criteria. \ + * {@link KnownPFTestResult} can be used interchangeably with PFTestResult, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PASSED** \ + * **NOT_APPLICABLE** \ + * **FAILED** + */ +export type PFTestResult = string; + +/** Known values of {@link Status} that the service accepts. */ +export enum KnownStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** PROVISIONING */ + PROVISIONING = "PROVISIONING", + /** PROVISIONED */ + PROVISIONED = "PROVISIONED", + /** CONFIGURING */ + CONFIGURING = "CONFIGURING", + /** CONFIGURED */ + CONFIGURED = "CONFIGURED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** EXECUTED */ + EXECUTED = "EXECUTED", + /** DEPROVISIONING */ + DEPROVISIONING = "DEPROVISIONING", + /** DEPROVISIONED */ + DEPROVISIONED = "DEPROVISIONED", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", + /** VALIDATION_SUCCESS */ + VALIDATION_SUCCESS = "VALIDATION_SUCCESS", + /** VALIDATION_FAILURE */ + VALIDATION_FAILURE = "VALIDATION_FAILURE", +} + +/** + * Test run status. \ + * {@link KnownStatus} can be used interchangeably with Status, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **PROVISIONING** \ + * **PROVISIONED** \ + * **CONFIGURING** \ + * **CONFIGURED** \ + * **EXECUTING** \ + * **EXECUTED** \ + * **DEPROVISIONING** \ + * **DEPROVISIONED** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** \ + * **VALIDATION_SUCCESS** \ + * **VALIDATION_FAILURE** + */ +export type Status = string; + +/** Known values of {@link RequestDataLevel} that the service accepts. */ +export enum KnownRequestDataLevel { + /** NONE */ + NONE = "NONE", + /** ERRORS */ + ERRORS = "ERRORS", +} + +/** + * Request data collection level for test run \ + * {@link KnownRequestDataLevel} can be used interchangeably with RequestDataLevel, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NONE** \ + * **ERRORS** + */ +export type RequestDataLevel = string; /** Test run app component */ export interface TestRunAppComponents { @@ -647,12 +1040,12 @@ export interface TestRunAppComponents { components: Record; /** Test run identifier */ readonly testRunId?: string; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -678,12 +1071,12 @@ export interface TestRunServerMetricConfig { * for metric id). */ metrics?: Record; - /** The creation datetime(ISO 8601 literal format). */ - readonly createdDateTime?: string; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; /** The user that created. */ readonly createdBy?: string; - /** The last Modified datetime(ISO 8601 literal format). */ - readonly lastModifiedDateTime?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; /** The user that last modified. */ readonly lastModifiedBy?: string; } @@ -698,11 +1091,41 @@ export function testRunServerMetricConfigSerializer( }; } -/** Type of Interval */ -export type Interval = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; +/** Known values of {@link TimeGrain} that the service accepts. */ +export enum KnownTimeGrain { + /** PT5S */ + PT5S = "PT5S", + /** PT10S */ + PT10S = "PT10S", + /** PT1M */ + PT1M = "PT1M", + /** PT5M */ + PT5M = "PT5M", + /** PT1H */ + PT1H = "PT1H", +} + +/** + * Time Grain \ + * {@link KnownTimeGrain} can be used interchangeably with TimeGrain, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PT5S** \ + * **PT10S** \ + * **PT1M** \ + * **PT5M** \ + * **PT1H** + */ +export type TimeGrain = string; +/** Metrics dimension values. */ export interface DimensionValueList { - value: string[]; + /** The dimension name */ + readonly name?: string; + /** The dimension value */ + value?: string[]; + /** Link for the next set of values in case of paginated results, if applicable. */ + nextLink?: string; } /** Represents collection of metric definitions. */ @@ -742,25 +1165,92 @@ export interface NameAndDesc { name?: string; } -/** Type of AggregationType */ -export type AggregationType = - | "Average" - | "Count" - | "None" - | "Total" - | "Percentile90" - | "Percentile95" - | "Percentile99"; -/** Type of MetricUnit */ -export type MetricUnit = - | "NotSpecified" - | "Percent" - | "Count" - | "Seconds" - | "Milliseconds" - | "Bytes" - | "BytesPerSecond" - | "CountPerSecond"; +/** Known values of {@link AggregationType} that the service accepts. */ +export enum KnownAggregationType { + /** Average */ + Average = "Average", + /** Count */ + Count = "Count", + /** None */ + None = "None", + /** Total */ + Total = "Total", + /** Percentile75 */ + Percentile75 = "Percentile75", + /** Percentile90 */ + Percentile90 = "Percentile90", + /** Percentile95 */ + Percentile95 = "Percentile95", + /** Percentile96 */ + Percentile96 = "Percentile96", + /** Percentile97 */ + Percentile97 = "Percentile97", + /** Percentile98 */ + Percentile98 = "Percentile98", + /** Percentile99 */ + Percentile99 = "Percentile99", + /** Percentile999 */ + Percentile999 = "Percentile999", + /** Percentile9999 */ + Percentile9999 = "Percentile9999", +} + +/** + * Aggregation type. \ + * {@link KnownAggregationType} can be used interchangeably with AggregationType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Average** \ + * **Count** \ + * **None** \ + * **Total** \ + * **Percentile75** \ + * **Percentile90** \ + * **Percentile95** \ + * **Percentile96** \ + * **Percentile97** \ + * **Percentile98** \ + * **Percentile99** \ + * **Percentile999** \ + * **Percentile9999** + */ +export type AggregationType = string; + +/** Known values of {@link MetricUnit} that the service accepts. */ +export enum KnownMetricUnit { + /** NotSpecified */ + NotSpecified = "NotSpecified", + /** Percent */ + Percent = "Percent", + /** Count */ + Count = "Count", + /** Seconds */ + Seconds = "Seconds", + /** Milliseconds */ + Milliseconds = "Milliseconds", + /** Bytes */ + Bytes = "Bytes", + /** BytesPerSecond */ + BytesPerSecond = "BytesPerSecond", + /** CountPerSecond */ + CountPerSecond = "CountPerSecond", +} + +/** + * Metric unit. \ + * {@link KnownMetricUnit} can be used interchangeably with MetricUnit, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **NotSpecified** \ + * **Percent** \ + * **Count** \ + * **Seconds** \ + * **Milliseconds** \ + * **Bytes** \ + * **BytesPerSecond** \ + * **CountPerSecond** + */ +export type MetricUnit = string; /** Metric availability specifies the time grain (aggregation interval or frequency) */ export interface MetricAvailability { @@ -771,9 +1261,6 @@ export interface MetricAvailability { timeGrain?: TimeGrain; } -/** Type of TimeGrain */ -export type TimeGrain = "PT5S" | "PT10S" | "PT1M" | "PT5M" | "PT1H"; - /** Represents collection of metric namespaces. */ export interface MetricNamespaceCollection { /** The values for the metric namespaces. */ @@ -788,7 +1275,7 @@ export interface MetricNamespace { name?: string; } -/** Filters to fetch the set of metric */ +/** Filters to fetch the set of metric. */ export interface MetricRequestPayload { /** * Get metrics for specific dimension values. Example: Metric contains dimension @@ -828,7 +1315,7 @@ export function dimensionFilterSerializer( } /** The response to a metrics query. */ -export interface _PagedTimeSeriesElement { +export interface _Metrics { /** The TimeSeriesElement items on this page */ value: TimeSeriesElement[]; /** The link to the next page of items */ @@ -845,8 +1332,8 @@ export interface TimeSeriesElement { /** Represents a metric value. */ export interface MetricValue { - /** The timestamp for the metric value in ISO 8601 format. */ - timestamp?: string; + /** The timestamp for the metric value in RFC 3339 format. */ + timestamp?: Date; /** The metric value. */ value?: number; } @@ -859,7 +1346,267 @@ export interface DimensionValue { value?: string; } -/** Collection of test runs */ +/** The Test Profile Model. A Test Profile resource enables you to set up a test profile which contains various configurations for a supported resource type and a load test to execute on that resource. */ +export interface TestProfile { + /** Unique identifier for the test profile, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileId: string; + /** Display name of the test profile. */ + displayName?: string; + /** Description for the test profile. */ + description?: string; + /** Associated test ID for the test profile. This property is required for creating a Test Profile and it's not allowed to be updated. */ + testId?: string; + /** Target resource ID on which the test profile is created. This property is required for creating a Test Profile and it's not allowed to be updated. */ + targetResourceId?: string; + /** Configurations of the target resource on which testing would be done. */ + targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileSerializer(item: TestProfile): TestProfileRest { + return { + displayName: item["displayName"], + description: item["description"], + testId: item["testId"], + targetResourceId: item["targetResourceId"], + targetResourceConfigurations: !item.targetResourceConfigurations + ? item.targetResourceConfigurations + : targetResourceConfigurationsUnionSerializer( + item.targetResourceConfigurations, + ), + }; +} + +/** Configurations of a target resource. This varies with the kind of resource. */ +export interface TargetResourceConfigurations { + /** the discriminator possible values: FunctionsFlexConsumption */ + kind: ResourceKind; +} + +export function targetResourceConfigurationsUnionSerializer( + item: TargetResourceConfigurationsUnion, +) { + switch (item.kind) { + case "FunctionsFlexConsumption": + return functionFlexConsumptionTargetResourceConfigurationsSerializer( + item as FunctionFlexConsumptionTargetResourceConfigurations, + ); + + default: + return targetResourceConfigurationsSerializer(item); + } +} + +export function targetResourceConfigurationsSerializer( + item: TargetResourceConfigurationsUnion, +): TargetResourceConfigurationsRest { + return { + kind: item["kind"], + }; +} + +/** Configurations for a Function App using Flex Consumption Plan. */ +export interface FunctionFlexConsumptionTargetResourceConfigurations + extends TargetResourceConfigurations { + /** + * The kind value to use when providing configuration. + * This should typically be not changed from its value. + */ + kind: "FunctionsFlexConsumption"; + /** A map of configurations for a Function app using Flex Consumption Plan. */ + configurations?: Record; +} + +export function functionFlexConsumptionTargetResourceConfigurationsSerializer( + item: FunctionFlexConsumptionTargetResourceConfigurations, +): FunctionFlexConsumptionTargetResourceConfigurationsRest { + return { + kind: item["kind"], + configurations: !item.configurations + ? item.configurations + : (serializeRecord( + item.configurations as any, + functionFlexConsumptionResourceConfigurationSerializer, + ) as any), + }; +} + +/** Resource configuration instance for a Flex Consumption based Azure Function App. */ +export interface FunctionFlexConsumptionResourceConfiguration { + /** Memory size of the instance. Supported values are 2048, 4096. */ + instanceMemoryMB: number; + /** HTTP Concurrency for the function app. */ + httpConcurrency: number; +} + +export function functionFlexConsumptionResourceConfigurationSerializer( + item: FunctionFlexConsumptionResourceConfiguration, +): FunctionFlexConsumptionResourceConfigurationRest { + return { + instanceMemoryMB: item["instanceMemoryMB"], + httpConcurrency: item["httpConcurrency"], + }; +} + +/** Known values of {@link ResourceKind} that the service accepts. */ +export enum KnownResourceKind { + /** FunctionsFlexConsumption */ + FunctionsFlexConsumption = "FunctionsFlexConsumption", +} + +/** + * Kind of the resource on which test profile is created. \ + * {@link KnownResourceKind} can be used interchangeably with ResourceKind, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **FunctionsFlexConsumption** + */ +export type ResourceKind = string; + +/** The Test Profile Run Model. Test Profile Run resource enables you to instantiate an already created test profile and run load tests to get recommendations on the optimal configuration for the target resource. */ +export interface TestProfileRun { + /** Unique identifier for the test profile run, must contain only lower-case alphabetic, numeric, underscore or hyphen characters. */ + readonly testProfileRunId: string; + /** Display name for the test profile run. */ + displayName?: string; + /** The test profile run description */ + description?: string; + /** Associated test profile ID for the test profile run. This is required to create a test profile run and can't be updated. */ + testProfileId?: string; + /** Target resource ID on which the test profile run is created */ + readonly targetResourceId?: string; + /** Configurations of the target resource on which the test profile ran. */ + readonly targetResourceConfigurations?: TargetResourceConfigurationsUnion; + /** The test profile run status. */ + readonly status?: TestProfileRunStatus; + /** Error details if there is any failure in test profile run. These errors are specific to the Test Profile Run. */ + readonly errorDetails?: ErrorDetails[]; + /** The test profile run start DateTime(RFC 3339 literal format). */ + readonly startDateTime?: Date; + /** The test profile run end DateTime(RFC 3339 literal format). */ + readonly endDateTime?: Date; + /** Test profile run duration in seconds. */ + readonly durationInSeconds?: number; + /** + * Details of the test runs ran as part of the test profile run. + * Key is the testRunId of the corresponding testRun. + */ + readonly testRunDetails?: Record; + /** Recommendations provided based on a successful test profile run. */ + readonly recommendations?: TestProfileRunRecommendation[]; + /** The creation datetime(RFC 3339 literal format). */ + readonly createdDateTime?: Date; + /** The user that created. */ + readonly createdBy?: string; + /** The last Modified datetime(RFC 3339 literal format). */ + readonly lastModifiedDateTime?: Date; + /** The user that last modified. */ + readonly lastModifiedBy?: string; +} + +export function testProfileRunSerializer( + item: TestProfileRun, +): TestProfileRunRest { + return { + displayName: item["displayName"], + description: item["description"], + testProfileId: item["testProfileId"], + }; +} + +/** Known values of {@link TestProfileRunStatus} that the service accepts. */ +export enum KnownTestProfileRunStatus { + /** ACCEPTED */ + ACCEPTED = "ACCEPTED", + /** NOTSTARTED */ + NOTSTARTED = "NOTSTARTED", + /** EXECUTING */ + EXECUTING = "EXECUTING", + /** DONE */ + DONE = "DONE", + /** CANCELLING */ + CANCELLING = "CANCELLING", + /** CANCELLED */ + CANCELLED = "CANCELLED", + /** FAILED */ + FAILED = "FAILED", +} + +/** + * Test profile run status. \ + * {@link KnownTestProfileRunStatus} can be used interchangeably with TestProfileRunStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ACCEPTED** \ + * **NOTSTARTED** \ + * **EXECUTING** \ + * **DONE** \ + * **CANCELLING** \ + * **CANCELLED** \ + * **FAILED** + */ +export type TestProfileRunStatus = string; + +/** Details of a particular test run for a test profile run. */ +export interface TestRunDetail { + /** Status of the test run. */ + status: Status; + /** ID of the configuration on which the test ran. */ + configurationId: string; + /** Key value pair of extra properties associated with the test run. */ + properties: Record; +} + +/** A recommendation object that provides a list of configuration that optimizes its category. */ +export interface TestProfileRunRecommendation { + /** Category of the recommendation. */ + category: RecommendationCategory; + /** List of configurations IDs for which the recommendation is applicable. These are a subset of the provided target resource configurations. */ + configurations?: string[]; +} + +/** Known values of {@link RecommendationCategory} that the service accepts. */ +export enum KnownRecommendationCategory { + /** ThroughputOptimized */ + ThroughputOptimized = "ThroughputOptimized", + /** CostOptimized */ + CostOptimized = "CostOptimized", +} + +/** + * Category of Recommendation. \ + * {@link KnownRecommendationCategory} can be used interchangeably with RecommendationCategory, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ThroughputOptimized** \ + * **CostOptimized** + */ +export type RecommendationCategory = string; + +/** Paged collection of TestFileInfo items */ +export interface _PagedTestFileInfo { + /** The TestFileInfo items on this page */ + value: TestFileInfo[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of Test items */ +export interface _PagedTest { + /** The Test items on this page */ + value: Test[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestRun items */ export interface _PagedTestRun { /** The TestRun items on this page */ value: TestRun[]; @@ -867,10 +1614,23 @@ export interface _PagedTestRun { nextLink?: string; } -/** Paged collection of DimensionValueList items */ -export interface _PagedDimensionValueList { - /** The DimensionValueList items on this page */ - value: DimensionValueList[]; +/** Paged collection of TestProfile items */ +export interface _PagedTestProfile { + /** The TestProfile items on this page */ + value: TestProfile[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Paged collection of TestProfileRun items */ +export interface _PagedTestProfileRun { + /** The TestProfileRun items on this page */ + value: TestProfileRun[]; /** The link to the next page of items */ nextLink?: string; } + +/** Alias for TargetResourceConfigurationsUnion */ +export type TargetResourceConfigurationsUnion = + | FunctionFlexConsumptionTargetResourceConfigurations + | TargetResourceConfigurations; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts index 965a8a192f..b7d2fc2c49 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/models/options.ts @@ -2,12 +2,10 @@ // Licensed under the MIT license. import { OperationOptions } from "@azure-rest/core-client"; -import { Interval } from "./models.js"; +import { TimeGrain } from "./models.js"; /** Optional parameters. */ -export interface TestRunOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; +export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { /** This request has a JSON Merge Patch body. */ contentType?: string; /** @@ -22,12 +20,14 @@ export interface TestRunOptionalParams extends OperationOptions { /** Optional parameters. */ export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } /** Optional parameters. */ export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { + /** Content type. */ contentType?: string; } @@ -51,21 +51,11 @@ export interface GetTestRunFileOptionalParams extends OperationOptions {} export interface ListMetricDimensionValuesOptionalParams extends OperationOptions { /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } /** Optional parameters. */ -export interface ListMetricDefinitionsOptionalParams extends OperationOptions { - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; -} +export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface ListMetricNamespacesOptionalParams extends OperationOptions {} @@ -75,16 +65,7 @@ export interface ListMetricsOptionalParams extends OperationOptions { /** The aggregation */ aggregation?: string; /** The interval (i.e. timegrain) of the query. */ - interval?: Interval; - /** Metric name */ - metricName?: string; - /** Metric namespace to query metric definitions for. */ - metricNamespace?: string; - /** - * The timespan of the query. It is a string with the following format - * 'startDateTime_ISO/endDateTime_ISO'. - */ - timespan?: string; + interval?: TimeGrain; } /** Optional parameters. */ @@ -102,10 +83,10 @@ export interface ListTestRunsOptionalParams extends OperationOptions { search?: string; /** Unique name of an existing load test. */ testId?: string; - /** Start DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionFrom?: string; - /** End DateTime(ISO 8601 literal format) of test-run execution time filter range. */ - executionTo?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date; /** Comma separated list of test run status. */ status?: string; /** Number of results in response. */ @@ -113,4 +94,4 @@ export interface ListTestRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopTestRunOptionalParams extends OperationOptions {} +export interface StopOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts deleted file mode 100644 index a96372d9f9..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/restorePollerHelpers.ts +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - PollerLike, - OperationState, - deserializeState, - ResourceLocationConfig, -} from "@azure/core-lro"; -import { TestRunOperationsClient } from "./testRunOperationsClient.js"; -import { getLongRunningPoller } from "./api/pollingHelpers.js"; -import { _testRunDeserialize } from "./api/operations.js"; -import { - PathUncheckedResponse, - OperationOptions, -} from "@azure-rest/core-client"; -import { AbortSignalLike } from "@azure/abort-controller"; - -export interface RestorePollerOptions< - TResult, - TResponse extends PathUncheckedResponse = PathUncheckedResponse, -> extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** - * The signal which can be used to abort requests. - */ - abortSignal?: AbortSignalLike; - /** Deserialization function for raw response body */ - processResponseBody?: (result: TResponse) => Promise; -} - -/** - * Creates a poller from the serialized state of another poller. This can be - * useful when you want to create pollers on a different host or a poller - * needs to be constructed after the original one is not in scope. - */ -export function restorePoller( - client: TestRunOperationsClient, - serializedState: string, - sourceOperation: ( - ...args: any[] - ) => PollerLike, TResult>, - options?: RestorePollerOptions, -): PollerLike, TResult> { - const pollerConfig = deserializeState(serializedState).config; - const { initialRequestUrl, requestMethod, metadata } = pollerConfig; - if (!initialRequestUrl || !requestMethod) { - throw new Error( - `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, - ); - } - const resourceLocationConfig = metadata?.["resourceLocationConfig"] as - | ResourceLocationConfig - | undefined; - const deserializeHelper = - options?.processResponseBody ?? - getDeserializationHelper(initialRequestUrl, requestMethod); - if (!deserializeHelper) { - throw new Error( - `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, - ); - } - return getLongRunningPoller( - (client as any)["_client"] ?? client, - deserializeHelper as (result: TResponse) => Promise, - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - resourceLocationConfig, - restoreFrom: serializedState, - initialRequestUrl, - }, - ); -} - -const deserializeMap: Record = { - "PATCH /test-runs/{testRunId}": _testRunDeserialize, -}; - -function getDeserializationHelper( - urlStr: string, - method: string, -): ((result: unknown) => Promise) | undefined { - const path = new URL(urlStr).pathname; - const pathParts = path.split("/"); - - // Traverse list to match the longest candidate - // matchedLen: the length of candidate path - // matchedValue: the matched status code array - let matchedLen = -1, - matchedValue: ((result: unknown) => Promise) | undefined; - - // Iterate the responseMap to find a match - for (const [key, value] of Object.entries(deserializeMap)) { - // Extracting the path from the map key which is in format - // GET /path/foo - if (!key.startsWith(method)) { - continue; - } - const candidatePath = getPathFromMapKey(key); - // Get each part of the url path - const candidateParts = candidatePath.split("/"); - - // track if we have found a match to return the values found. - let found = true; - for ( - let i = candidateParts.length - 1, j = pathParts.length - 1; - i >= 1 && j >= 1; - i--, j-- - ) { - if ( - candidateParts[i]?.startsWith("{") && - candidateParts[i]?.indexOf("}") !== -1 - ) { - const start = candidateParts[i]!.indexOf("}") + 1, - end = candidateParts[i]?.length; - // If the current part of the candidate is a "template" part - // Try to use the suffix of pattern to match the path - // {guid} ==> $ - // {guid}:export ==> :export$ - const isMatched = new RegExp( - `${candidateParts[i]?.slice(start, end)}`, - ).test(pathParts[j] || ""); - - if (!isMatched) { - found = false; - break; - } - continue; - } - - // If the candidate part is not a template and - // the parts don't match mark the candidate as not found - // to move on with the next candidate path. - if (candidateParts[i] !== pathParts[j]) { - found = false; - break; - } - } - - // We finished evaluating the current candidate parts - // Update the matched value if and only if we found the longer pattern - if (found && candidatePath.length > matchedLen) { - matchedLen = candidatePath.length; - matchedValue = value as (result: unknown) => Promise; - } - } - - return matchedValue; -} - -function getPathFromMapKey(mapKey: string): string { - const pathStart = mapKey.indexOf("/"); - return mapKey.slice(pathStart); -} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts index 89148e5863..286f8219cb 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testRunOperations/testRunOperationsClient.ts @@ -1,12 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { PollerLike, OperationState } from "@azure/core-lro"; import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - FileInfo, TestRun, + TestRunFileInfo, TestRunAppComponents, TestRunServerMetricConfig, DimensionValueList, @@ -16,7 +15,7 @@ import { TimeSeriesElement, } from "./models/models.js"; import { - TestRunOptionalParams, + CreateOrUpdateTestRunOptionalParams, CreateOrUpdateAppComponentsOptionalParams, CreateOrUpdateServerMetricsConfigOptionalParams, DeleteTestRunOptionalParams, @@ -29,11 +28,11 @@ import { ListMetricNamespacesOptionalParams, ListMetricsOptionalParams, ListTestRunsOptionalParams, - StopTestRunOptionalParams, + StopOptionalParams, } from "./models/options.js"; import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { - testRun, + createOrUpdateTestRun, createOrUpdateAppComponents, createOrUpdateServerMetricsConfig, deleteTestRun, @@ -46,16 +45,16 @@ import { listMetricNamespaces, listMetrics, listTestRuns, - stopTestRun, + stop, createTestRunOperations, TestRunOperationsClientOptionalParams, - AzureLoadTestingContext, + LoadTestServiceContext, } from "./api/index.js"; export { TestRunOperationsClientOptionalParams } from "./api/testRunOperationsContext.js"; export class TestRunOperationsClient { - private _client: AzureLoadTestingContext; + private _client: LoadTestServiceContext; /** The pipeline used by this client to make requests */ public readonly pipeline: Pipeline; @@ -76,16 +75,16 @@ export class TestRunOperationsClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given name. */ - testRun( + /** Create and start a new test run with the given test run Id. */ + createOrUpdateTestRun( testRunId: string, - resource: TestRun, - options: TestRunOptionalParams = { requestOptions: {} }, - ): PollerLike, TestRun> { - return testRun(this._client, testRunId, resource, options); + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTestRun(this._client, testRunId, body, options); } - /** Associate an app component (collection of azure resources) to a test run */ + /** Add an app component to a test run by providing the resource Id, name and type. */ createOrUpdateAppComponents( testRunId: string, body: TestRunAppComponents, @@ -110,7 +109,7 @@ export class TestRunOperationsClient { ); } - /** Delete a test run by its name. */ + /** Delete an existing load test run by providing the testRunId. */ deleteTestRun( testRunId: string, options: DeleteTestRunOptionalParams = { requestOptions: {} }, @@ -129,7 +128,7 @@ export class TestRunOperationsClient { return getAppComponents(this._client, testRunId, options); } - /** List server metrics configuration for the given test run. */ + /** Get associated server metrics configuration for the given test run. */ getServerMetricsConfig( testRunId: string, options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, @@ -137,7 +136,7 @@ export class TestRunOperationsClient { return getServerMetricsConfig(this._client, testRunId, options); } - /** Get test run details by name. */ + /** Get test run details by test run Id. */ getTestRun( testRunId: string, options: GetTestRunOptionalParams = { requestOptions: {} }, @@ -150,7 +149,7 @@ export class TestRunOperationsClient { testRunId: string, fileName: string, options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise { + ): Promise { return getTestRunFile(this._client, testRunId, fileName, options); } @@ -158,14 +157,18 @@ export class TestRunOperationsClient { listMetricDimensionValues( testRunId: string, name: string, + metricname: string, metricNamespace: string, + timespan: string, options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { + ): Promise { return listMetricDimensionValues( this._client, testRunId, name, + metricname, metricNamespace, + timespan, options, ); } @@ -173,9 +176,15 @@ export class TestRunOperationsClient { /** List the metric definitions for a load test run. */ listMetricDefinitions( testRunId: string, + metricNamespace: string, options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): Promise { - return listMetricDefinitions(this._client, testRunId, options); + return listMetricDefinitions( + this._client, + testRunId, + metricNamespace, + options, + ); } /** List the metric namespaces for a load test run. */ @@ -189,24 +198,35 @@ export class TestRunOperationsClient { /** List the metric values for a load test run. */ listMetrics( testRunId: string, - body: MetricRequestPayload, + metricname: string, + metricNamespace: string, + timespan: string, + body?: MetricRequestPayload, options: ListMetricsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { - return listMetrics(this._client, testRunId, body, options); + return listMetrics( + this._client, + testRunId, + metricname, + metricNamespace, + timespan, + body, + options, + ); } - /** Get all test runs with given filters */ + /** Get all test runs for the given filters. */ listTestRuns( options: ListTestRunsOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } - /** Stop test run by name. */ - stopTestRun( + /** Stop test run by test run Id. */ + stop( testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + options: StopOptionalParams = { requestOptions: {} }, ): Promise { - return stopTestRun(this._client, testRunId, options); + return stop(this._client, testRunId, options); } } From c2da92650bd3b4a0cedc8c95e6a26be8ad89020c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 16 Jul 2024 20:42:26 +0800 Subject: [PATCH 18/18] Update the changes --- .../resiliency/srv-driven-main/generated/src/api/index.ts | 2 +- .../generated/src/api/serviceDrivenContext.ts | 4 ++-- .../resiliency/srv-driven-main/generated/src/index.ts | 2 +- .../srv-driven-main/generated/src/serviceDrivenClient.ts | 6 +++--- .../resiliency/srv-driven-old/generated/src/api/index.ts | 2 +- .../generated/src/api/serviceDrivenContext.ts | 4 ++-- .../resiliency/srv-driven-old/generated/src/index.ts | 2 +- .../srv-driven-old/generated/src/serviceDrivenClient.ts | 6 +++--- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/index.ts index 884e3fd740..879698b46b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/index.ts @@ -9,6 +9,6 @@ export { } from "./operations.js"; export { createServiceDriven, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, ServiceDrivenContext, } from "./serviceDrivenContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/serviceDrivenContext.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/serviceDrivenContext.ts index f2a9fe30a6..23edef8bd3 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/serviceDrivenContext.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/api/serviceDrivenContext.ts @@ -6,7 +6,7 @@ import { ServiceDrivenContext } from "../rest/index.js"; import getClient from "../rest/index.js"; /** Optional parameters for the client. */ -export interface ServiceDrivenClientOptions extends ClientOptions { +export interface ServiceDrivenClientOptionalParams extends ClientOptions { /** Pass in either 'v1' or 'v2'. This represents the API version of a service. */ apiVersion?: string; } @@ -28,7 +28,7 @@ export { ServiceDrivenContext } from "../rest/index.js"; export function createServiceDriven( endpointParam: string, serviceDeploymentVersion: string, - options: ServiceDrivenClientOptions = {}, + options: ServiceDrivenClientOptionalParams = {}, ): ServiceDrivenContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/index.ts index b36468a33c..bb0419219d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/index.ts @@ -3,7 +3,7 @@ export { ServiceDrivenClient, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, } from "./serviceDrivenClient.js"; export { Versions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/serviceDrivenClient.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/serviceDrivenClient.ts index ec8ac41278..62d4e52cc2 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/serviceDrivenClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/generated/src/serviceDrivenClient.ts @@ -14,11 +14,11 @@ import { fromOneRequired, fromOneOptional, createServiceDriven, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, ServiceDrivenContext, } from "./api/index.js"; -export { ServiceDrivenClientOptions } from "./api/serviceDrivenContext.js"; +export { ServiceDrivenClientOptionalParams } from "./api/serviceDrivenContext.js"; export class ServiceDrivenClient { private _client: ServiceDrivenContext; @@ -40,7 +40,7 @@ export class ServiceDrivenClient { constructor( endpointParam: string, serviceDeploymentVersion: string, - options: ServiceDrivenClientOptions = {}, + options: ServiceDrivenClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/index.ts index d917f1252e..4dcc2b1b0c 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/index.ts @@ -4,6 +4,6 @@ export { fromNone, fromOneRequired, fromOneOptional } from "./operations.js"; export { createServiceDriven, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, ServiceDrivenContext, } from "./serviceDrivenContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/serviceDrivenContext.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/serviceDrivenContext.ts index be21c283f8..fccb73b774 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/serviceDrivenContext.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/api/serviceDrivenContext.ts @@ -6,7 +6,7 @@ import { ServiceDrivenContext } from "../rest/index.js"; import getClient from "../rest/index.js"; /** Optional parameters for the client. */ -export interface ServiceDrivenClientOptions extends ClientOptions { +export interface ServiceDrivenClientOptionalParams extends ClientOptions { /** Pass in 'v1'. This represents the API version of the service. Will grow up in the next deployment to be both 'v1' and 'v2' */ apiVersion?: string; } @@ -17,7 +17,7 @@ export { ServiceDrivenContext } from "../rest/index.js"; export function createServiceDriven( endpointParam: string, serviceDeploymentVersion: string, - options: ServiceDrivenClientOptions = {}, + options: ServiceDrivenClientOptionalParams = {}, ): ServiceDrivenContext { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/index.ts index 5c54d394c0..9395a4e1ab 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/index.ts @@ -3,7 +3,7 @@ export { ServiceDrivenClient, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, } from "./serviceDrivenClient.js"; export { Versions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/serviceDrivenClient.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/serviceDrivenClient.ts index 49ec1d7fdc..b508dce51e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/serviceDrivenClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/generated/src/serviceDrivenClient.ts @@ -12,11 +12,11 @@ import { fromOneRequired, fromOneOptional, createServiceDriven, - ServiceDrivenClientOptions, + ServiceDrivenClientOptionalParams, ServiceDrivenContext, } from "./api/index.js"; -export { ServiceDrivenClientOptions } from "./api/serviceDrivenContext.js"; +export { ServiceDrivenClientOptionalParams } from "./api/serviceDrivenContext.js"; export class ServiceDrivenClient { private _client: ServiceDrivenContext; @@ -27,7 +27,7 @@ export class ServiceDrivenClient { constructor( endpointParam: string, serviceDeploymentVersion: string, - options: ServiceDrivenClientOptions = {}, + options: ServiceDrivenClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions