diff --git a/sdk/communication/communication-job-router-rest/CHANGELOG.md b/sdk/communication/communication-job-router-rest/CHANGELOG.md index 76a338687404..eaed990721cb 100644 --- a/sdk/communication/communication-job-router-rest/CHANGELOG.md +++ b/sdk/communication/communication-job-router-rest/CHANGELOG.md @@ -1,14 +1,10 @@ # Release History -## 1.1.0-beta.2 (Unreleased) +## 1.1.0-beta.2 (2024-12-16) ### Features Added -### Breaking Changes - -### Bugs Fixed - -### Other Changes +- refresh @azure-rest/communication-job-router sdk ## 1.1.0-beta.1 (2024-04-12) diff --git a/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts b/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts new file mode 100644 index 000000000000..a518300f3123 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/azureCommunicationRoutingServiceClient.ts @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "./logger.js"; +import { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; + +/** The optional parameters for the client */ +export interface AzureCommunicationRoutingServiceClientOptions + extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + +/** + * Initialize a new instance of `AzureCommunicationRoutingServiceClient` + * @param endpointParam - Uri of your Communication resource + * @param options - the parameter for all optional parameters + */ +export default function createClient( + endpointParam: string, + { + apiVersion = "2024-01-18-preview", + ...options + }: AzureCommunicationRoutingServiceClientOptions = {}, +): AzureCommunicationRoutingServiceClient { + const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const userAgentInfo = `azsdk-js-communication-job-router-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + const client = getClient( + endpointUrl, + options, + ) as AzureCommunicationRoutingServiceClient; + + 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/sdk/communication/communication-job-router-rest/generated/clientDefinitions.ts b/sdk/communication/communication-job-router-rest/generated/clientDefinitions.ts new file mode 100644 index 000000000000..2a68137400e3 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/clientDefinitions.ts @@ -0,0 +1,436 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +import { + UpsertClassificationPolicyParameters, + GetClassificationPolicyParameters, + DeleteClassificationPolicyParameters, + ListClassificationPoliciesParameters, + UpsertDistributionPolicyParameters, + GetDistributionPolicyParameters, + DeleteDistributionPolicyParameters, + ListDistributionPoliciesParameters, + UpsertExceptionPolicyParameters, + GetExceptionPolicyParameters, + DeleteExceptionPolicyParameters, + ListExceptionPoliciesParameters, + UpsertQueueParameters, + GetQueueParameters, + DeleteQueueParameters, + ListQueuesParameters, + UpsertJobParameters, + GetJobParameters, + DeleteJobParameters, + ReclassifyParameters, + CancelParameters, + CompleteParameters, + CloseParameters, + ListJobsParameters, + GetInQueuePositionParameters, + UnassignParameters, + AcceptParameters, + DeclineParameters, + GetQueueStatisticsParameters, + UpsertWorkerParameters, + GetWorkerParameters, + DeleteWorkerParameters, + ListWorkersParameters, +} from "./parameters.js"; +import type { + UpsertClassificationPolicy200Response, + UpsertClassificationPolicy201Response, + UpsertClassificationPolicyDefaultResponse, + GetClassificationPolicy200Response, + GetClassificationPolicyDefaultResponse, + DeleteClassificationPolicy204Response, + DeleteClassificationPolicyDefaultResponse, + ListClassificationPolicies200Response, + ListClassificationPoliciesDefaultResponse, + UpsertDistributionPolicy200Response, + UpsertDistributionPolicy201Response, + UpsertDistributionPolicyDefaultResponse, + GetDistributionPolicy200Response, + GetDistributionPolicyDefaultResponse, + DeleteDistributionPolicy204Response, + DeleteDistributionPolicyDefaultResponse, + ListDistributionPolicies200Response, + ListDistributionPoliciesDefaultResponse, + UpsertExceptionPolicy200Response, + UpsertExceptionPolicy201Response, + UpsertExceptionPolicyDefaultResponse, + GetExceptionPolicy200Response, + GetExceptionPolicyDefaultResponse, + DeleteExceptionPolicy204Response, + DeleteExceptionPolicyDefaultResponse, + ListExceptionPolicies200Response, + ListExceptionPoliciesDefaultResponse, + UpsertQueue200Response, + UpsertQueue201Response, + UpsertQueueDefaultResponse, + GetQueue200Response, + GetQueueDefaultResponse, + DeleteQueue204Response, + DeleteQueueDefaultResponse, + ListQueues200Response, + ListQueuesDefaultResponse, + UpsertJob200Response, + UpsertJob201Response, + UpsertJobDefaultResponse, + GetJob200Response, + GetJobDefaultResponse, + DeleteJob204Response, + DeleteJobDefaultResponse, + Reclassify200Response, + ReclassifyDefaultResponse, + Cancel200Response, + CancelDefaultResponse, + Complete200Response, + CompleteDefaultResponse, + Close200Response, + CloseDefaultResponse, + ListJobs200Response, + ListJobsDefaultResponse, + GetInQueuePosition200Response, + GetInQueuePositionDefaultResponse, + Unassign200Response, + UnassignDefaultResponse, + Accept200Response, + AcceptDefaultResponse, + Decline200Response, + DeclineDefaultResponse, + GetQueueStatistics200Response, + GetQueueStatisticsDefaultResponse, + UpsertWorker200Response, + UpsertWorker201Response, + UpsertWorkerDefaultResponse, + GetWorker200Response, + GetWorkerDefaultResponse, + DeleteWorker204Response, + DeleteWorkerDefaultResponse, + ListWorkers200Response, + ListWorkersDefaultResponse, +} from "./responses.js"; +import type { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface UpsertClassificationPolicy { + /** Creates or updates a classification policy. */ + patch( + options: UpsertClassificationPolicyParameters, + ): StreamableMethod< + | UpsertClassificationPolicy200Response + | UpsertClassificationPolicy201Response + | UpsertClassificationPolicyDefaultResponse + >; + /** Retrieves an existing classification policy by Id. */ + get( + options?: GetClassificationPolicyParameters, + ): StreamableMethod< + GetClassificationPolicy200Response | GetClassificationPolicyDefaultResponse + >; + /** Delete a classification policy by Id. */ + delete( + options?: DeleteClassificationPolicyParameters, + ): StreamableMethod< + | DeleteClassificationPolicy204Response + | DeleteClassificationPolicyDefaultResponse + >; +} + +export interface ListClassificationPolicies { + /** Retrieves existing classification policies. */ + get( + options?: ListClassificationPoliciesParameters, + ): StreamableMethod< + | ListClassificationPolicies200Response + | ListClassificationPoliciesDefaultResponse + >; +} + +export interface UpsertDistributionPolicy { + /** Creates or updates a distribution policy. */ + patch( + options: UpsertDistributionPolicyParameters, + ): StreamableMethod< + | UpsertDistributionPolicy200Response + | UpsertDistributionPolicy201Response + | UpsertDistributionPolicyDefaultResponse + >; + /** Retrieves an existing distribution policy by Id. */ + get( + options?: GetDistributionPolicyParameters, + ): StreamableMethod< + GetDistributionPolicy200Response | GetDistributionPolicyDefaultResponse + >; + /** Delete a distribution policy by Id. */ + delete( + options?: DeleteDistributionPolicyParameters, + ): StreamableMethod< + | DeleteDistributionPolicy204Response + | DeleteDistributionPolicyDefaultResponse + >; +} + +export interface ListDistributionPolicies { + /** Retrieves existing distribution policies. */ + get( + options?: ListDistributionPoliciesParameters, + ): StreamableMethod< + | ListDistributionPolicies200Response + | ListDistributionPoliciesDefaultResponse + >; +} + +export interface UpsertExceptionPolicy { + /** Creates or updates a exception policy. */ + patch( + options: UpsertExceptionPolicyParameters, + ): StreamableMethod< + | UpsertExceptionPolicy200Response + | UpsertExceptionPolicy201Response + | UpsertExceptionPolicyDefaultResponse + >; + /** Retrieves an existing exception policy by Id. */ + get( + options?: GetExceptionPolicyParameters, + ): StreamableMethod< + GetExceptionPolicy200Response | GetExceptionPolicyDefaultResponse + >; + /** Deletes a exception policy by Id. */ + delete( + options?: DeleteExceptionPolicyParameters, + ): StreamableMethod< + DeleteExceptionPolicy204Response | DeleteExceptionPolicyDefaultResponse + >; +} + +export interface ListExceptionPolicies { + /** Retrieves existing exception policies. */ + get( + options?: ListExceptionPoliciesParameters, + ): StreamableMethod< + ListExceptionPolicies200Response | ListExceptionPoliciesDefaultResponse + >; +} + +export interface UpsertQueue { + /** Creates or updates a queue. */ + patch( + options: UpsertQueueParameters, + ): StreamableMethod< + UpsertQueue200Response | UpsertQueue201Response | UpsertQueueDefaultResponse + >; + /** Retrieves an existing queue by Id. */ + get( + options?: GetQueueParameters, + ): StreamableMethod; + /** Deletes a queue by Id. */ + delete( + options?: DeleteQueueParameters, + ): StreamableMethod; +} + +export interface ListQueues { + /** Retrieves existing queues. */ + get( + options?: ListQueuesParameters, + ): StreamableMethod; +} + +export interface UpsertJob { + /** Creates or updates a router job. */ + patch( + options: UpsertJobParameters, + ): StreamableMethod< + UpsertJob200Response | UpsertJob201Response | UpsertJobDefaultResponse + >; + /** Retrieves an existing job by Id. */ + get( + options?: GetJobParameters, + ): StreamableMethod; + /** Deletes a job and all of its traces. */ + delete( + options?: DeleteJobParameters, + ): StreamableMethod; +} + +export interface Reclassify { + /** Reclassify a job. */ + post( + options?: ReclassifyParameters, + ): StreamableMethod; +} + +export interface Cancel { + /** Submits request to cancel an existing job by Id while supplying free-form cancellation reason. */ + post( + options?: CancelParameters, + ): StreamableMethod; +} + +export interface Complete { + /** Completes an assigned job. */ + post( + options?: CompleteParameters, + ): StreamableMethod; +} + +export interface Close { + /** Closes a completed job. */ + post( + options?: CloseParameters, + ): StreamableMethod; +} + +export interface ListJobs { + /** Retrieves list of jobs based on filter parameters. */ + get( + options?: ListJobsParameters, + ): StreamableMethod; +} + +export interface GetInQueuePosition { + /** Gets a job's position details. */ + get( + options?: GetInQueuePositionParameters, + ): StreamableMethod< + GetInQueuePosition200Response | GetInQueuePositionDefaultResponse + >; +} + +export interface Unassign { + /** Unassign a job. */ + post( + options?: UnassignParameters, + ): StreamableMethod; +} + +export interface Accept { + /** Accepts an offer to work on a job and returns a 409/Conflict if another agent accepted the job already. */ + post( + options?: AcceptParameters, + ): StreamableMethod; +} + +export interface Decline { + /** Declines an offer to work on a job. */ + post( + options?: DeclineParameters, + ): StreamableMethod; +} + +export interface GetQueueStatistics { + /** Retrieves a queue's statistics. */ + get( + options?: GetQueueStatisticsParameters, + ): StreamableMethod< + GetQueueStatistics200Response | GetQueueStatisticsDefaultResponse + >; +} + +export interface UpsertWorker { + /** Creates or updates a worker. */ + patch( + options: UpsertWorkerParameters, + ): StreamableMethod< + | UpsertWorker200Response + | UpsertWorker201Response + | UpsertWorkerDefaultResponse + >; + /** Retrieves an existing worker by Id. */ + get( + options?: GetWorkerParameters, + ): StreamableMethod; + /** Deletes a worker and all of its traces. */ + delete( + options?: DeleteWorkerParameters, + ): StreamableMethod; +} + +export interface ListWorkers { + /** Retrieves existing workers. */ + get( + options?: ListWorkersParameters, + ): StreamableMethod; +} + +export interface Routes { + /** Resource for '/routing/classificationPolicies/\{classificationPolicyId\}' has methods for the following verbs: patch, get, delete */ + ( + path: "/routing/classificationPolicies/{classificationPolicyId}", + classificationPolicyId: string, + ): UpsertClassificationPolicy; + /** Resource for '/routing/classificationPolicies' has methods for the following verbs: get */ + (path: "/routing/classificationPolicies"): ListClassificationPolicies; + /** Resource for '/routing/distributionPolicies/\{distributionPolicyId\}' has methods for the following verbs: patch, get, delete */ + ( + path: "/routing/distributionPolicies/{distributionPolicyId}", + distributionPolicyId: string, + ): UpsertDistributionPolicy; + /** Resource for '/routing/distributionPolicies' has methods for the following verbs: get */ + (path: "/routing/distributionPolicies"): ListDistributionPolicies; + /** Resource for '/routing/exceptionPolicies/\{exceptionPolicyId\}' has methods for the following verbs: patch, get, delete */ + ( + path: "/routing/exceptionPolicies/{exceptionPolicyId}", + exceptionPolicyId: string, + ): UpsertExceptionPolicy; + /** Resource for '/routing/exceptionPolicies' has methods for the following verbs: get */ + (path: "/routing/exceptionPolicies"): ListExceptionPolicies; + /** Resource for '/routing/queues/\{queueId\}' has methods for the following verbs: patch, get, delete */ + (path: "/routing/queues/{queueId}", queueId: string): UpsertQueue; + /** Resource for '/routing/queues' has methods for the following verbs: get */ + (path: "/routing/queues"): ListQueues; + /** Resource for '/routing/jobs/\{jobId\}' has methods for the following verbs: patch, get, delete */ + (path: "/routing/jobs/{jobId}", jobId: string): UpsertJob; + /** Resource for '/routing/jobs/\{jobId\}:reclassify' has methods for the following verbs: post */ + (path: "/routing/jobs/{jobId}:reclassify", jobId: string): Reclassify; + /** Resource for '/routing/jobs/\{jobId\}:cancel' has methods for the following verbs: post */ + (path: "/routing/jobs/{jobId}:cancel", jobId: string): Cancel; + /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:complete' has methods for the following verbs: post */ + ( + path: "/routing/jobs/{jobId}/assignments/{assignmentId}:complete", + jobId: string, + assignmentId: string, + ): Complete; + /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:close' has methods for the following verbs: post */ + ( + path: "/routing/jobs/{jobId}/assignments/{assignmentId}:close", + jobId: string, + assignmentId: string, + ): Close; + /** Resource for '/routing/jobs' has methods for the following verbs: get */ + (path: "/routing/jobs"): ListJobs; + /** Resource for '/routing/jobs/\{jobId\}/position' has methods for the following verbs: get */ + (path: "/routing/jobs/{jobId}/position", jobId: string): GetInQueuePosition; + /** Resource for '/routing/jobs/\{jobId\}/assignments/\{assignmentId\}:unassign' has methods for the following verbs: post */ + ( + path: "/routing/jobs/{jobId}/assignments/{assignmentId}:unassign", + jobId: string, + assignmentId: string, + ): Unassign; + /** Resource for '/routing/workers/\{workerId\}/offers/\{offerId\}:accept' has methods for the following verbs: post */ + ( + path: "/routing/workers/{workerId}/offers/{offerId}:accept", + workerId: string, + offerId: string, + ): Accept; + /** Resource for '/routing/workers/\{workerId\}/offers/\{offerId\}:decline' has methods for the following verbs: post */ + ( + path: "/routing/workers/{workerId}/offers/{offerId}:decline", + workerId: string, + offerId: string, + ): Decline; + /** Resource for '/routing/queues/\{queueId\}/statistics' has methods for the following verbs: get */ + ( + path: "/routing/queues/{queueId}/statistics", + queueId: string, + ): GetQueueStatistics; + /** Resource for '/routing/workers/\{workerId\}' has methods for the following verbs: patch, get, delete */ + (path: "/routing/workers/{workerId}", workerId: string): UpsertWorker; + /** Resource for '/routing/workers' has methods for the following verbs: get */ + (path: "/routing/workers"): ListWorkers; +} + +export type AzureCommunicationRoutingServiceClient = Client & { + path: Routes; +}; diff --git a/sdk/communication/communication-job-router-rest/generated/index.ts b/sdk/communication/communication-job-router-rest/generated/index.ts new file mode 100644 index 000000000000..1c1e0181dcda --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/index.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceClient.js"; + +export * from "./azureCommunicationRoutingServiceClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./isUnexpected.js"; +export * from "./models.js"; +export * from "./outputModels.js"; +export * from "./paginateHelper.js"; + +export default AzureCommunicationRoutingServiceClient; diff --git a/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts b/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts new file mode 100644 index 000000000000..db118337e18e --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/isUnexpected.ts @@ -0,0 +1,439 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + UpsertClassificationPolicy200Response, + UpsertClassificationPolicy201Response, + UpsertClassificationPolicyDefaultResponse, + GetClassificationPolicy200Response, + GetClassificationPolicyDefaultResponse, + DeleteClassificationPolicy204Response, + DeleteClassificationPolicyDefaultResponse, + ListClassificationPolicies200Response, + ListClassificationPoliciesDefaultResponse, + UpsertDistributionPolicy200Response, + UpsertDistributionPolicy201Response, + UpsertDistributionPolicyDefaultResponse, + GetDistributionPolicy200Response, + GetDistributionPolicyDefaultResponse, + DeleteDistributionPolicy204Response, + DeleteDistributionPolicyDefaultResponse, + ListDistributionPolicies200Response, + ListDistributionPoliciesDefaultResponse, + UpsertExceptionPolicy200Response, + UpsertExceptionPolicy201Response, + UpsertExceptionPolicyDefaultResponse, + GetExceptionPolicy200Response, + GetExceptionPolicyDefaultResponse, + DeleteExceptionPolicy204Response, + DeleteExceptionPolicyDefaultResponse, + ListExceptionPolicies200Response, + ListExceptionPoliciesDefaultResponse, + UpsertQueue200Response, + UpsertQueue201Response, + UpsertQueueDefaultResponse, + GetQueue200Response, + GetQueueDefaultResponse, + DeleteQueue204Response, + DeleteQueueDefaultResponse, + ListQueues200Response, + ListQueuesDefaultResponse, + UpsertJob200Response, + UpsertJob201Response, + UpsertJobDefaultResponse, + GetJob200Response, + GetJobDefaultResponse, + DeleteJob204Response, + DeleteJobDefaultResponse, + Reclassify200Response, + ReclassifyDefaultResponse, + Cancel200Response, + CancelDefaultResponse, + Complete200Response, + CompleteDefaultResponse, + Close200Response, + CloseDefaultResponse, + ListJobs200Response, + ListJobsDefaultResponse, + GetInQueuePosition200Response, + GetInQueuePositionDefaultResponse, + Unassign200Response, + UnassignDefaultResponse, + Accept200Response, + AcceptDefaultResponse, + Decline200Response, + DeclineDefaultResponse, + GetQueueStatistics200Response, + GetQueueStatisticsDefaultResponse, + UpsertWorker200Response, + UpsertWorker201Response, + UpsertWorkerDefaultResponse, + GetWorker200Response, + GetWorkerDefaultResponse, + DeleteWorker204Response, + DeleteWorkerDefaultResponse, + ListWorkers200Response, + ListWorkersDefaultResponse, +} from "./responses.js"; + +const responseMap: Record = { + "PATCH /routing/classificationPolicies/{classificationPolicyId}": [ + "200", + "201", + ], + "GET /routing/classificationPolicies/{classificationPolicyId}": ["200"], + "DELETE /routing/classificationPolicies/{classificationPolicyId}": ["204"], + "GET /routing/classificationPolicies": ["200"], + "PATCH /routing/distributionPolicies/{distributionPolicyId}": ["200", "201"], + "GET /routing/distributionPolicies/{distributionPolicyId}": ["200"], + "DELETE /routing/distributionPolicies/{distributionPolicyId}": ["204"], + "GET /routing/distributionPolicies": ["200"], + "PATCH /routing/exceptionPolicies/{exceptionPolicyId}": ["200", "201"], + "GET /routing/exceptionPolicies/{exceptionPolicyId}": ["200"], + "DELETE /routing/exceptionPolicies/{exceptionPolicyId}": ["204"], + "GET /routing/exceptionPolicies": ["200"], + "PATCH /routing/queues/{queueId}": ["200", "201"], + "GET /routing/queues/{queueId}": ["200"], + "DELETE /routing/queues/{queueId}": ["204"], + "GET /routing/queues": ["200"], + "PATCH /routing/jobs/{jobId}": ["200", "201"], + "GET /routing/jobs/{jobId}": ["200"], + "DELETE /routing/jobs/{jobId}": ["204"], + "POST /routing/jobs/{jobId}:reclassify": ["200"], + "POST /routing/jobs/{jobId}:cancel": ["200"], + "POST /routing/jobs/{jobId}/assignments/{assignmentId}:complete": ["200"], + "POST /routing/jobs/{jobId}/assignments/{assignmentId}:close": ["200"], + "GET /routing/jobs": ["200"], + "GET /routing/jobs/{jobId}/position": ["200"], + "POST /routing/jobs/{jobId}/assignments/{assignmentId}:unassign": ["200"], + "POST /routing/workers/{workerId}/offers/{offerId}:accept": ["200"], + "POST /routing/workers/{workerId}/offers/{offerId}:decline": ["200"], + "GET /routing/queues/{queueId}/statistics": ["200"], + "PATCH /routing/workers/{workerId}": ["200", "201"], + "GET /routing/workers/{workerId}": ["200"], + "DELETE /routing/workers/{workerId}": ["204"], + "GET /routing/workers": ["200"], +}; + +export function isUnexpected( + response: + | UpsertClassificationPolicy200Response + | UpsertClassificationPolicy201Response + | UpsertClassificationPolicyDefaultResponse, +): response is UpsertClassificationPolicyDefaultResponse; +export function isUnexpected( + response: + | GetClassificationPolicy200Response + | GetClassificationPolicyDefaultResponse, +): response is GetClassificationPolicyDefaultResponse; +export function isUnexpected( + response: + | DeleteClassificationPolicy204Response + | DeleteClassificationPolicyDefaultResponse, +): response is DeleteClassificationPolicyDefaultResponse; +export function isUnexpected( + response: + | ListClassificationPolicies200Response + | ListClassificationPoliciesDefaultResponse, +): response is ListClassificationPoliciesDefaultResponse; +export function isUnexpected( + response: + | UpsertDistributionPolicy200Response + | UpsertDistributionPolicy201Response + | UpsertDistributionPolicyDefaultResponse, +): response is UpsertDistributionPolicyDefaultResponse; +export function isUnexpected( + response: + | GetDistributionPolicy200Response + | GetDistributionPolicyDefaultResponse, +): response is GetDistributionPolicyDefaultResponse; +export function isUnexpected( + response: + | DeleteDistributionPolicy204Response + | DeleteDistributionPolicyDefaultResponse, +): response is DeleteDistributionPolicyDefaultResponse; +export function isUnexpected( + response: + | ListDistributionPolicies200Response + | ListDistributionPoliciesDefaultResponse, +): response is ListDistributionPoliciesDefaultResponse; +export function isUnexpected( + response: + | UpsertExceptionPolicy200Response + | UpsertExceptionPolicy201Response + | UpsertExceptionPolicyDefaultResponse, +): response is UpsertExceptionPolicyDefaultResponse; +export function isUnexpected( + response: GetExceptionPolicy200Response | GetExceptionPolicyDefaultResponse, +): response is GetExceptionPolicyDefaultResponse; +export function isUnexpected( + response: + | DeleteExceptionPolicy204Response + | DeleteExceptionPolicyDefaultResponse, +): response is DeleteExceptionPolicyDefaultResponse; +export function isUnexpected( + response: + | ListExceptionPolicies200Response + | ListExceptionPoliciesDefaultResponse, +): response is ListExceptionPoliciesDefaultResponse; +export function isUnexpected( + response: + | UpsertQueue200Response + | UpsertQueue201Response + | UpsertQueueDefaultResponse, +): response is UpsertQueueDefaultResponse; +export function isUnexpected( + response: GetQueue200Response | GetQueueDefaultResponse, +): response is GetQueueDefaultResponse; +export function isUnexpected( + response: DeleteQueue204Response | DeleteQueueDefaultResponse, +): response is DeleteQueueDefaultResponse; +export function isUnexpected( + response: ListQueues200Response | ListQueuesDefaultResponse, +): response is ListQueuesDefaultResponse; +export function isUnexpected( + response: + | UpsertJob200Response + | UpsertJob201Response + | UpsertJobDefaultResponse, +): response is UpsertJobDefaultResponse; +export function isUnexpected( + response: GetJob200Response | GetJobDefaultResponse, +): response is GetJobDefaultResponse; +export function isUnexpected( + response: DeleteJob204Response | DeleteJobDefaultResponse, +): response is DeleteJobDefaultResponse; +export function isUnexpected( + response: Reclassify200Response | ReclassifyDefaultResponse, +): response is ReclassifyDefaultResponse; +export function isUnexpected( + response: Cancel200Response | CancelDefaultResponse, +): response is CancelDefaultResponse; +export function isUnexpected( + response: Complete200Response | CompleteDefaultResponse, +): response is CompleteDefaultResponse; +export function isUnexpected( + response: Close200Response | CloseDefaultResponse, +): response is CloseDefaultResponse; +export function isUnexpected( + response: ListJobs200Response | ListJobsDefaultResponse, +): response is ListJobsDefaultResponse; +export function isUnexpected( + response: GetInQueuePosition200Response | GetInQueuePositionDefaultResponse, +): response is GetInQueuePositionDefaultResponse; +export function isUnexpected( + response: Unassign200Response | UnassignDefaultResponse, +): response is UnassignDefaultResponse; +export function isUnexpected( + response: Accept200Response | AcceptDefaultResponse, +): response is AcceptDefaultResponse; +export function isUnexpected( + response: Decline200Response | DeclineDefaultResponse, +): response is DeclineDefaultResponse; +export function isUnexpected( + response: GetQueueStatistics200Response | GetQueueStatisticsDefaultResponse, +): response is GetQueueStatisticsDefaultResponse; +export function isUnexpected( + response: + | UpsertWorker200Response + | UpsertWorker201Response + | UpsertWorkerDefaultResponse, +): response is UpsertWorkerDefaultResponse; +export function isUnexpected( + response: GetWorker200Response | GetWorkerDefaultResponse, +): response is GetWorkerDefaultResponse; +export function isUnexpected( + response: DeleteWorker204Response | DeleteWorkerDefaultResponse, +): response is DeleteWorkerDefaultResponse; +export function isUnexpected( + response: ListWorkers200Response | ListWorkersDefaultResponse, +): response is ListWorkersDefaultResponse; +export function isUnexpected( + response: + | UpsertClassificationPolicy200Response + | UpsertClassificationPolicy201Response + | UpsertClassificationPolicyDefaultResponse + | GetClassificationPolicy200Response + | GetClassificationPolicyDefaultResponse + | DeleteClassificationPolicy204Response + | DeleteClassificationPolicyDefaultResponse + | ListClassificationPolicies200Response + | ListClassificationPoliciesDefaultResponse + | UpsertDistributionPolicy200Response + | UpsertDistributionPolicy201Response + | UpsertDistributionPolicyDefaultResponse + | GetDistributionPolicy200Response + | GetDistributionPolicyDefaultResponse + | DeleteDistributionPolicy204Response + | DeleteDistributionPolicyDefaultResponse + | ListDistributionPolicies200Response + | ListDistributionPoliciesDefaultResponse + | UpsertExceptionPolicy200Response + | UpsertExceptionPolicy201Response + | UpsertExceptionPolicyDefaultResponse + | GetExceptionPolicy200Response + | GetExceptionPolicyDefaultResponse + | DeleteExceptionPolicy204Response + | DeleteExceptionPolicyDefaultResponse + | ListExceptionPolicies200Response + | ListExceptionPoliciesDefaultResponse + | UpsertQueue200Response + | UpsertQueue201Response + | UpsertQueueDefaultResponse + | GetQueue200Response + | GetQueueDefaultResponse + | DeleteQueue204Response + | DeleteQueueDefaultResponse + | ListQueues200Response + | ListQueuesDefaultResponse + | UpsertJob200Response + | UpsertJob201Response + | UpsertJobDefaultResponse + | GetJob200Response + | GetJobDefaultResponse + | DeleteJob204Response + | DeleteJobDefaultResponse + | Reclassify200Response + | ReclassifyDefaultResponse + | Cancel200Response + | CancelDefaultResponse + | Complete200Response + | CompleteDefaultResponse + | Close200Response + | CloseDefaultResponse + | ListJobs200Response + | ListJobsDefaultResponse + | GetInQueuePosition200Response + | GetInQueuePositionDefaultResponse + | Unassign200Response + | UnassignDefaultResponse + | Accept200Response + | AcceptDefaultResponse + | Decline200Response + | DeclineDefaultResponse + | GetQueueStatistics200Response + | GetQueueStatisticsDefaultResponse + | UpsertWorker200Response + | UpsertWorker201Response + | UpsertWorkerDefaultResponse + | GetWorker200Response + | GetWorkerDefaultResponse + | DeleteWorker204Response + | DeleteWorkerDefaultResponse + | ListWorkers200Response + | ListWorkersDefaultResponse, +): response is + | UpsertClassificationPolicyDefaultResponse + | GetClassificationPolicyDefaultResponse + | DeleteClassificationPolicyDefaultResponse + | ListClassificationPoliciesDefaultResponse + | UpsertDistributionPolicyDefaultResponse + | GetDistributionPolicyDefaultResponse + | DeleteDistributionPolicyDefaultResponse + | ListDistributionPoliciesDefaultResponse + | UpsertExceptionPolicyDefaultResponse + | GetExceptionPolicyDefaultResponse + | DeleteExceptionPolicyDefaultResponse + | ListExceptionPoliciesDefaultResponse + | UpsertQueueDefaultResponse + | GetQueueDefaultResponse + | DeleteQueueDefaultResponse + | ListQueuesDefaultResponse + | UpsertJobDefaultResponse + | GetJobDefaultResponse + | DeleteJobDefaultResponse + | ReclassifyDefaultResponse + | CancelDefaultResponse + | CompleteDefaultResponse + | CloseDefaultResponse + | ListJobsDefaultResponse + | GetInQueuePositionDefaultResponse + | UnassignDefaultResponse + | AcceptDefaultResponse + | DeclineDefaultResponse + | GetQueueStatisticsDefaultResponse + | UpsertWorkerDefaultResponse + | GetWorkerDefaultResponse + | DeleteWorkerDefaultResponse + | ListWorkersDefaultResponse { + const lroOriginal = response.headers["x-ms-original-url"]; + const url = new URL(lroOriginal ?? response.request.url); + const method = response.request.method; + let pathDetails = responseMap[`${method} ${url.pathname}`]; + if (!pathDetails) { + pathDetails = getParametrizedPathSuccess(method, url.pathname); + } + return !pathDetails.includes(response.status); +} + +function getParametrizedPathSuccess(method: string, path: string): string[] { + 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: string[] = []; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(responseMap)) { + // 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; + } + } + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/sdk/communication/communication-job-router-rest/generated/logger.ts b/sdk/communication/communication-job-router-rest/generated/logger.ts new file mode 100644 index 000000000000..b6132440690f --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/logger.ts @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("communication-job-router"); diff --git a/sdk/communication/communication-job-router-rest/generated/models.ts b/sdk/communication/communication-job-router-rest/generated/models.ts new file mode 100644 index 000000000000..45c45224ec50 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/models.ts @@ -0,0 +1,665 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +/** A container for the rules that govern how jobs are classified. */ +export interface ClassificationPolicy { + /** Friendly name of this policy. */ + name?: string; + /** Id of a fallback queue to select if queue selector attachments doesn't find a match. */ + fallbackQueueId?: string; + /** Queue selector attachments used to resolve a queue for a job. */ + queueSelectorAttachments?: Array; + /** A rule to determine a priority score for a job. */ + prioritizationRule?: RouterRule; + /** Worker selector attachments used to attach worker selectors to a job. */ + workerSelectorAttachments?: Array; +} + +/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ +export interface QueueSelectorAttachmentParent { + kind: QueueSelectorAttachmentKind; +} + +/** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ +export interface ConditionalQueueSelectorAttachment + extends QueueSelectorAttachmentParent { + /** The condition that must be true for the queue selectors to be attached. */ + condition: RouterRule; + /** The queue selectors to attach. */ + queueSelectors: Array; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "conditional"; +} + +/** + * A rule of one of the following types: + * StaticRule: A rule providing static rules that always return the same result, regardless of input. + * DirectMapRule: A rule that return the same labels as the input labels. + * ExpressionRule: A rule providing inline expression rules. + * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. + * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. + */ +export interface RouterRuleParent { + kind: RouterRuleKind; +} + +/** A rule that return the same labels as the input labels. */ +export interface DirectMapRouterRule extends RouterRuleParent { + /** The type discriminator describing a sub-type of Rule. */ + kind: "directMap"; +} + +/** A rule providing inline expression rules. */ +export interface ExpressionRouterRule extends RouterRuleParent { + /** + * The expression language to compile to and execute. + * + * Possible values: "powerFx" + */ + language?: ExpressionRouterRuleLanguage; + /** An expression to evaluate. Should contain return statement with calculated values. */ + expression: string; + /** The type discriminator describing a sub-type of Rule. */ + kind: "expression"; +} + +/** A rule providing a binding to an HTTP Triggered Azure Function. */ +export interface FunctionRouterRule extends RouterRuleParent { + /** URL for Azure Function. */ + functionUri: string; + /** Credentials used to access Azure function rule. */ + credential?: FunctionRouterRuleCredential; + /** The type discriminator describing a sub-type of Rule. */ + kind: "function"; +} + +/** Credentials used to access Azure function rule. */ +export interface FunctionRouterRuleCredential { + /** Access key scoped to a particular function. */ + functionKey?: string; + /** Access key scoped to a Azure Function app. This key grants access to all functions under the app. */ + appKey?: string; + /** Client id, when AppKey is provided In context of Azure function, this is usually the name of the key. */ + clientId?: string; +} + +/** A rule providing static rules that always return the same result, regardless of input. */ +export interface StaticRouterRule extends RouterRuleParent { + /** The static value this rule always returns. Values must be primitive values - number, string, boolean. */ + value?: unknown; + /** The type discriminator describing a sub-type of Rule. */ + kind: "static"; +} + +/** A rule providing a binding to an external web server. */ +export interface WebhookRouterRule extends RouterRuleParent { + /** Uri for Authorization Server. */ + authorizationServerUri?: string; + /** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ + clientCredential?: OAuth2WebhookClientCredential; + /** Uri for Contoso's Web Server. */ + webhookUri?: string; + /** The type discriminator describing a sub-type of Rule. */ + kind: "webhook"; +} + +/** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ +export interface OAuth2WebhookClientCredential { + /** ClientId for Contoso Authorization server. */ + clientId?: string; + /** Client secret for Contoso Authorization server. */ + clientSecret?: string; +} + +/** Describes a condition that must be met against a set of labels for queue selection. */ +export interface RouterQueueSelector { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value defined on the label selector. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperator; + /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ + value?: unknown; +} + +/** Attaches a queue selector where the value is passed through from a job's label with the same key. */ +export interface PassThroughQueueSelectorAttachment + extends QueueSelectorAttachmentParent { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value pass through. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperator; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "passThrough"; +} + +/** Attaches queue selectors to a job when the RouterRule is resolved. */ +export interface RuleEngineQueueSelectorAttachment + extends QueueSelectorAttachmentParent { + /** A RouterRule that resolves a collection of queue selectors to attach. */ + rule: RouterRule; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "ruleEngine"; +} + +/** Describes a queue selector that will be attached to a job. */ +export interface StaticQueueSelectorAttachment + extends QueueSelectorAttachmentParent { + /** The queue selector to attach. */ + queueSelector: RouterQueueSelector; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "static"; +} + +/** Describes multiple sets of queue selectors, of which one will be selected and attached according to a weighting. */ +export interface WeightedAllocationQueueSelectorAttachment + extends QueueSelectorAttachmentParent { + /** A collection of percentage based weighted allocations. */ + allocations: Array; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "weightedAllocation"; +} + +/** Contains the weight percentage and queue selectors to be applied if selected for weighted distributions. */ +export interface QueueWeightedAllocation { + /** The percentage of this weight, expressed as a fraction of 1. */ + weight: number; + /** A collection of queue selectors that will be applied if this allocation is selected. */ + queueSelectors: Array; +} + +/** An attachment which attaches worker selectors to a job. */ +export interface WorkerSelectorAttachmentParent { + kind: WorkerSelectorAttachmentKind; +} + +/** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ +export interface ConditionalWorkerSelectorAttachment + extends WorkerSelectorAttachmentParent { + /** The condition that must be true for the worker selectors to be attached. */ + condition: RouterRule; + /** The worker selectors to attach. */ + workerSelectors: Array; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "conditional"; +} + +/** Describes a condition that must be met against a set of labels for worker selection. */ +export interface RouterWorkerSelector { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value defined on the worker selector. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperator; + /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ + value?: unknown; + /** Describes how long this label selector is valid in seconds. */ + expiresAfterSeconds?: number; + /** Pushes a job to the front of the queue as long as this selector is active. */ + expedite?: boolean; +} + +/** Attaches a worker selector where the value is passed through from a job's label with the same key. */ +export interface PassThroughWorkerSelectorAttachment + extends WorkerSelectorAttachmentParent { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value pass through. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperator; + /** Describes how long the attached label selector is valid in seconds. */ + expiresAfterSeconds?: number; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "passThrough"; +} + +/** Attaches worker selectors to a job when a RouterRule is resolved. */ +export interface RuleEngineWorkerSelectorAttachment + extends WorkerSelectorAttachmentParent { + /** A RouterRule that resolves a collection of worker selectors to attach. */ + rule: RouterRule; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "ruleEngine"; +} + +/** Describes a worker selector that will be attached to a job. */ +export interface StaticWorkerSelectorAttachment + extends WorkerSelectorAttachmentParent { + /** The worker selector to attach. */ + workerSelector: RouterWorkerSelector; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "static"; +} + +/** Describes multiple sets of worker selectors, of which one will be selected and attached according to a weighting. */ +export interface WeightedAllocationWorkerSelectorAttachment + extends WorkerSelectorAttachmentParent { + /** A collection of percentage based weighted allocations. */ + allocations: Array; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "weightedAllocation"; +} + +/** Contains the weight percentage and worker selectors to be applied if selected for weighted distributions. */ +export interface WorkerWeightedAllocation { + /** The percentage of this weight, expressed as a fraction of 1. */ + weight: number; + /** A collection of worker selectors that will be applied if this allocation is selected. */ + workerSelectors: Array; +} + +/** Policy governing how jobs are distributed to workers */ +export interface DistributionPolicy { + /** Friendly name of this policy. */ + name?: string; + /** Number of seconds after which any offers created under this policy will be expired. */ + offerExpiresAfterSeconds?: number; + /** Mode governing the specific distribution method. */ + mode?: DistributionMode; +} + +/** Abstract base class for defining a distribution mode. */ +export interface DistributionModeParent { + /** Governs the minimum desired number of active concurrent offers a job can have. */ + minConcurrentOffers?: number; + /** Governs the maximum number of active concurrent offers a job can have. */ + maxConcurrentOffers?: number; + /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ + bypassSelectors?: boolean; + kind: DistributionModeKind; +} + +/** Jobs are distributed to the worker with the strongest abilities available. */ +export interface BestWorkerMode extends DistributionModeParent { + /** Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match and/or exceed using a logistic function (https://en.wikipedia.org/wiki/Logistic_function). */ + scoringRule?: RouterRule; + /** Options to configure 'scoringRule'. If not set, default values are used. */ + scoringRuleOptions?: ScoringRuleOptions; + /** The type discriminator describing a sub-type of Mode */ + kind: "bestWorker"; +} + +/** Encapsulates all options that can be passed as parameters for scoring rule with BestWorkerMode. */ +export interface ScoringRuleOptions { + /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ + batchSize?: number; + /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ + scoringParameters?: ScoringRuleParameterSelector[]; + /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ + isBatchScoringEnabled?: boolean; + /** If false, will sort scores by ascending order. By default, set to true. */ + descendingOrder?: boolean; +} + +/** Jobs are directed to the worker who has been idle longest. */ +export interface LongestIdleMode extends DistributionModeParent { + /** The type discriminator describing a sub-type of Mode. */ + kind: "longestIdle"; +} + +/** Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. */ +export interface RoundRobinMode extends DistributionModeParent { + /** The type discriminator describing a sub-type of Mode. */ + kind: "roundRobin"; +} + +/** A policy that defines actions to execute when exception are triggered. */ +export interface ExceptionPolicy { + /** Friendly name of this policy. */ + name?: string; + /** A collection of exception rules on the exception policy. */ + exceptionRules?: Array; +} + +/** A rule that defines actions to execute upon a specific trigger. */ +export interface ExceptionRule { + /** Id of an exception rule. */ + id: string; + /** The trigger for this exception rule. */ + trigger: ExceptionTrigger; + /** A collection of actions to perform once the exception is triggered. */ + actions: Array; +} + +/** Abstract base class for defining a trigger for exception rules. */ +export interface ExceptionTriggerParent { + kind: ExceptionTriggerKind; +} + +/** Trigger for an exception action on exceeding queue length. */ +export interface QueueLengthExceptionTrigger extends ExceptionTriggerParent { + /** Threshold of number of jobs ahead in the queue to for this trigger to fire. */ + threshold: number; + /** The type discriminator describing a sub-type of ExceptionTrigger. */ + kind: "queueLength"; +} + +/** Trigger for an exception action on exceeding wait time. */ +export interface WaitTimeExceptionTrigger extends ExceptionTriggerParent { + /** Threshold for wait time for this trigger. */ + thresholdSeconds: number; + /** The type discriminator describing a sub-type of ExceptionTrigger. */ + kind: "waitTime"; +} + +/** The action to take when the exception is triggered. */ +export interface ExceptionActionParent { + /** Unique Id of the exception action. */ + id?: string; + kind: ExceptionActionKind; +} + +/** An action that marks a job as cancelled. */ +export interface CancelExceptionAction extends ExceptionActionParent { + /** A note that will be appended to a job's notes collection with the current timestamp. */ + note?: string; + /** Indicates the outcome of a job, populate this field with your own custom values. */ + dispositionCode?: string; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "cancel"; +} + +/** An action that manually reclassifies a job by providing the queue, priority and worker selectors. */ +export interface ManualReclassifyExceptionAction extends ExceptionActionParent { + /** Updated QueueId. */ + queueId?: string; + /** Updated Priority. */ + priority?: number; + /** Updated WorkerSelectors. */ + workerSelectors?: Array; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "manualReclassify"; +} + +/** An action that modifies labels on a job and then reclassifies it. */ +export interface ReclassifyExceptionAction extends ExceptionActionParent { + /** The new classification policy that will determine queue, priority and worker selectors. */ + classificationPolicyId?: string; + /** Dictionary containing the labels to update (or add if not existing) in key-value pairs. Values must be primitive values - number, string, boolean. */ + labelsToUpsert?: Record; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "reclassify"; +} + +/** A queue that can contain jobs to be routed. */ +export interface RouterQueue { + /** Friendly name of this queue. */ + name?: string; + /** Id of a distribution policy that will determine how a job is distributed to workers. */ + distributionPolicyId?: string; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** Id of an exception policy that determines various job escalation rules. */ + exceptionPolicyId?: string; +} + +/** A unit of work to be routed */ +export interface RouterJob { + /** Reference to an external parent context, eg. call ID. */ + channelReference?: string; + /** The channel identifier. eg. voice, chat, etc. */ + channelId?: string; + /** Id of a classification policy used for classifying this job. */ + classificationPolicyId?: string; + /** Id of a queue that this job is queued to. */ + queueId?: string; + /** Priority of this job. Value must be between -100 to 100. */ + priority?: number; + /** Reason code for cancelled or closed jobs. */ + dispositionCode?: string; + /** A collection of manually specified worker selectors, which a worker must satisfy in order to process this job. */ + requestedWorkerSelectors?: Array; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** A set of non-identifying attributes attached to this job. Values must be primitive values - number, string, boolean. */ + tags?: Record; + /** Notes attached to a job, sorted by timestamp. */ + notes?: Array; + /** If provided, will determine how job matching will be carried out. Default mode: QueueAndMatchMode. */ + matchingMode?: JobMatchingMode; +} + +/** Assignment details of a job to a worker. */ +export interface RouterJobAssignment { + /** Id of the Worker assigned to the job. */ + workerId?: string; + /** Timestamp when the job was assigned to a worker in UTC. */ + assignedAt: Date | string; + /** Timestamp when the job was marked as completed after being assigned in UTC. */ + completedAt?: Date | string; + /** Timestamp when the job was marked as closed after being completed in UTC. */ + closedAt?: Date | string; +} + +/** A note attached to a job. */ +export interface RouterJobNote { + /** The message contained in the note. */ + message: string; + /** The time at which the note was added in UTC. If not provided, will default to the current time. */ + addedAt?: Date | string; +} + +/** + * A matching mode of one of the following types: + * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. + * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. + * SuspendMode: Used when matching workers to a job needs to be suspended. + */ +export interface JobMatchingModeParent { + kind: JobMatchingModeKind; +} + +/** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ +export interface ScheduleAndSuspendMode extends JobMatchingModeParent { + /** Requested schedule time. */ + scheduleAt: Date | string; + /** The type discriminator describing ScheduleAndSuspendMode */ + kind: "scheduleAndSuspend"; +} + +/** Describes a matching mode where matching worker to a job is automatically started after job is queued successfully. */ +export interface QueueAndMatchMode extends JobMatchingModeParent { + /** The type discriminator describing QueueAndMatchMode */ + kind: "queueAndMatch"; +} + +/** Describes a matching mode where matching worker to a job is suspended. */ +export interface SuspendMode extends JobMatchingModeParent { + /** The type discriminator describing SuspendMode */ + kind: "suspend"; +} + +/** Request payload for reclassifying jobs. */ +export interface ReclassifyJobOptions { } + +/** Request payload for cancelling a job. */ +export interface CancelJobOptions { + /** A note that will be appended to a job's Notes collection with the current timestamp. */ + note?: string; + /** Indicates the outcome of a job, populate this field with your own custom values. If not provided, default value of "Cancelled" is set. */ + dispositionCode?: string; +} + +/** Request payload for completing jobs. */ +export interface CompleteJobOptions { + /** A note that will be appended to a job's Notes collection with the current timestamp. */ + note?: string; +} + +/** Request payload for closing jobs */ +export interface CloseJobOptions { + /** Indicates the outcome of a job, populate this field with your own custom values. */ + dispositionCode?: string; + /** If not provided, worker capacity is released immediately along with a JobClosedEvent notification. If provided, worker capacity is released along with a JobClosedEvent notification at a future time in UTC. */ + closeAt?: Date | string; + /** A note that will be appended to a job's Notes collection with the current timestamp. */ + note?: string; +} + +/** Request payload for unassigning a job. */ +export interface UnassignJobOptions { + /** If SuspendMatching is true, then a job is not queued for re-matching with a worker. */ + suspendMatching?: boolean; +} + +/** Request payload for declining offers. */ +export interface DeclineJobOfferOptions { + /** If the RetryOfferAt is not provided, then this job will not be offered again to the worker who declined this job unless the worker is de-registered and re-registered. If a RetryOfferAt time is provided, then the job will be re-matched to eligible workers at the retry time in UTC. The worker that declined the job will also be eligible for the job at that time. */ + retryOfferAt?: Date | string; +} + +/** An entity for jobs to be routed to. */ +export interface RouterWorker { + /** Collection of queue(s) that this worker can receive work from. */ + queues?: string[]; + /** The total capacity score this worker has to manage multiple concurrent jobs. */ + capacity?: number; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** A set of non-identifying attributes attached to this worker. Values must be primitive values - number, string, boolean. */ + tags?: Record; + /** Collection of channel(s) this worker can handle and their impact on the workers capacity. */ + channels?: Array; + /** A flag indicating this worker is open to receive offers or not. */ + availableForOffers?: boolean; + /** If this is set, the worker will only receive up to this many new offers at a time. */ + maxConcurrentOffers?: number; +} + +/** Represents the capacity a job in this channel will consume from a worker. */ +export interface RouterChannel { + /** Id of a channel. */ + channelId: string; + /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ + capacityCostPerJob: number; + /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ + maxNumberOfJobs?: number; +} + +/** An offer of a job to a worker. */ +export interface RouterJobOffer { + /** Id of the job. */ + jobId: string; + /** The capacity cost consumed by the job offer. */ + capacityCost: number; + /** Timestamp when the offer was created in UTC. */ + offeredAt?: Date | string; + /** Timestamp when the offer will expire in UTC. */ + expiresAt?: Date | string; +} + +/** The assignment for a worker to a job. */ +export interface RouterWorkerAssignment { + /** Id of the assignment. */ + assignmentId: string; + /** Id of the job assigned. */ + jobId: string; + /** The amount of capacity this assignment has consumed on the worker. */ + capacityCost: number; + /** The assignment time of the job in UTC. */ + assignedAt: Date | string; +} + +/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ +export type QueueSelectorAttachment = + | QueueSelectorAttachmentParent + | ConditionalQueueSelectorAttachment + | PassThroughQueueSelectorAttachment + | RuleEngineQueueSelectorAttachment + | StaticQueueSelectorAttachment + | WeightedAllocationQueueSelectorAttachment; +/** + * A rule of one of the following types: + * StaticRule: A rule providing static rules that always return the same result, regardless of input. + * DirectMapRule: A rule that return the same labels as the input labels. + * ExpressionRule: A rule providing inline expression rules. + * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. + * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. + */ +export type RouterRule = + | RouterRuleParent + | DirectMapRouterRule + | ExpressionRouterRule + | FunctionRouterRule + | StaticRouterRule + | WebhookRouterRule; +/** An attachment which attaches worker selectors to a job. */ +export type WorkerSelectorAttachment = + | WorkerSelectorAttachmentParent + | ConditionalWorkerSelectorAttachment + | PassThroughWorkerSelectorAttachment + | RuleEngineWorkerSelectorAttachment + | StaticWorkerSelectorAttachment + | WeightedAllocationWorkerSelectorAttachment; +/** Abstract base class for defining a distribution mode. */ +export type DistributionMode = + | DistributionModeParent + | BestWorkerMode + | LongestIdleMode + | RoundRobinMode; +/** Abstract base class for defining a trigger for exception rules. */ +export type ExceptionTrigger = + | ExceptionTriggerParent + | QueueLengthExceptionTrigger + | WaitTimeExceptionTrigger; +/** The action to take when the exception is triggered. */ +export type ExceptionAction = + | ExceptionActionParent + | CancelExceptionAction + | ManualReclassifyExceptionAction + | ReclassifyExceptionAction; +/** + * A matching mode of one of the following types: + * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. + * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. + * SuspendMode: Used when matching workers to a job needs to be suspended. + */ +export type JobMatchingMode = + | JobMatchingModeParent + | ScheduleAndSuspendMode + | QueueAndMatchMode + | SuspendMode; +/** Alias for QueueSelectorAttachmentKind */ +export type QueueSelectorAttachmentKind = string; +/** Alias for RouterRuleKind */ +export type RouterRuleKind = string; +/** Alias for ExpressionRouterRuleLanguage */ +export type ExpressionRouterRuleLanguage = string; +/** Alias for LabelOperator */ +export type LabelOperator = string; +/** Alias for WorkerSelectorAttachmentKind */ +export type WorkerSelectorAttachmentKind = string; +/** Alias for RouterWorkerSelectorStatus */ +export type RouterWorkerSelectorStatus = string; +/** Alias for DistributionModeKind */ +export type DistributionModeKind = string; +/** Alias for ScoringRuleParameterSelector */ +export type ScoringRuleParameterSelector = string; +/** Alias for ExceptionTriggerKind */ +export type ExceptionTriggerKind = string; +/** Alias for ExceptionActionKind */ +export type ExceptionActionKind = string; +/** Alias for RouterJobStatus */ +export type RouterJobStatus = string; +/** Alias for JobMatchingModeKind */ +export type JobMatchingModeKind = string; +/** Alias for RouterJobStatusSelector */ +export type RouterJobStatusSelector = string; +/** Alias for RouterWorkerState */ +export type RouterWorkerState = string; +/** Alias for RouterWorkerStateSelector */ +export type RouterWorkerStateSelector = string; diff --git a/sdk/communication/communication-job-router-rest/generated/outputModels.ts b/sdk/communication/communication-job-router-rest/generated/outputModels.ts new file mode 100644 index 000000000000..ccc072ce07c3 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/outputModels.ts @@ -0,0 +1,797 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +/** A container for the rules that govern how jobs are classified. */ +export interface ClassificationPolicyOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of a classification policy. */ + readonly id: string; + /** Friendly name of this policy. */ + name?: string; + /** Id of a fallback queue to select if queue selector attachments doesn't find a match. */ + fallbackQueueId?: string; + /** Queue selector attachments used to resolve a queue for a job. */ + queueSelectorAttachments?: Array; + /** A rule to determine a priority score for a job. */ + prioritizationRule?: RouterRuleOutput; + /** Worker selector attachments used to attach worker selectors to a job. */ + workerSelectorAttachments?: Array; +} + +/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ +export interface QueueSelectorAttachmentOutputParent { + kind: QueueSelectorAttachmentKindOutput; +} + +/** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ +export interface ConditionalQueueSelectorAttachmentOutput + extends QueueSelectorAttachmentOutputParent { + /** The condition that must be true for the queue selectors to be attached. */ + condition: RouterRuleOutput; + /** The queue selectors to attach. */ + queueSelectors: Array; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "conditional"; +} + +/** + * A rule of one of the following types: + * StaticRule: A rule providing static rules that always return the same result, regardless of input. + * DirectMapRule: A rule that return the same labels as the input labels. + * ExpressionRule: A rule providing inline expression rules. + * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. + * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. + */ +export interface RouterRuleOutputParent { + kind: RouterRuleKindOutput; +} + +/** A rule that return the same labels as the input labels. */ +export interface DirectMapRouterRuleOutput extends RouterRuleOutputParent { + /** The type discriminator describing a sub-type of Rule. */ + kind: "directMap"; +} + +/** A rule providing inline expression rules. */ +export interface ExpressionRouterRuleOutput extends RouterRuleOutputParent { + /** + * The expression language to compile to and execute. + * + * Possible values: "powerFx" + */ + language?: ExpressionRouterRuleLanguageOutput; + /** An expression to evaluate. Should contain return statement with calculated values. */ + expression: string; + /** The type discriminator describing a sub-type of Rule. */ + kind: "expression"; +} + +/** A rule providing a binding to an HTTP Triggered Azure Function. */ +export interface FunctionRouterRuleOutput extends RouterRuleOutputParent { + /** URL for Azure Function. */ + functionUri: string; + /** Credentials used to access Azure function rule. */ + credential?: FunctionRouterRuleCredentialOutput; + /** The type discriminator describing a sub-type of Rule. */ + kind: "function"; +} + +/** Credentials used to access Azure function rule. */ +export interface FunctionRouterRuleCredentialOutput { + /** Access key scoped to a particular function. */ + functionKey?: string; + /** Access key scoped to a Azure Function app. This key grants access to all functions under the app. */ + appKey?: string; + /** Client id, when AppKey is provided In context of Azure function, this is usually the name of the key. */ + clientId?: string; +} + +/** A rule providing static rules that always return the same result, regardless of input. */ +export interface StaticRouterRuleOutput extends RouterRuleOutputParent { + /** The static value this rule always returns. Values must be primitive values - number, string, boolean. */ + value?: any; + /** The type discriminator describing a sub-type of Rule. */ + kind: "static"; +} + +/** A rule providing a binding to an external web server. */ +export interface WebhookRouterRuleOutput extends RouterRuleOutputParent { + /** Uri for Authorization Server. */ + authorizationServerUri?: string; + /** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ + clientCredential?: OAuth2WebhookClientCredentialOutput; + /** Uri for Contoso's Web Server. */ + webhookUri?: string; + /** The type discriminator describing a sub-type of Rule. */ + kind: "webhook"; +} + +/** OAuth2.0 Credentials used to Contoso's Authorization server. Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ */ +export interface OAuth2WebhookClientCredentialOutput { + /** ClientId for Contoso Authorization server. */ + clientId?: string; + /** Client secret for Contoso Authorization server. */ + clientSecret?: string; +} + +/** Describes a condition that must be met against a set of labels for queue selection. */ +export interface RouterQueueSelectorOutput { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value defined on the label selector. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperatorOutput; + /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ + value?: any; +} + +/** Attaches a queue selector where the value is passed through from a job's label with the same key. */ +export interface PassThroughQueueSelectorAttachmentOutput + extends QueueSelectorAttachmentOutputParent { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value pass through. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperatorOutput; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "passThrough"; +} + +/** Attaches queue selectors to a job when the RouterRule is resolved. */ +export interface RuleEngineQueueSelectorAttachmentOutput + extends QueueSelectorAttachmentOutputParent { + /** A RouterRule that resolves a collection of queue selectors to attach. */ + rule: RouterRuleOutput; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "ruleEngine"; +} + +/** Describes a queue selector that will be attached to a job. */ +export interface StaticQueueSelectorAttachmentOutput + extends QueueSelectorAttachmentOutputParent { + /** The queue selector to attach. */ + queueSelector: RouterQueueSelectorOutput; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "static"; +} + +/** Describes multiple sets of queue selectors, of which one will be selected and attached according to a weighting. */ +export interface WeightedAllocationQueueSelectorAttachmentOutput + extends QueueSelectorAttachmentOutputParent { + /** A collection of percentage based weighted allocations. */ + allocations: Array; + /** The type discriminator describing the type of queue selector attachment. */ + kind: "weightedAllocation"; +} + +/** Contains the weight percentage and queue selectors to be applied if selected for weighted distributions. */ +export interface QueueWeightedAllocationOutput { + /** The percentage of this weight, expressed as a fraction of 1. */ + weight: number; + /** A collection of queue selectors that will be applied if this allocation is selected. */ + queueSelectors: Array; +} + +/** An attachment which attaches worker selectors to a job. */ +export interface WorkerSelectorAttachmentOutputParent { + kind: WorkerSelectorAttachmentKindOutput; +} + +/** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ +export interface ConditionalWorkerSelectorAttachmentOutput + extends WorkerSelectorAttachmentOutputParent { + /** The condition that must be true for the worker selectors to be attached. */ + condition: RouterRuleOutput; + /** The worker selectors to attach. */ + workerSelectors: Array; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "conditional"; +} + +/** Describes a condition that must be met against a set of labels for worker selection. */ +export interface RouterWorkerSelectorOutput { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value defined on the worker selector. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperatorOutput; + /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ + value?: any; + /** Describes how long this label selector is valid in seconds. */ + expiresAfterSeconds?: number; + /** Pushes a job to the front of the queue as long as this selector is active. */ + expedite?: boolean; + /** + * Status of the worker selector. + * + * Possible values: "active", "expired" + */ + readonly status?: RouterWorkerSelectorStatusOutput; + /** The time at which this worker selector expires in UTC. */ + readonly expiresAt?: string; +} + +/** Attaches a worker selector where the value is passed through from a job's label with the same key. */ +export interface PassThroughWorkerSelectorAttachmentOutput + extends WorkerSelectorAttachmentOutputParent { + /** The label key to query against. */ + key: string; + /** + * Describes how the value of the label is compared to the value pass through. + * + * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" + */ + labelOperator: LabelOperatorOutput; + /** Describes how long the attached label selector is valid in seconds. */ + expiresAfterSeconds?: number; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "passThrough"; +} + +/** Attaches worker selectors to a job when a RouterRule is resolved. */ +export interface RuleEngineWorkerSelectorAttachmentOutput + extends WorkerSelectorAttachmentOutputParent { + /** A RouterRule that resolves a collection of worker selectors to attach. */ + rule: RouterRuleOutput; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "ruleEngine"; +} + +/** Describes a worker selector that will be attached to a job. */ +export interface StaticWorkerSelectorAttachmentOutput + extends WorkerSelectorAttachmentOutputParent { + /** The worker selector to attach. */ + workerSelector: RouterWorkerSelectorOutput; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "static"; +} + +/** Describes multiple sets of worker selectors, of which one will be selected and attached according to a weighting. */ +export interface WeightedAllocationWorkerSelectorAttachmentOutput + extends WorkerSelectorAttachmentOutputParent { + /** A collection of percentage based weighted allocations. */ + allocations: Array; + /** The type discriminator describing the type of worker selector attachment. */ + kind: "weightedAllocation"; +} + +/** Contains the weight percentage and worker selectors to be applied if selected for weighted distributions. */ +export interface WorkerWeightedAllocationOutput { + /** The percentage of this weight, expressed as a fraction of 1. */ + weight: number; + /** A collection of worker selectors that will be applied if this allocation is selected. */ + workerSelectors: Array; +} + +/** Paged collection of ClassificationPolicy items */ +export interface PagedClassificationPolicyOutput { + /** The ClassificationPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Policy governing how jobs are distributed to workers */ +export interface DistributionPolicyOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of a distribution policy. */ + readonly id: string; + /** Friendly name of this policy. */ + name?: string; + /** Number of seconds after which any offers created under this policy will be expired. */ + offerExpiresAfterSeconds?: number; + /** Mode governing the specific distribution method. */ + mode?: DistributionModeOutput; +} + +/** Abstract base class for defining a distribution mode. */ +export interface DistributionModeOutputParent { + /** Governs the minimum desired number of active concurrent offers a job can have. */ + minConcurrentOffers?: number; + /** Governs the maximum number of active concurrent offers a job can have. */ + maxConcurrentOffers?: number; + /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ + bypassSelectors?: boolean; + kind: DistributionModeKindOutput; +} + +/** Jobs are distributed to the worker with the strongest abilities available. */ +export interface BestWorkerModeOutput extends DistributionModeOutputParent { + /** Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match and/or exceed using a logistic function (https://en.wikipedia.org/wiki/Logistic_function). */ + scoringRule?: RouterRuleOutput; + /** Options to configure 'scoringRule'. If not set, default values are used. */ + scoringRuleOptions?: ScoringRuleOptionsOutput; + /** The type discriminator describing a sub-type of Mode */ + kind: "bestWorker"; +} + +/** Encapsulates all options that can be passed as parameters for scoring rule with BestWorkerMode. */ +export interface ScoringRuleOptionsOutput { + /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ + batchSize?: number; + /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ + scoringParameters?: ScoringRuleParameterSelectorOutput[]; + /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ + isBatchScoringEnabled?: boolean; + /** If false, will sort scores by ascending order. By default, set to true. */ + descendingOrder?: boolean; +} + +/** Jobs are directed to the worker who has been idle longest. */ +export interface LongestIdleModeOutput extends DistributionModeOutputParent { + /** The type discriminator describing a sub-type of Mode. */ + kind: "longestIdle"; +} + +/** Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. */ +export interface RoundRobinModeOutput extends DistributionModeOutputParent { + /** The type discriminator describing a sub-type of Mode. */ + kind: "roundRobin"; +} + +/** Paged collection of DistributionPolicy items */ +export interface PagedDistributionPolicyOutput { + /** The DistributionPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** A policy that defines actions to execute when exception are triggered. */ +export interface ExceptionPolicyOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of an exception policy. */ + readonly id: string; + /** Friendly name of this policy. */ + name?: string; + /** A collection of exception rules on the exception policy. */ + exceptionRules?: Array; +} + +/** A rule that defines actions to execute upon a specific trigger. */ +export interface ExceptionRuleOutput { + /** Id of an exception rule. */ + id: string; + /** The trigger for this exception rule. */ + trigger: ExceptionTriggerOutput; + /** A collection of actions to perform once the exception is triggered. */ + actions: Array; +} + +/** Abstract base class for defining a trigger for exception rules. */ +export interface ExceptionTriggerOutputParent { + kind: ExceptionTriggerKindOutput; +} + +/** Trigger for an exception action on exceeding queue length. */ +export interface QueueLengthExceptionTriggerOutput + extends ExceptionTriggerOutputParent { + /** Threshold of number of jobs ahead in the queue to for this trigger to fire. */ + threshold: number; + /** The type discriminator describing a sub-type of ExceptionTrigger. */ + kind: "queueLength"; +} + +/** Trigger for an exception action on exceeding wait time. */ +export interface WaitTimeExceptionTriggerOutput + extends ExceptionTriggerOutputParent { + /** Threshold for wait time for this trigger. */ + thresholdSeconds: number; + /** The type discriminator describing a sub-type of ExceptionTrigger. */ + kind: "waitTime"; +} + +/** The action to take when the exception is triggered. */ +export interface ExceptionActionOutputParent { + /** Unique Id of the exception action. */ + id?: string; + kind: ExceptionActionKindOutput; +} + +/** An action that marks a job as cancelled. */ +export interface CancelExceptionActionOutput + extends ExceptionActionOutputParent { + /** A note that will be appended to a job's notes collection with the current timestamp. */ + note?: string; + /** Indicates the outcome of a job, populate this field with your own custom values. */ + dispositionCode?: string; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "cancel"; +} + +/** An action that manually reclassifies a job by providing the queue, priority and worker selectors. */ +export interface ManualReclassifyExceptionActionOutput + extends ExceptionActionOutputParent { + /** Updated QueueId. */ + queueId?: string; + /** Updated Priority. */ + priority?: number; + /** Updated WorkerSelectors. */ + workerSelectors?: Array; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "manualReclassify"; +} + +/** An action that modifies labels on a job and then reclassifies it. */ +export interface ReclassifyExceptionActionOutput + extends ExceptionActionOutputParent { + /** The new classification policy that will determine queue, priority and worker selectors. */ + classificationPolicyId?: string; + /** Dictionary containing the labels to update (or add if not existing) in key-value pairs. Values must be primitive values - number, string, boolean. */ + labelsToUpsert?: Record; + /** The type discriminator describing a sub-type of ExceptionAction. */ + kind: "reclassify"; +} + +/** Paged collection of ExceptionPolicy items */ +export interface PagedExceptionPolicyOutput { + /** The ExceptionPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** A queue that can contain jobs to be routed. */ +export interface RouterQueueOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of a queue. */ + readonly id: string; + /** Friendly name of this queue. */ + name?: string; + /** Id of a distribution policy that will determine how a job is distributed to workers. */ + distributionPolicyId?: string; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** Id of an exception policy that determines various job escalation rules. */ + exceptionPolicyId?: string; +} + +/** Paged collection of RouterQueue items */ +export interface PagedRouterQueueOutput { + /** The RouterQueue items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** A unit of work to be routed */ +export interface RouterJobOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of a job. */ + readonly id: string; + /** Reference to an external parent context, eg. call ID. */ + channelReference?: string; + /** + * The status of the job. + * + * Possible values: "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation" + */ + readonly status?: RouterJobStatusOutput; + /** Timestamp a job was queued in UTC. */ + readonly enqueuedAt?: string; + /** The channel identifier. eg. voice, chat, etc. */ + channelId?: string; + /** Id of a classification policy used for classifying this job. */ + classificationPolicyId?: string; + /** Id of a queue that this job is queued to. */ + queueId?: string; + /** Priority of this job. Value must be between -100 to 100. */ + priority?: number; + /** Reason code for cancelled or closed jobs. */ + dispositionCode?: string; + /** A collection of manually specified worker selectors, which a worker must satisfy in order to process this job. */ + requestedWorkerSelectors?: Array; + /** A collection of worker selectors attached by a classification policy, which a worker must satisfy in order to process this job. */ + readonly attachedWorkerSelectors?: Array; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** A collection of the assignments of the job. Key is AssignmentId. */ + readonly assignments?: Record; + /** A set of non-identifying attributes attached to this job. Values must be primitive values - number, string, boolean. */ + tags?: Record; + /** Notes attached to a job, sorted by timestamp. */ + notes?: Array; + /** If set, job will be scheduled to be enqueued at a given time. */ + readonly scheduledAt?: string; + /** If provided, will determine how job matching will be carried out. Default mode: QueueAndMatchMode. */ + matchingMode?: JobMatchingModeOutput; +} + +/** Assignment details of a job to a worker. */ +export interface RouterJobAssignmentOutput { + /** Id of a job assignment. */ + readonly assignmentId: string; + /** Id of the Worker assigned to the job. */ + workerId?: string; + /** Timestamp when the job was assigned to a worker in UTC. */ + assignedAt: string; + /** Timestamp when the job was marked as completed after being assigned in UTC. */ + completedAt?: string; + /** Timestamp when the job was marked as closed after being completed in UTC. */ + closedAt?: string; +} + +/** A note attached to a job. */ +export interface RouterJobNoteOutput { + /** The message contained in the note. */ + message: string; + /** The time at which the note was added in UTC. If not provided, will default to the current time. */ + addedAt?: string; +} + +/** + * A matching mode of one of the following types: + * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. + * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. + * SuspendMode: Used when matching workers to a job needs to be suspended. + */ +export interface JobMatchingModeOutputParent { + kind: JobMatchingModeKindOutput; +} + +/** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ +export interface ScheduleAndSuspendModeOutput + extends JobMatchingModeOutputParent { + /** Requested schedule time. */ + scheduleAt: string; + /** The type discriminator describing ScheduleAndSuspendMode */ + kind: "scheduleAndSuspend"; +} + +/** Describes a matching mode where matching worker to a job is automatically started after job is queued successfully. */ +export interface QueueAndMatchModeOutput extends JobMatchingModeOutputParent { + /** The type discriminator describing QueueAndMatchMode */ + kind: "queueAndMatch"; +} + +/** Describes a matching mode where matching worker to a job is suspended. */ +export interface SuspendModeOutput extends JobMatchingModeOutputParent { + /** The type discriminator describing SuspendMode */ + kind: "suspend"; +} + +/** Response payload from reclassifying a job. */ +export interface ReclassifyJobResultOutput { } + +/** Response payload from cancelling a job. */ +export interface CancelJobResultOutput { } + +/** Response payload from completing a job. */ +export interface CompleteJobResultOutput { } + +/** Response payload from closing a job. */ +export interface CloseJobResultOutput { } + +/** Paged collection of RouterJob items */ +export interface PagedRouterJobOutput { + /** The RouterJob items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** Position and estimated wait time for a job. */ +export interface RouterJobPositionDetailsOutput { + /** Id of the job these details are about. */ + jobId: string; + /** Position of the job in question within that queue. */ + position: number; + /** Id of the queue this job is enqueued in. */ + queueId: string; + /** Length of the queue: total number of enqueued jobs. */ + queueLength: number; + /** Estimated wait time of the job rounded up to the nearest minute. */ + estimatedWaitTimeMinutes: number; +} + +/** Response payload after a job has been successfully unassigned. */ +export interface UnassignJobResultOutput { + /** Id of an unassigned job. */ + jobId: string; + /** The number of times a job is unassigned. At a maximum 3. */ + unassignmentCount: number; +} + +/** Response containing ids for the worker, job, and assignment from an accepted offer. */ +export interface AcceptJobOfferResultOutput { + /** Id of job assignment that assigns a worker that has accepted an offer to a job. */ + assignmentId: string; + /** Id of the job assigned. */ + jobId: string; + /** Id of the worker that has been assigned this job. */ + workerId: string; +} + +/** Response payload from declining a job. */ +export interface DeclineJobOfferResultOutput { } + +/** Statistics for the queue. */ +export interface RouterQueueStatisticsOutput { + /** Id of the queue these details are about. */ + queueId: string; + /** Length of the queue: total number of enqueued jobs. */ + length: number; + /** The estimated wait time of this queue rounded up to the nearest minute, grouped by job priority. */ + estimatedWaitTimeMinutes?: Record; + /** The wait time of the job that has been enqueued in this queue for the longest. */ + longestJobWaitTimeMinutes?: number; +} + +/** An entity for jobs to be routed to. */ +export interface RouterWorkerOutput { + /** The entity tag for this resource. */ + readonly etag: string; + /** Id of a worker. */ + readonly id: string; + /** + * Current state of a worker. + * + * Possible values: "active", "draining", "inactive" + */ + readonly state?: RouterWorkerStateOutput; + /** Collection of queue(s) that this worker can receive work from. */ + queues?: string[]; + /** The total capacity score this worker has to manage multiple concurrent jobs. */ + capacity?: number; + /** A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean. */ + labels?: Record; + /** A set of non-identifying attributes attached to this worker. Values must be primitive values - number, string, boolean. */ + tags?: Record; + /** Collection of channel(s) this worker can handle and their impact on the workers capacity. */ + channels?: Array; + /** A list of active offers issued to this worker. */ + readonly offers?: Array; + /** A list of assigned jobs attached to this worker. */ + readonly assignedJobs?: Array; + /** A value indicating the workers capacity. A value of '1' means all capacity is consumed. A value of '0' means no capacity is currently consumed. */ + readonly loadRatio?: number; + /** A flag indicating this worker is open to receive offers or not. */ + availableForOffers?: boolean; + /** If this is set, the worker will only receive up to this many new offers at a time. */ + maxConcurrentOffers?: number; +} + +/** Represents the capacity a job in this channel will consume from a worker. */ +export interface RouterChannelOutput { + /** Id of a channel. */ + channelId: string; + /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ + capacityCostPerJob: number; + /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ + maxNumberOfJobs?: number; +} + +/** An offer of a job to a worker. */ +export interface RouterJobOfferOutput { + /** Id of an offer. */ + readonly offerId: string; + /** Id of the job. */ + jobId: string; + /** The capacity cost consumed by the job offer. */ + capacityCost: number; + /** Timestamp when the offer was created in UTC. */ + offeredAt?: string; + /** Timestamp when the offer will expire in UTC. */ + expiresAt?: string; +} + +/** The assignment for a worker to a job. */ +export interface RouterWorkerAssignmentOutput { + /** Id of the assignment. */ + assignmentId: string; + /** Id of the job assigned. */ + jobId: string; + /** The amount of capacity this assignment has consumed on the worker. */ + capacityCost: number; + /** The assignment time of the job in UTC. */ + assignedAt: string; +} + +/** Paged collection of RouterWorker items */ +export interface PagedRouterWorkerOutput { + /** The RouterWorker items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + +/** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ +export type QueueSelectorAttachmentOutput = + | QueueSelectorAttachmentOutputParent + | ConditionalQueueSelectorAttachmentOutput + | PassThroughQueueSelectorAttachmentOutput + | RuleEngineQueueSelectorAttachmentOutput + | StaticQueueSelectorAttachmentOutput + | WeightedAllocationQueueSelectorAttachmentOutput; +/** + * A rule of one of the following types: + * StaticRule: A rule providing static rules that always return the same result, regardless of input. + * DirectMapRule: A rule that return the same labels as the input labels. + * ExpressionRule: A rule providing inline expression rules. + * FunctionRule: A rule providing a binding to an HTTP Triggered Azure Function. + * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. + */ +export type RouterRuleOutput = + | RouterRuleOutputParent + | DirectMapRouterRuleOutput + | ExpressionRouterRuleOutput + | FunctionRouterRuleOutput + | StaticRouterRuleOutput + | WebhookRouterRuleOutput; +/** An attachment which attaches worker selectors to a job. */ +export type WorkerSelectorAttachmentOutput = + | WorkerSelectorAttachmentOutputParent + | ConditionalWorkerSelectorAttachmentOutput + | PassThroughWorkerSelectorAttachmentOutput + | RuleEngineWorkerSelectorAttachmentOutput + | StaticWorkerSelectorAttachmentOutput + | WeightedAllocationWorkerSelectorAttachmentOutput; +/** Abstract base class for defining a distribution mode. */ +export type DistributionModeOutput = + | DistributionModeOutputParent + | BestWorkerModeOutput + | LongestIdleModeOutput + | RoundRobinModeOutput; +/** Abstract base class for defining a trigger for exception rules. */ +export type ExceptionTriggerOutput = + | ExceptionTriggerOutputParent + | QueueLengthExceptionTriggerOutput + | WaitTimeExceptionTriggerOutput; +/** The action to take when the exception is triggered. */ +export type ExceptionActionOutput = + | ExceptionActionOutputParent + | CancelExceptionActionOutput + | ManualReclassifyExceptionActionOutput + | ReclassifyExceptionActionOutput; +/** + * A matching mode of one of the following types: + * QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. + * ScheduleAndSuspendMode: Used for scheduling jobs to be queued at a future time. At specified time, matching of a worker to the job will not start automatically. + * SuspendMode: Used when matching workers to a job needs to be suspended. + */ +export type JobMatchingModeOutput = + | JobMatchingModeOutputParent + | ScheduleAndSuspendModeOutput + | QueueAndMatchModeOutput + | SuspendModeOutput; +/** Alias for QueueSelectorAttachmentKindOutput */ +export type QueueSelectorAttachmentKindOutput = string; +/** Alias for RouterRuleKindOutput */ +export type RouterRuleKindOutput = string; +/** Alias for ExpressionRouterRuleLanguageOutput */ +export type ExpressionRouterRuleLanguageOutput = string; +/** Alias for LabelOperatorOutput */ +export type LabelOperatorOutput = string; +/** Alias for WorkerSelectorAttachmentKindOutput */ +export type WorkerSelectorAttachmentKindOutput = string; +/** Alias for RouterWorkerSelectorStatusOutput */ +export type RouterWorkerSelectorStatusOutput = string; +/** Alias for DistributionModeKindOutput */ +export type DistributionModeKindOutput = string; +/** Alias for ScoringRuleParameterSelectorOutput */ +export type ScoringRuleParameterSelectorOutput = string; +/** Alias for ExceptionTriggerKindOutput */ +export type ExceptionTriggerKindOutput = string; +/** Alias for ExceptionActionKindOutput */ +export type ExceptionActionKindOutput = string; +/** Alias for RouterJobStatusOutput */ +export type RouterJobStatusOutput = string; +/** Alias for JobMatchingModeKindOutput */ +export type JobMatchingModeKindOutput = string; +/** Alias for RouterWorkerStateOutput */ +export type RouterWorkerStateOutput = string; diff --git a/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts b/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts new file mode 100644 index 000000000000..9358a3f884b0 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/paginateHelper.ts @@ -0,0 +1,298 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * 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 = PageSettings, + TLink = string, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + (((settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken as unknown as TLink | undefined, + }); + }) as unknown as ( + settings?: TPageSettings, + ) => AsyncIterableIterator), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: TLink; + } = {}, +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + yield response.page; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield response.page; + } +} + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * 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 = 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. + */ +interface PagedResult { + /** + * Link to the first page of results. + */ + firstPageLink: TLink; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink: TLink, + ) => Promise<{ page: TPage; nextPageLink?: TLink } | 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) => unknown[]; +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = (pageLink: string) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends { + body: { value?: infer TPage }; +} + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {}, +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + const itemName = "value"; + const nextLinkName = "nextLink"; + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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 { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/sdk/communication/communication-job-router-rest/generated/parameters.ts b/sdk/communication/communication-job-router-rest/generated/parameters.ts new file mode 100644 index 000000000000..8f66b8ee3ddc --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/parameters.ts @@ -0,0 +1,354 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +import { RawHttpHeadersInput } from "@azure/core-rest-pipeline"; +import { RequestParameters } from "@azure-rest/core-client"; +import { + ClassificationPolicy, + DistributionPolicy, + ExceptionPolicy, + RouterQueue, + RouterJob, + ReclassifyJobOptions, + CancelJobOptions, + CompleteJobOptions, + CloseJobOptions, + RouterJobStatusSelector, + UnassignJobOptions, + DeclineJobOfferOptions, + RouterWorker, + RouterWorkerStateSelector, +} from "./models.js"; + +export interface UpsertClassificationPolicyHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type ClassificationPolicyResourceMergeAndPatch = + Partial; + +export interface UpsertClassificationPolicyBodyParam { + /** The resource instance. */ + body: ClassificationPolicyResourceMergeAndPatch; +} + +export interface UpsertClassificationPolicyHeaderParam { + headers?: RawHttpHeadersInput & UpsertClassificationPolicyHeaders; +} + +export interface UpsertClassificationPolicyMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertClassificationPolicyParameters = + UpsertClassificationPolicyHeaderParam & + UpsertClassificationPolicyMediaTypesParam & + UpsertClassificationPolicyBodyParam & + RequestParameters; +export type GetClassificationPolicyParameters = RequestParameters; +export type DeleteClassificationPolicyParameters = RequestParameters; + +export interface ListClassificationPoliciesQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; +} + +export interface ListClassificationPoliciesQueryParam { + queryParameters?: ListClassificationPoliciesQueryParamProperties; +} + +export type ListClassificationPoliciesParameters = + ListClassificationPoliciesQueryParam & RequestParameters; + +export interface UpsertDistributionPolicyHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type DistributionPolicyResourceMergeAndPatch = + Partial; + +export interface UpsertDistributionPolicyBodyParam { + /** The resource instance. */ + body: DistributionPolicyResourceMergeAndPatch; +} + +export interface UpsertDistributionPolicyHeaderParam { + headers?: RawHttpHeadersInput & UpsertDistributionPolicyHeaders; +} + +export interface UpsertDistributionPolicyMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertDistributionPolicyParameters = + UpsertDistributionPolicyHeaderParam & + UpsertDistributionPolicyMediaTypesParam & + UpsertDistributionPolicyBodyParam & + RequestParameters; +export type GetDistributionPolicyParameters = RequestParameters; +export type DeleteDistributionPolicyParameters = RequestParameters; + +export interface ListDistributionPoliciesQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; +} + +export interface ListDistributionPoliciesQueryParam { + queryParameters?: ListDistributionPoliciesQueryParamProperties; +} + +export type ListDistributionPoliciesParameters = + ListDistributionPoliciesQueryParam & RequestParameters; + +export interface UpsertExceptionPolicyHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type ExceptionPolicyResourceMergeAndPatch = Partial; + +export interface UpsertExceptionPolicyBodyParam { + /** The resource instance. */ + body: ExceptionPolicyResourceMergeAndPatch; +} + +export interface UpsertExceptionPolicyHeaderParam { + headers?: RawHttpHeadersInput & UpsertExceptionPolicyHeaders; +} + +export interface UpsertExceptionPolicyMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertExceptionPolicyParameters = UpsertExceptionPolicyHeaderParam & + UpsertExceptionPolicyMediaTypesParam & + UpsertExceptionPolicyBodyParam & + RequestParameters; +export type GetExceptionPolicyParameters = RequestParameters; +export type DeleteExceptionPolicyParameters = RequestParameters; + +export interface ListExceptionPoliciesQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; +} + +export interface ListExceptionPoliciesQueryParam { + queryParameters?: ListExceptionPoliciesQueryParamProperties; +} + +export type ListExceptionPoliciesParameters = ListExceptionPoliciesQueryParam & + RequestParameters; + +export interface UpsertQueueHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type RouterQueueResourceMergeAndPatch = Partial; + +export interface UpsertQueueBodyParam { + /** The resource instance. */ + body: RouterQueueResourceMergeAndPatch; +} + +export interface UpsertQueueHeaderParam { + headers?: RawHttpHeadersInput & UpsertQueueHeaders; +} + +export interface UpsertQueueMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertQueueParameters = UpsertQueueHeaderParam & + UpsertQueueMediaTypesParam & + UpsertQueueBodyParam & + RequestParameters; +export type GetQueueParameters = RequestParameters; +export type DeleteQueueParameters = RequestParameters; + +export interface ListQueuesQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; +} + +export interface ListQueuesQueryParam { + queryParameters?: ListQueuesQueryParamProperties; +} + +export type ListQueuesParameters = ListQueuesQueryParam & RequestParameters; + +export interface UpsertJobHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type RouterJobResourceMergeAndPatch = Partial; + +export interface UpsertJobBodyParam { + /** The resource instance. */ + body: RouterJobResourceMergeAndPatch; +} + +export interface UpsertJobHeaderParam { + headers?: RawHttpHeadersInput & UpsertJobHeaders; +} + +export interface UpsertJobMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertJobParameters = UpsertJobHeaderParam & + UpsertJobMediaTypesParam & + UpsertJobBodyParam & + RequestParameters; +export type GetJobParameters = RequestParameters; +export type DeleteJobParameters = RequestParameters; + +export interface ReclassifyBodyParam { + /** Request object for reclassifying a job. */ + body?: ReclassifyJobOptions; +} + +export type ReclassifyParameters = ReclassifyBodyParam & RequestParameters; + +export interface CancelBodyParam { + /** Request model for cancelling job. */ + body?: CancelJobOptions; +} + +export type CancelParameters = CancelBodyParam & RequestParameters; + +export interface CompleteBodyParam { + /** Request model for completing job. */ + body?: CompleteJobOptions; +} + +export type CompleteParameters = CompleteBodyParam & RequestParameters; + +export interface CloseBodyParam { + /** Request model for closing job. */ + body?: CloseJobOptions; +} + +export type CloseParameters = CloseBodyParam & RequestParameters; + +export interface ListJobsQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; + /** + * If specified, filter jobs by status. + * + * Possible values: "all", "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation", "active" + */ + status?: RouterJobStatusSelector; + /** If specified, filter jobs by queue. */ + queueId?: string; + /** If specified, filter jobs by channel. */ + channelId?: string; + /** If specified, filter jobs by classificationPolicy. */ + classificationPolicyId?: string; + /** If specified, filter on jobs that was scheduled before or at given timestamp. Range: (-Inf, scheduledBefore]. */ + scheduledBefore?: Date | string; + /** If specified, filter on jobs that was scheduled at or after given value. Range: [scheduledAfter, +Inf). */ + scheduledAfter?: Date | string; +} + +export interface ListJobsQueryParam { + queryParameters?: ListJobsQueryParamProperties; +} + +export type ListJobsParameters = ListJobsQueryParam & RequestParameters; +export type GetInQueuePositionParameters = RequestParameters; + +export interface UnassignBodyParam { + /** Request body for unassign route. */ + body?: UnassignJobOptions; +} + +export type UnassignParameters = UnassignBodyParam & RequestParameters; +export type AcceptParameters = RequestParameters; + +export interface DeclineBodyParam { + /** Request model for declining offer. */ + body?: DeclineJobOfferOptions; +} + +export type DeclineParameters = DeclineBodyParam & RequestParameters; +export type GetQueueStatisticsParameters = RequestParameters; + +export interface UpsertWorkerHeaders { + /** The request should only proceed if an entity matches this string. */ + "If-Match"?: string; + /** The request should only proceed if the entity was not modified after this time. */ + "If-Unmodified-Since"?: string; +} + +/** The resource instance. */ +export type RouterWorkerResourceMergeAndPatch = Partial; + +export interface UpsertWorkerBodyParam { + /** The resource instance. */ + body: RouterWorkerResourceMergeAndPatch; +} + +export interface UpsertWorkerHeaderParam { + headers?: RawHttpHeadersInput & UpsertWorkerHeaders; +} + +export interface UpsertWorkerMediaTypesParam { + /** This request has a JSON Merge Patch body. */ + contentType: "application/merge-patch+json"; +} + +export type UpsertWorkerParameters = UpsertWorkerHeaderParam & + UpsertWorkerMediaTypesParam & + UpsertWorkerBodyParam & + RequestParameters; +export type GetWorkerParameters = RequestParameters; +export type DeleteWorkerParameters = RequestParameters; + +export interface ListWorkersQueryParamProperties { + /** Number of objects to return per page. */ + maxpagesize?: number; + /** + * If specified, select workers by worker state. + * + * Possible values: "active", "draining", "inactive", "all" + */ + state?: RouterWorkerStateSelector; + /** If specified, select workers who have a channel configuration with this channel. */ + channelId?: string; + /** If specified, select workers who are assigned to this queue. */ + queueId?: string; + /** If set to true, select only workers who have capacity for the channel specified by `channelId` or for any channel if `channelId` not specified. If set to false, then will return all workers including workers without any capacity for jobs. Defaults to false. */ + hasCapacity?: boolean; +} + +export interface ListWorkersQueryParam { + queryParameters?: ListWorkersQueryParamProperties; +} + +export type ListWorkersParameters = ListWorkersQueryParam & RequestParameters; diff --git a/sdk/communication/communication-job-router-rest/generated/responses.ts b/sdk/communication/communication-job-router-rest/generated/responses.ts new file mode 100644 index 000000000000..41b88d424c24 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/generated/responses.ts @@ -0,0 +1,767 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + + +import { RawHttpHeaders } from "@azure/core-rest-pipeline"; +import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; +import { + ClassificationPolicyOutput, + PagedClassificationPolicyOutput, + DistributionPolicyOutput, + PagedDistributionPolicyOutput, + ExceptionPolicyOutput, + PagedExceptionPolicyOutput, + RouterQueueOutput, + PagedRouterQueueOutput, + RouterJobOutput, + ReclassifyJobResultOutput, + CancelJobResultOutput, + CompleteJobResultOutput, + CloseJobResultOutput, + PagedRouterJobOutput, + RouterJobPositionDetailsOutput, + UnassignJobResultOutput, + AcceptJobOfferResultOutput, + DeclineJobOfferResultOutput, + RouterQueueStatisticsOutput, + RouterWorkerOutput, + PagedRouterWorkerOutput, +} from "./outputModels.js"; + +export interface UpsertClassificationPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertClassificationPolicy200Response extends HttpResponse { + status: "200"; + body: ClassificationPolicyOutput; + headers: RawHttpHeaders & UpsertClassificationPolicy200Headers; +} + +export interface UpsertClassificationPolicy201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertClassificationPolicy201Response extends HttpResponse { + status: "201"; + body: ClassificationPolicyOutput; + headers: RawHttpHeaders & UpsertClassificationPolicy201Headers; +} + +export interface UpsertClassificationPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertClassificationPolicyDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertClassificationPolicyDefaultHeaders; +} + +export interface GetClassificationPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetClassificationPolicy200Response extends HttpResponse { + status: "200"; + body: ClassificationPolicyOutput; + headers: RawHttpHeaders & GetClassificationPolicy200Headers; +} + +export interface GetClassificationPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetClassificationPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetClassificationPolicyDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteClassificationPolicy204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteClassificationPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteClassificationPolicyDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteClassificationPolicyDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListClassificationPolicies200Response extends HttpResponse { + status: "200"; + body: PagedClassificationPolicyOutput; +} + +export interface ListClassificationPoliciesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListClassificationPoliciesDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListClassificationPoliciesDefaultHeaders; +} + +export interface UpsertDistributionPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertDistributionPolicy200Response extends HttpResponse { + status: "200"; + body: DistributionPolicyOutput; + headers: RawHttpHeaders & UpsertDistributionPolicy200Headers; +} + +export interface UpsertDistributionPolicy201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertDistributionPolicy201Response extends HttpResponse { + status: "201"; + body: DistributionPolicyOutput; + headers: RawHttpHeaders & UpsertDistributionPolicy201Headers; +} + +export interface UpsertDistributionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertDistributionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertDistributionPolicyDefaultHeaders; +} + +export interface GetDistributionPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetDistributionPolicy200Response extends HttpResponse { + status: "200"; + body: DistributionPolicyOutput; + headers: RawHttpHeaders & GetDistributionPolicy200Headers; +} + +export interface GetDistributionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetDistributionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetDistributionPolicyDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteDistributionPolicy204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteDistributionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteDistributionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteDistributionPolicyDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListDistributionPolicies200Response extends HttpResponse { + status: "200"; + body: PagedDistributionPolicyOutput; +} + +export interface ListDistributionPoliciesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListDistributionPoliciesDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListDistributionPoliciesDefaultHeaders; +} + +export interface UpsertExceptionPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertExceptionPolicy200Response extends HttpResponse { + status: "200"; + body: ExceptionPolicyOutput; + headers: RawHttpHeaders & UpsertExceptionPolicy200Headers; +} + +export interface UpsertExceptionPolicy201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertExceptionPolicy201Response extends HttpResponse { + status: "201"; + body: ExceptionPolicyOutput; + headers: RawHttpHeaders & UpsertExceptionPolicy201Headers; +} + +export interface UpsertExceptionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertExceptionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertExceptionPolicyDefaultHeaders; +} + +export interface GetExceptionPolicy200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetExceptionPolicy200Response extends HttpResponse { + status: "200"; + body: ExceptionPolicyOutput; + headers: RawHttpHeaders & GetExceptionPolicy200Headers; +} + +export interface GetExceptionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetExceptionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetExceptionPolicyDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteExceptionPolicy204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteExceptionPolicyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteExceptionPolicyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteExceptionPolicyDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListExceptionPolicies200Response extends HttpResponse { + status: "200"; + body: PagedExceptionPolicyOutput; +} + +export interface ListExceptionPoliciesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListExceptionPoliciesDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListExceptionPoliciesDefaultHeaders; +} + +export interface UpsertQueue200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertQueue200Response extends HttpResponse { + status: "200"; + body: RouterQueueOutput; + headers: RawHttpHeaders & UpsertQueue200Headers; +} + +export interface UpsertQueue201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertQueue201Response extends HttpResponse { + status: "201"; + body: RouterQueueOutput; + headers: RawHttpHeaders & UpsertQueue201Headers; +} + +export interface UpsertQueueDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertQueueDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertQueueDefaultHeaders; +} + +export interface GetQueue200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetQueue200Response extends HttpResponse { + status: "200"; + body: RouterQueueOutput; + headers: RawHttpHeaders & GetQueue200Headers; +} + +export interface GetQueueDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetQueueDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetQueueDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteQueue204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteQueueDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteQueueDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteQueueDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListQueues200Response extends HttpResponse { + status: "200"; + body: PagedRouterQueueOutput; +} + +export interface ListQueuesDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListQueuesDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListQueuesDefaultHeaders; +} + +export interface UpsertJob200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertJob200Response extends HttpResponse { + status: "200"; + body: RouterJobOutput; + headers: RawHttpHeaders & UpsertJob200Headers; +} + +export interface UpsertJob201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertJob201Response extends HttpResponse { + status: "201"; + body: RouterJobOutput; + headers: RawHttpHeaders & UpsertJob201Headers; +} + +export interface UpsertJobDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertJobDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertJobDefaultHeaders; +} + +export interface GetJob200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetJob200Response extends HttpResponse { + status: "200"; + body: RouterJobOutput; + headers: RawHttpHeaders & GetJob200Headers; +} + +export interface GetJobDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetJobDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetJobDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteJob204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteJobDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteJobDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteJobDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Reclassify200Response extends HttpResponse { + status: "200"; + body: ReclassifyJobResultOutput; +} + +export interface ReclassifyDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ReclassifyDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ReclassifyDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Cancel200Response extends HttpResponse { + status: "200"; + body: CancelJobResultOutput; +} + +export interface CancelDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface CancelDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & CancelDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Complete200Response extends HttpResponse { + status: "200"; + body: CompleteJobResultOutput; +} + +export interface CompleteDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface CompleteDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & CompleteDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Close200Response extends HttpResponse { + status: "200"; + body: CloseJobResultOutput; +} + +export interface CloseDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface CloseDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & CloseDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListJobs200Response extends HttpResponse { + status: "200"; + body: PagedRouterJobOutput; +} + +export interface ListJobsDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListJobsDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListJobsDefaultHeaders; +} + +/** The request has succeeded. */ +export interface GetInQueuePosition200Response extends HttpResponse { + status: "200"; + body: RouterJobPositionDetailsOutput; +} + +export interface GetInQueuePositionDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetInQueuePositionDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetInQueuePositionDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Unassign200Response extends HttpResponse { + status: "200"; + body: UnassignJobResultOutput; +} + +export interface UnassignDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UnassignDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UnassignDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Accept200Response extends HttpResponse { + status: "200"; + body: AcceptJobOfferResultOutput; +} + +export interface AcceptDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface AcceptDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & AcceptDefaultHeaders; +} + +/** The request has succeeded. */ +export interface Decline200Response extends HttpResponse { + status: "200"; + body: DeclineJobOfferResultOutput; +} + +export interface DeclineDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeclineDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeclineDefaultHeaders; +} + +/** The request has succeeded. */ +export interface GetQueueStatistics200Response extends HttpResponse { + status: "200"; + body: RouterQueueStatisticsOutput; +} + +export interface GetQueueStatisticsDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetQueueStatisticsDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetQueueStatisticsDefaultHeaders; +} + +export interface UpsertWorker200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface UpsertWorker200Response extends HttpResponse { + status: "200"; + body: RouterWorkerOutput; + headers: RawHttpHeaders & UpsertWorker200Headers; +} + +export interface UpsertWorker201Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded and a new resource has been created as a result. */ +export interface UpsertWorker201Response extends HttpResponse { + status: "201"; + body: RouterWorkerOutput; + headers: RawHttpHeaders & UpsertWorker201Headers; +} + +export interface UpsertWorkerDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface UpsertWorkerDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & UpsertWorkerDefaultHeaders; +} + +export interface GetWorker200Headers { + /** The entity tag for the response. */ + etag?: string; + /** The last modified timestamp. */ + "last-modified"?: string; +} + +/** The request has succeeded. */ +export interface GetWorker200Response extends HttpResponse { + status: "200"; + body: RouterWorkerOutput; + headers: RawHttpHeaders & GetWorker200Headers; +} + +export interface GetWorkerDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface GetWorkerDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & GetWorkerDefaultHeaders; +} + +/** There is no content to send for this request, but the headers may be useful. */ +export interface DeleteWorker204Response extends HttpResponse { + status: "204"; +} + +export interface DeleteWorkerDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface DeleteWorkerDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & DeleteWorkerDefaultHeaders; +} + +/** The request has succeeded. */ +export interface ListWorkers200Response extends HttpResponse { + status: "200"; + body: PagedRouterWorkerOutput; +} + +export interface ListWorkersDefaultHeaders { + /** String error code indicating what went wrong. */ + "x-ms-error-code"?: string; +} + +export interface ListWorkersDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponse; + headers: RawHttpHeaders & ListWorkersDefaultHeaders; +} diff --git a/sdk/communication/communication-job-router-rest/package.json b/sdk/communication/communication-job-router-rest/package.json index 4fb46a67a980..db3738064b11 100644 --- a/sdk/communication/communication-job-router-rest/package.json +++ b/sdk/communication/communication-job-router-rest/package.json @@ -61,7 +61,6 @@ "@azure-rest/core-client": "^2.3.1", "@azure/communication-common": "^2.3.1", "@azure/core-auth": "^1.9.0", - "@azure/core-paging": "^1.6.2", "@azure/core-rest-pipeline": "^1.18.0", "@azure/logger": "^1.1.4", "tslib": "^2.8.1" diff --git a/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md b/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md index 9b30c2a23469..e7f08b01ff65 100644 --- a/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md +++ b/sdk/communication/communication-job-router-rest/review/communication-job-router.api.md @@ -9,8 +9,6 @@ import type { ClientOptions } from '@azure-rest/core-client'; import type { ErrorResponse } from '@azure-rest/core-client'; import type { HttpResponse } from '@azure-rest/core-client'; import type { KeyCredential } from '@azure/core-auth'; -import type { Paged } from '@azure/core-paging'; -import type { PagedAsyncIterableIterator } from '@azure/core-paging'; import type { PathUncheckedResponse } from '@azure-rest/core-client'; import type { RawHttpHeaders } from '@azure/core-rest-pipeline'; import type { RawHttpHeadersInput } from '@azure/core-rest-pipeline'; @@ -61,6 +59,11 @@ export type AzureCommunicationRoutingServiceClient = Client & { path: Routes; }; +// @public +export interface AzureCommunicationRoutingServiceClientOptions extends ClientOptions { + apiVersion?: string; +} + // @public export interface BestWorkerMode extends DistributionModeParent { kind: "bestWorker"; @@ -487,6 +490,12 @@ export interface DirectMapRouterRuleOutput extends RouterRuleOutputParent { // @public export type DistributionMode = DistributionModeParent | BestWorkerMode | LongestIdleMode | RoundRobinMode; +// @public +export type DistributionModeKind = string; + +// @public +export type DistributionModeKindOutput = string; + // @public export type DistributionModeOutput = DistributionModeOutputParent | BestWorkerModeOutput | LongestIdleModeOutput | RoundRobinModeOutput; @@ -494,7 +503,7 @@ export type DistributionModeOutput = DistributionModeOutputParent | BestWorkerMo export interface DistributionModeOutputParent { bypassSelectors?: boolean; // (undocumented) - kind: string; + kind: DistributionModeKindOutput; maxConcurrentOffers?: number; minConcurrentOffers?: number; } @@ -503,7 +512,7 @@ export interface DistributionModeOutputParent { export interface DistributionModeParent { bypassSelectors?: boolean; // (undocumented) - kind: string; + kind: DistributionModeKind; maxConcurrentOffers?: number; minConcurrentOffers?: number; } @@ -530,6 +539,12 @@ export type DistributionPolicyResourceMergeAndPatch = Partial = (pageLink: string, maxPageSize?: number) => Promise<{ +export type GetPage = (pageLink: string) => Promise<{ page: TPage; nextPageLink?: string; }>; @@ -1015,21 +1042,33 @@ export function isUnexpected(response: ListWorkers200Response | ListWorkersDefau // @public export type JobMatchingMode = JobMatchingModeParent | ScheduleAndSuspendMode | QueueAndMatchMode | SuspendMode; +// @public +export type JobMatchingModeKind = string; + +// @public +export type JobMatchingModeKindOutput = string; + // @public export type JobMatchingModeOutput = JobMatchingModeOutputParent | ScheduleAndSuspendModeOutput | QueueAndMatchModeOutput | SuspendModeOutput; // @public export interface JobMatchingModeOutputParent { // (undocumented) - kind: string; + kind: JobMatchingModeKindOutput; } // @public export interface JobMatchingModeParent { // (undocumented) - kind: string; + kind: JobMatchingModeKind; } +// @public +export type LabelOperator = string; + +// @public +export type LabelOperatorOutput = string; + // @public (undocumented) export interface ListClassificationPolicies { get(options?: ListClassificationPoliciesParameters): StreamableMethod; @@ -1201,7 +1240,7 @@ export interface ListJobsQueryParamProperties { queueId?: string; scheduledAfter?: Date | string; scheduledBefore?: Date | string; - status?: string; + status?: RouterJobStatusSelector; } // @public (undocumented) @@ -1289,7 +1328,7 @@ export interface ListWorkersQueryParamProperties { hasCapacity?: boolean; maxpagesize?: number; queueId?: string; - state?: string; + state?: RouterWorkerStateSelector; } // @public @@ -1331,22 +1370,52 @@ export interface OAuth2WebhookClientCredentialOutput { } // @public -export type PagedClassificationPolicyOutput = Paged; +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + +// @public +export interface PagedClassificationPolicyOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedDistributionPolicyOutput = Paged; +export interface PagedDistributionPolicyOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedExceptionPolicyOutput = Paged; +export interface PagedExceptionPolicyOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedRouterJobOutput = Paged; +export interface PagedRouterJobOutput { + nextLink?: string; + value: Array; +} + +// @public +export interface PagedRouterQueueOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedRouterQueueOutput = Paged; +export interface PagedRouterWorkerOutput { + nextLink?: string; + value: Array; +} // @public -export type PagedRouterWorkerOutput = Paged; +export interface PageSettings { + continuationToken?: string; +} // @public export function paginate(client: Client, initialResponse: TResponse, options?: PagingOptions): PagedAsyncIterableIterator>; @@ -1367,14 +1436,14 @@ export interface PagingOptions { export interface PassThroughQueueSelectorAttachment extends QueueSelectorAttachmentParent { key: string; kind: "passThrough"; - labelOperator: string; + labelOperator: LabelOperator; } // @public export interface PassThroughQueueSelectorAttachmentOutput extends QueueSelectorAttachmentOutputParent { key: string; kind: "passThrough"; - labelOperator: string; + labelOperator: LabelOperatorOutput; } // @public @@ -1382,7 +1451,7 @@ export interface PassThroughWorkerSelectorAttachment extends WorkerSelectorAttac expiresAfterSeconds?: number; key: string; kind: "passThrough"; - labelOperator: string; + labelOperator: LabelOperator; } // @public @@ -1390,7 +1459,7 @@ export interface PassThroughWorkerSelectorAttachmentOutput extends WorkerSelecto expiresAfterSeconds?: number; key: string; kind: "passThrough"; - labelOperator: string; + labelOperator: LabelOperatorOutput; } // @public @@ -1418,19 +1487,25 @@ export interface QueueLengthExceptionTriggerOutput extends ExceptionTriggerOutpu // @public export type QueueSelectorAttachment = QueueSelectorAttachmentParent | ConditionalQueueSelectorAttachment | PassThroughQueueSelectorAttachment | RuleEngineQueueSelectorAttachment | StaticQueueSelectorAttachment | WeightedAllocationQueueSelectorAttachment; +// @public +export type QueueSelectorAttachmentKind = string; + +// @public +export type QueueSelectorAttachmentKindOutput = string; + // @public export type QueueSelectorAttachmentOutput = QueueSelectorAttachmentOutputParent | ConditionalQueueSelectorAttachmentOutput | PassThroughQueueSelectorAttachmentOutput | RuleEngineQueueSelectorAttachmentOutput | StaticQueueSelectorAttachmentOutput | WeightedAllocationQueueSelectorAttachmentOutput; // @public export interface QueueSelectorAttachmentOutputParent { // (undocumented) - kind: string; + kind: QueueSelectorAttachmentKindOutput; } // @public export interface QueueSelectorAttachmentParent { // (undocumented) - kind: string; + kind: QueueSelectorAttachmentKind; } // @public @@ -1527,10 +1602,6 @@ export interface RouterChannelOutput { maxNumberOfJobs?: number; } -// @public -export interface RouterConditionalRequestHeadersOutput { -} - // @public export interface RouterJob { channelId?: string; @@ -1610,7 +1681,7 @@ export interface RouterJobOutput { queueId?: string; requestedWorkerSelectors?: Array; readonly scheduledAt?: string; - readonly status?: string; + readonly status?: RouterJobStatusOutput; tags?: Record; } @@ -1626,6 +1697,15 @@ export interface RouterJobPositionDetailsOutput { // @public export type RouterJobResourceMergeAndPatch = Partial; +// @public +export type RouterJobStatus = string; + +// @public +export type RouterJobStatusOutput = string; + +// @public +export type RouterJobStatusSelector = string; + // @public export interface RouterQueue { distributionPolicyId?: string; @@ -1650,14 +1730,14 @@ export type RouterQueueResourceMergeAndPatch = Partial; // @public export interface RouterQueueSelector { key: string; - labelOperator: string; + labelOperator: LabelOperator; value?: unknown; } // @public export interface RouterQueueSelectorOutput { key: string; - labelOperator: string; + labelOperator: LabelOperatorOutput; value?: any; } @@ -1672,19 +1752,25 @@ export interface RouterQueueStatisticsOutput { // @public export type RouterRule = RouterRuleParent | DirectMapRouterRule | ExpressionRouterRule | FunctionRouterRule | StaticRouterRule | WebhookRouterRule; +// @public +export type RouterRuleKind = string; + +// @public +export type RouterRuleKindOutput = string; + // @public export type RouterRuleOutput = RouterRuleOutputParent | DirectMapRouterRuleOutput | ExpressionRouterRuleOutput | FunctionRouterRuleOutput | StaticRouterRuleOutput | WebhookRouterRuleOutput; // @public export interface RouterRuleOutputParent { // (undocumented) - kind: string; + kind: RouterRuleKindOutput; } // @public export interface RouterRuleParent { // (undocumented) - kind: string; + kind: RouterRuleKind; } // @public @@ -1727,7 +1813,7 @@ export interface RouterWorkerOutput { maxConcurrentOffers?: number; readonly offers?: Array; queues?: string[]; - readonly state?: string; + readonly state?: RouterWorkerStateOutput; tags?: Record; } @@ -1739,7 +1825,7 @@ export interface RouterWorkerSelector { expedite?: boolean; expiresAfterSeconds?: number; key: string; - labelOperator: string; + labelOperator: LabelOperator; value?: unknown; } @@ -1749,11 +1835,26 @@ export interface RouterWorkerSelectorOutput { expiresAfterSeconds?: number; readonly expiresAt?: string; key: string; - labelOperator: string; - readonly status?: string; + labelOperator: LabelOperatorOutput; + readonly status?: RouterWorkerSelectorStatusOutput; value?: any; } +// @public +export type RouterWorkerSelectorStatus = string; + +// @public +export type RouterWorkerSelectorStatusOutput = string; + +// @public +export type RouterWorkerState = string; + +// @public +export type RouterWorkerStateOutput = string; + +// @public +export type RouterWorkerStateSelector = string; + // @public (undocumented) export interface Routes { (path: "/routing/classificationPolicies/{classificationPolicyId}", classificationPolicyId: string): UpsertClassificationPolicy; @@ -1820,7 +1921,7 @@ export interface ScoringRuleOptions { batchSize?: number; descendingOrder?: boolean; isBatchScoringEnabled?: boolean; - scoringParameters?: string[]; + scoringParameters?: ScoringRuleParameterSelector[]; } // @public @@ -1828,9 +1929,15 @@ export interface ScoringRuleOptionsOutput { batchSize?: number; descendingOrder?: boolean; isBatchScoringEnabled?: boolean; - scoringParameters?: string[]; + scoringParameters?: ScoringRuleParameterSelectorOutput[]; } +// @public +export type ScoringRuleParameterSelector = string; + +// @public +export type ScoringRuleParameterSelectorOutput = string; + // @public export interface StaticQueueSelectorAttachment extends QueueSelectorAttachmentParent { kind: "static"; @@ -2453,19 +2560,25 @@ export interface WeightedAllocationWorkerSelectorAttachmentOutput extends Worker // @public export type WorkerSelectorAttachment = WorkerSelectorAttachmentParent | ConditionalWorkerSelectorAttachment | PassThroughWorkerSelectorAttachment | RuleEngineWorkerSelectorAttachment | StaticWorkerSelectorAttachment | WeightedAllocationWorkerSelectorAttachment; +// @public +export type WorkerSelectorAttachmentKind = string; + +// @public +export type WorkerSelectorAttachmentKindOutput = string; + // @public export type WorkerSelectorAttachmentOutput = WorkerSelectorAttachmentOutputParent | ConditionalWorkerSelectorAttachmentOutput | PassThroughWorkerSelectorAttachmentOutput | RuleEngineWorkerSelectorAttachmentOutput | StaticWorkerSelectorAttachmentOutput | WeightedAllocationWorkerSelectorAttachmentOutput; // @public export interface WorkerSelectorAttachmentOutputParent { // (undocumented) - kind: string; + kind: WorkerSelectorAttachmentKindOutput; } // @public export interface WorkerSelectorAttachmentParent { // (undocumented) - kind: string; + kind: WorkerSelectorAttachmentKind; } // @public diff --git a/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts index 3cd6a13c6624..f61c98ecd0b1 100644 --- a/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts +++ b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceClient.ts @@ -3,67 +3,32 @@ import type { ClientOptions } from "@azure-rest/core-client"; import { getClient } from "@azure-rest/core-client"; -import type { KeyCredential, TokenCredential } from "@azure/core-auth"; -import { isTokenCredential } from "@azure/core-auth"; import { logger } from "./logger.js"; import type { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; -import { - createCommunicationAuthPolicy, - isKeyCredential, - parseClientArguments, -} from "@azure/communication-common"; -/** - * Initialize a new instance of `AzureCommunicationRoutingServiceClient` - * @param connectionString - The connectionString or url of your Communication Services resource. - * @param options - the parameter for all optional parameters - */ -export default function createClient( - connectionString: string, - options: ClientOptions, -): AzureCommunicationRoutingServiceClient; +/** The optional parameters for the client */ +export interface AzureCommunicationRoutingServiceClientOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} /** * Initialize a new instance of `AzureCommunicationRoutingServiceClient` - * @param endpoint - Uri of your Communication resource - * @param credentialOrOptions - The key or token credential. + * @param endpointParam - Uri of your Communication resource * @param options - the parameter for all optional parameters */ export default function createClient( - endpoint: string, - credentialOrOptions?: KeyCredential | TokenCredential, - options?: ClientOptions, -): AzureCommunicationRoutingServiceClient; - -// Implementation -export default function createClient( - arg1: string, - arg2?: ClientOptions | (KeyCredential | TokenCredential), - arg3?: ClientOptions, + endpointParam: string, + { + apiVersion = "2024-01-18-preview", + ...options + }: AzureCommunicationRoutingServiceClientOptions = {}, ): AzureCommunicationRoutingServiceClient { - let credentialOrOptions: KeyCredential | TokenCredential | undefined; - let options: ClientOptions | undefined; - const connectionStringOrUrl = arg1; - - // Determine which constructor is being called based on the types of the arguments - if (isTokenCredential(arg2) || isKeyCredential(arg2)) { - credentialOrOptions = arg2 as KeyCredential | TokenCredential; - options = arg3 as ClientOptions; - } else { - options = arg2 as ClientOptions; - } - if (options === undefined) { - options = {}; - } - - // Rest of the function remains the same, using connectionStringOrUrl or endpoint as needed - const { url, credential } = parseClientArguments(connectionStringOrUrl, credentialOrOptions); - const baseUrl = options?.baseUrl ?? `${url}`; - options.apiVersion = options.apiVersion ?? "2024-01-18-preview"; - const userAgentInfo = `azsdk-js-communication-job-router-rest/1.1.0-beta.2`; + const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const userAgentInfo = `azsdk-js-communication-job-router-rest/1.0.0-beta.1`; const userAgentPrefix = - options?.userAgentOptions && options?.userAgentOptions.userAgentPrefix - ? `${options?.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` : `${userAgentInfo}`; options = { ...options, @@ -71,14 +36,26 @@ export default function createClient( userAgentPrefix, }, loggingOptions: { - logger: options?.loggingOptions?.logger ?? logger.info, + logger: options.loggingOptions?.logger ?? logger.info, }, }; - - const client = getClient(baseUrl, options) as AzureCommunicationRoutingServiceClient; - - const authPolicy = createCommunicationAuthPolicy(credential); - client.pipeline.addPolicy(authPolicy); + const client = getClient(endpointUrl, options) as AzureCommunicationRoutingServiceClient; + + 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/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts new file mode 100644 index 000000000000..c0c9bec08aa0 --- /dev/null +++ b/sdk/communication/communication-job-router-rest/src/azureCommunicationRoutingServiceCustmizedClient.ts @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import type { ClientOptions } from "@azure-rest/core-client"; +import type { KeyCredential, TokenCredential } from "@azure/core-auth"; +import { isTokenCredential } from "@azure/core-auth"; +import type { AzureCommunicationRoutingServiceClient } from "./clientDefinitions.js"; +import { + createCommunicationAuthPolicy, + isKeyCredential, + parseClientArguments, +} from "@azure/communication-common"; +import createGeneratedClient from "./azureCommunicationRoutingServiceClient.js"; + +/** + * Initialize a new instance of `AzureCommunicationRoutingServiceClient` + * @param connectionString - The connectionString or url of your Communication Services resource. + * @param options - the parameter for all optional parameters + */ +export default function createClient( + connectionString: string, + options: ClientOptions, +): AzureCommunicationRoutingServiceClient; + +/** + * Initialize a new instance of `AzureCommunicationRoutingServiceClient` + * @param endpoint - Uri of your Communication resource + * @param credentialOrOptions - The key or token credential. + * @param options - the parameter for all optional parameters + */ +export default function createClient( + endpoint: string, + credentialOrOptions?: KeyCredential | TokenCredential, + options?: ClientOptions, +): AzureCommunicationRoutingServiceClient; + +// Implementation +export default function createClient( + arg1: string, + arg2?: ClientOptions | (KeyCredential | TokenCredential), + arg3?: ClientOptions, +): AzureCommunicationRoutingServiceClient { + let credentialOrOptions: KeyCredential | TokenCredential | undefined; + let options: ClientOptions | undefined; + const connectionStringOrUrl = arg1; + + // Determine which constructor is being called based on the types of the arguments + if (isTokenCredential(arg2) || isKeyCredential(arg2)) { + credentialOrOptions = arg2 as KeyCredential | TokenCredential; + options = arg3 as ClientOptions; + } else { + options = arg2 as ClientOptions; + } + if (options === undefined) { + options = {}; + } + + // Rest of the function remains the same, using connectionStringOrUrl or endpoint as needed + const { url, credential } = parseClientArguments(connectionStringOrUrl, credentialOrOptions); + const client = createGeneratedClient(url, options); + const authPolicy = createCommunicationAuthPolicy(credential); + client.pipeline.addPolicy(authPolicy); + + return client; +} diff --git a/sdk/communication/communication-job-router-rest/src/index.ts b/sdk/communication/communication-job-router-rest/src/index.ts index 1c1e0181dcda..92afbd477873 100644 --- a/sdk/communication/communication-job-router-rest/src/index.ts +++ b/sdk/communication/communication-job-router-rest/src/index.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceClient.js"; +import AzureCommunicationRoutingServiceClient from "./azureCommunicationRoutingServiceCustmizedClient.js"; export * from "./azureCommunicationRoutingServiceClient.js"; export * from "./parameters.js"; diff --git a/sdk/communication/communication-job-router-rest/src/isUnexpected.ts b/sdk/communication/communication-job-router-rest/src/isUnexpected.ts index 2a4c05d342b5..3799fd2f884e 100644 --- a/sdk/communication/communication-job-router-rest/src/isUnexpected.ts +++ b/sdk/communication/communication-job-router-rest/src/isUnexpected.ts @@ -395,7 +395,6 @@ function getParametrizedPathSuccess(method: string, path: string): string[] { matchedValue = value; } } - return matchedValue; } diff --git a/sdk/communication/communication-job-router-rest/src/models.ts b/sdk/communication/communication-job-router-rest/src/models.ts index b84576d57d2f..4500187dfa5e 100644 --- a/sdk/communication/communication-job-router-rest/src/models.ts +++ b/sdk/communication/communication-job-router-rest/src/models.ts @@ -17,7 +17,7 @@ export interface ClassificationPolicy { /** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ export interface QueueSelectorAttachmentParent { - kind: string; + kind: QueueSelectorAttachmentKind; } /** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ @@ -39,7 +39,7 @@ export interface ConditionalQueueSelectorAttachment extends QueueSelectorAttachm * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. */ export interface RouterRuleParent { - kind: string; + kind: RouterRuleKind; } /** A rule that return the same labels as the input labels. */ @@ -55,7 +55,7 @@ export interface ExpressionRouterRule extends RouterRuleParent { * * Possible values: "powerFx" */ - language?: string; + language?: ExpressionRouterRuleLanguage; /** An expression to evaluate. Should contain return statement with calculated values. */ expression: string; /** The type discriminator describing a sub-type of Rule. */ @@ -119,7 +119,7 @@ export interface RouterQueueSelector { * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperator; /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ value?: unknown; } @@ -133,7 +133,7 @@ export interface PassThroughQueueSelectorAttachment extends QueueSelectorAttachm * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperator; /** The type discriminator describing the type of queue selector attachment. */ kind: "passThrough"; } @@ -172,7 +172,7 @@ export interface QueueWeightedAllocation { /** An attachment which attaches worker selectors to a job. */ export interface WorkerSelectorAttachmentParent { - kind: string; + kind: WorkerSelectorAttachmentKind; } /** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ @@ -194,7 +194,7 @@ export interface RouterWorkerSelector { * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperator; /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ value?: unknown; /** Describes how long this label selector is valid in seconds. */ @@ -212,7 +212,7 @@ export interface PassThroughWorkerSelectorAttachment extends WorkerSelectorAttac * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperator; /** Describes how long the attached label selector is valid in seconds. */ expiresAfterSeconds?: number; /** The type discriminator describing the type of worker selector attachment. */ @@ -269,7 +269,7 @@ export interface DistributionModeParent { maxConcurrentOffers?: number; /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ bypassSelectors?: boolean; - kind: string; + kind: DistributionModeKind; } /** Jobs are distributed to the worker with the strongest abilities available. */ @@ -287,7 +287,7 @@ export interface ScoringRuleOptions { /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ batchSize?: number; /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ - scoringParameters?: string[]; + scoringParameters?: ScoringRuleParameterSelector[]; /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ isBatchScoringEnabled?: boolean; /** If false, will sort scores by ascending order. By default, set to true. */ @@ -326,7 +326,7 @@ export interface ExceptionRule { /** Abstract base class for defining a trigger for exception rules. */ export interface ExceptionTriggerParent { - kind: string; + kind: ExceptionTriggerKind; } /** Trigger for an exception action on exceeding queue length. */ @@ -349,7 +349,7 @@ export interface WaitTimeExceptionTrigger extends ExceptionTriggerParent { export interface ExceptionActionParent { /** Unique Id of the exception action. */ id?: string; - kind: string; + kind: ExceptionActionKind; } /** An action that marks a job as cancelled. */ @@ -406,7 +406,7 @@ export interface RouterJob { classificationPolicyId?: string; /** Id of a queue that this job is queued to. */ queueId?: string; - /** Priority of this job. */ + /** Priority of this job. Value must be between -100 to 100. */ priority?: number; /** Reason code for cancelled or closed jobs. */ dispositionCode?: string; @@ -449,7 +449,7 @@ export interface RouterJobNote { * SuspendMode: Used when matching workers to a job needs to be suspended. */ export interface JobMatchingModeParent { - kind: string; + kind: JobMatchingModeKind; } /** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ @@ -535,7 +535,7 @@ export interface RouterChannel { channelId: string; /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ capacityCostPerJob: number; - /** The maximum number of jobs that can be supported concurrently for this channel. */ + /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ maxNumberOfJobs?: number; } @@ -622,3 +622,33 @@ export type JobMatchingMode = | ScheduleAndSuspendMode | QueueAndMatchMode | SuspendMode; +/** Alias for QueueSelectorAttachmentKind */ +export type QueueSelectorAttachmentKind = string; +/** Alias for RouterRuleKind */ +export type RouterRuleKind = string; +/** Alias for ExpressionRouterRuleLanguage */ +export type ExpressionRouterRuleLanguage = string; +/** Alias for LabelOperator */ +export type LabelOperator = string; +/** Alias for WorkerSelectorAttachmentKind */ +export type WorkerSelectorAttachmentKind = string; +/** Alias for RouterWorkerSelectorStatus */ +export type RouterWorkerSelectorStatus = string; +/** Alias for DistributionModeKind */ +export type DistributionModeKind = string; +/** Alias for ScoringRuleParameterSelector */ +export type ScoringRuleParameterSelector = string; +/** Alias for ExceptionTriggerKind */ +export type ExceptionTriggerKind = string; +/** Alias for ExceptionActionKind */ +export type ExceptionActionKind = string; +/** Alias for RouterJobStatus */ +export type RouterJobStatus = string; +/** Alias for JobMatchingModeKind */ +export type JobMatchingModeKind = string; +/** Alias for RouterJobStatusSelector */ +export type RouterJobStatusSelector = string; +/** Alias for RouterWorkerState */ +export type RouterWorkerState = string; +/** Alias for RouterWorkerStateSelector */ +export type RouterWorkerStateSelector = string; diff --git a/sdk/communication/communication-job-router-rest/src/outputModels.ts b/sdk/communication/communication-job-router-rest/src/outputModels.ts index 9c1515d7a9c2..1a00c0074612 100644 --- a/sdk/communication/communication-job-router-rest/src/outputModels.ts +++ b/sdk/communication/communication-job-router-rest/src/outputModels.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { Paged } from "@azure/core-paging"; - /** A container for the rules that govern how jobs are classified. */ export interface ClassificationPolicyOutput { /** The entity tag for this resource. */ @@ -23,7 +21,7 @@ export interface ClassificationPolicyOutput { /** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ export interface QueueSelectorAttachmentOutputParent { - kind: string; + kind: QueueSelectorAttachmentKindOutput; } /** Describes a set of queue selectors that will be attached if the given condition resolves to true. */ @@ -46,7 +44,7 @@ export interface ConditionalQueueSelectorAttachmentOutput * WebhookRule: A rule providing a binding to a webserver following OAuth2.0 authentication protocol. */ export interface RouterRuleOutputParent { - kind: string; + kind: RouterRuleKindOutput; } /** A rule that return the same labels as the input labels. */ @@ -62,7 +60,7 @@ export interface ExpressionRouterRuleOutput extends RouterRuleOutputParent { * * Possible values: "powerFx" */ - language?: string; + language?: ExpressionRouterRuleLanguageOutput; /** An expression to evaluate. Should contain return statement with calculated values. */ expression: string; /** The type discriminator describing a sub-type of Rule. */ @@ -126,7 +124,7 @@ export interface RouterQueueSelectorOutput { * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperatorOutput; /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ value?: any; } @@ -141,7 +139,7 @@ export interface PassThroughQueueSelectorAttachmentOutput * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperatorOutput; /** The type discriminator describing the type of queue selector attachment. */ kind: "passThrough"; } @@ -182,7 +180,7 @@ export interface QueueWeightedAllocationOutput { /** An attachment which attaches worker selectors to a job. */ export interface WorkerSelectorAttachmentOutputParent { - kind: string; + kind: WorkerSelectorAttachmentKindOutput; } /** Describes a set of worker selectors that will be attached if the given condition resolves to true. */ @@ -205,7 +203,7 @@ export interface RouterWorkerSelectorOutput { * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperatorOutput; /** The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean. */ value?: any; /** Describes how long this label selector is valid in seconds. */ @@ -217,7 +215,7 @@ export interface RouterWorkerSelectorOutput { * * Possible values: "active", "expired" */ - readonly status?: string; + readonly status?: RouterWorkerSelectorStatusOutput; /** The time at which this worker selector expires in UTC. */ readonly expiresAt?: string; } @@ -232,7 +230,7 @@ export interface PassThroughWorkerSelectorAttachmentOutput * * Possible values: "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" */ - labelOperator: string; + labelOperator: LabelOperatorOutput; /** Describes how long the attached label selector is valid in seconds. */ expiresAfterSeconds?: number; /** The type discriminator describing the type of worker selector attachment. */ @@ -273,8 +271,13 @@ export interface WorkerWeightedAllocationOutput { workerSelectors: Array; } -/** Provides the 'If-*' headers to enable conditional (cached) responses for JobRouter. */ -export interface RouterConditionalRequestHeadersOutput {} +/** Paged collection of ClassificationPolicy items */ +export interface PagedClassificationPolicyOutput { + /** The ClassificationPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} /** Policy governing how jobs are distributed to workers */ export interface DistributionPolicyOutput { @@ -298,7 +301,7 @@ export interface DistributionModeOutputParent { maxConcurrentOffers?: number; /** If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false. */ bypassSelectors?: boolean; - kind: string; + kind: DistributionModeKindOutput; } /** Jobs are distributed to the worker with the strongest abilities available. */ @@ -316,7 +319,7 @@ export interface ScoringRuleOptionsOutput { /** Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. */ batchSize?: number; /** List of extra parameters from a job that will be sent as part of the payload to scoring rule. If not set, a job's labels (sent in the payload as `job`) and a job's worker selectors (sent in the payload as `selectors`) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. */ - scoringParameters?: string[]; + scoringParameters?: ScoringRuleParameterSelectorOutput[]; /** If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as `workers`. By default, set to false and the parameter name for the worker labels will be sent as `worker`. Note: If enabled, use 'batchSize' to set batch size. */ isBatchScoringEnabled?: boolean; /** If false, will sort scores by ascending order. By default, set to true. */ @@ -335,6 +338,14 @@ export interface RoundRobinModeOutput extends DistributionModeOutputParent { kind: "roundRobin"; } +/** Paged collection of DistributionPolicy items */ +export interface PagedDistributionPolicyOutput { + /** The DistributionPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** A policy that defines actions to execute when exception are triggered. */ export interface ExceptionPolicyOutput { /** The entity tag for this resource. */ @@ -359,7 +370,7 @@ export interface ExceptionRuleOutput { /** Abstract base class for defining a trigger for exception rules. */ export interface ExceptionTriggerOutputParent { - kind: string; + kind: ExceptionTriggerKindOutput; } /** Trigger for an exception action on exceeding queue length. */ @@ -382,7 +393,7 @@ export interface WaitTimeExceptionTriggerOutput extends ExceptionTriggerOutputPa export interface ExceptionActionOutputParent { /** Unique Id of the exception action. */ id?: string; - kind: string; + kind: ExceptionActionKindOutput; } /** An action that marks a job as cancelled. */ @@ -417,6 +428,14 @@ export interface ReclassifyExceptionActionOutput extends ExceptionActionOutputPa kind: "reclassify"; } +/** Paged collection of ExceptionPolicy items */ +export interface PagedExceptionPolicyOutput { + /** The ExceptionPolicy items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** A queue that can contain jobs to be routed. */ export interface RouterQueueOutput { /** The entity tag for this resource. */ @@ -433,6 +452,14 @@ export interface RouterQueueOutput { exceptionPolicyId?: string; } +/** Paged collection of RouterQueue items */ +export interface PagedRouterQueueOutput { + /** The RouterQueue items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** A unit of work to be routed */ export interface RouterJobOutput { /** The entity tag for this resource. */ @@ -446,7 +473,7 @@ export interface RouterJobOutput { * * Possible values: "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation" */ - readonly status?: string; + readonly status?: RouterJobStatusOutput; /** Timestamp a job was queued in UTC. */ readonly enqueuedAt?: string; /** The channel identifier. eg. voice, chat, etc. */ @@ -455,7 +482,7 @@ export interface RouterJobOutput { classificationPolicyId?: string; /** Id of a queue that this job is queued to. */ queueId?: string; - /** Priority of this job. */ + /** Priority of this job. Value must be between -100 to 100. */ priority?: number; /** Reason code for cancelled or closed jobs. */ dispositionCode?: string; @@ -506,7 +533,7 @@ export interface RouterJobNoteOutput { * SuspendMode: Used when matching workers to a job needs to be suspended. */ export interface JobMatchingModeOutputParent { - kind: string; + kind: JobMatchingModeKindOutput; } /** Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. */ @@ -541,6 +568,14 @@ export interface CompleteJobResultOutput {} /** Response payload from closing a job. */ export interface CloseJobResultOutput {} +/** Paged collection of RouterJob items */ +export interface PagedRouterJobOutput { + /** The RouterJob items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** Position and estimated wait time for a job. */ export interface RouterJobPositionDetailsOutput { /** Id of the job these details are about. */ @@ -599,7 +634,7 @@ export interface RouterWorkerOutput { * * Possible values: "active", "draining", "inactive" */ - readonly state?: string; + readonly state?: RouterWorkerStateOutput; /** Collection of queue(s) that this worker can receive work from. */ queues?: string[]; /** The total capacity score this worker has to manage multiple concurrent jobs. */ @@ -628,7 +663,7 @@ export interface RouterChannelOutput { channelId: string; /** The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. */ capacityCostPerJob: number; - /** The maximum number of jobs that can be supported concurrently for this channel. */ + /** The maximum number of jobs that can be supported concurrently for this channel. Value must be greater than zero. */ maxNumberOfJobs?: number; } @@ -658,6 +693,14 @@ export interface RouterWorkerAssignmentOutput { assignedAt: string; } +/** Paged collection of RouterWorker items */ +export interface PagedRouterWorkerOutput { + /** The RouterWorker items on this page */ + value: Array; + /** The link to the next page of items */ + nextLink?: string; +} + /** An attachment of queue selectors to resolve a queue to a job from a classification policy. */ export type QueueSelectorAttachmentOutput = | QueueSelectorAttachmentOutputParent @@ -717,15 +760,29 @@ export type JobMatchingModeOutput = | ScheduleAndSuspendModeOutput | QueueAndMatchModeOutput | SuspendModeOutput; -/** Paged collection of ClassificationPolicy items */ -export type PagedClassificationPolicyOutput = Paged; -/** Paged collection of DistributionPolicy items */ -export type PagedDistributionPolicyOutput = Paged; -/** Paged collection of ExceptionPolicy items */ -export type PagedExceptionPolicyOutput = Paged; -/** Paged collection of RouterQueue items */ -export type PagedRouterQueueOutput = Paged; -/** Paged collection of RouterJob items */ -export type PagedRouterJobOutput = Paged; -/** Paged collection of RouterWorker items */ -export type PagedRouterWorkerOutput = Paged; +/** Alias for QueueSelectorAttachmentKindOutput */ +export type QueueSelectorAttachmentKindOutput = string; +/** Alias for RouterRuleKindOutput */ +export type RouterRuleKindOutput = string; +/** Alias for ExpressionRouterRuleLanguageOutput */ +export type ExpressionRouterRuleLanguageOutput = string; +/** Alias for LabelOperatorOutput */ +export type LabelOperatorOutput = string; +/** Alias for WorkerSelectorAttachmentKindOutput */ +export type WorkerSelectorAttachmentKindOutput = string; +/** Alias for RouterWorkerSelectorStatusOutput */ +export type RouterWorkerSelectorStatusOutput = string; +/** Alias for DistributionModeKindOutput */ +export type DistributionModeKindOutput = string; +/** Alias for ScoringRuleParameterSelectorOutput */ +export type ScoringRuleParameterSelectorOutput = string; +/** Alias for ExceptionTriggerKindOutput */ +export type ExceptionTriggerKindOutput = string; +/** Alias for ExceptionActionKindOutput */ +export type ExceptionActionKindOutput = string; +/** Alias for RouterJobStatusOutput */ +export type RouterJobStatusOutput = string; +/** Alias for JobMatchingModeKindOutput */ +export type JobMatchingModeKindOutput = string; +/** Alias for RouterWorkerStateOutput */ +export type RouterWorkerStateOutput = string; diff --git a/sdk/communication/communication-job-router-rest/src/paginateHelper.ts b/sdk/communication/communication-job-router-rest/src/paginateHelper.ts index 5d541b4e406d..9ea946d9d6c5 100644 --- a/sdk/communication/communication-job-router-rest/src/paginateHelper.ts +++ b/sdk/communication/communication-job-router-rest/src/paginateHelper.ts @@ -1,11 +1,148 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import type { PagedAsyncIterableIterator, PagedResult } from "@azure/core-paging"; -import { getPagedAsyncIterator } from "@azure/core-paging"; import type { Client, PathUncheckedResponse } from "@azure-rest/core-client"; import { createRestError } from "@azure-rest/core-client"; +/** + * 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 = PageSettings, + TLink = string, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + (((settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken as unknown as TLink | undefined, + }); + }) as unknown as (settings?: TPageSettings) => AsyncIterableIterator), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: TLink; + } = {}, +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage(pageLink ?? pagedResult.firstPageLink); + if (!response) { + return; + } + yield response.page; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield response.page; + } +} + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * 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 = 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; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings?: TPageSettings) => AsyncIterableIterator; +} + +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult { + /** + * Link to the first page of results. + */ + firstPageLink: TLink; + /** + * A method that returns a page of results. + */ + getPage: (pageLink: TLink) => Promise<{ page: TPage; nextPageLink?: TLink } | 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) => unknown[]; +} + /** * Helper type to extract the type of an array */ @@ -14,10 +151,7 @@ export type GetArrayType = T extends Array ? TData : never; /** * The type of a custom function that defines how to get a page and a link to the next one if any. */ -export type GetPage = ( - pageLink: string, - maxPageSize?: number, -) => Promise<{ +export type GetPage = (pageLink: string) => Promise<{ page: TPage; nextPageLink?: string; }>; diff --git a/sdk/communication/communication-job-router-rest/src/parameters.ts b/sdk/communication/communication-job-router-rest/src/parameters.ts index e55abc76993d..9f7e28f60770 100644 --- a/sdk/communication/communication-job-router-rest/src/parameters.ts +++ b/sdk/communication/communication-job-router-rest/src/parameters.ts @@ -13,9 +13,11 @@ import type { CancelJobOptions, CompleteJobOptions, CloseJobOptions, + RouterJobStatusSelector, UnassignJobOptions, DeclineJobOfferOptions, RouterWorker, + RouterWorkerStateSelector, } from "./models.js"; export interface UpsertClassificationPolicyHeaders { @@ -255,7 +257,7 @@ export interface ListJobsQueryParamProperties { * * Possible values: "all", "pendingClassification", "queued", "assigned", "completed", "closed", "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", "scheduleFailed", "waitingForActivation", "active" */ - status?: string; + status?: RouterJobStatusSelector; /** If specified, filter jobs by queue. */ queueId?: string; /** If specified, filter jobs by channel. */ @@ -330,7 +332,7 @@ export interface ListWorkersQueryParamProperties { * * Possible values: "active", "draining", "inactive", "all" */ - state?: string; + state?: RouterWorkerStateSelector; /** If specified, select workers who have a channel configuration with this channel. */ channelId?: string; /** If specified, select workers who are assigned to this queue. */ diff --git a/sdk/communication/communication-job-router-rest/tsp-location.yaml b/sdk/communication/communication-job-router-rest/tsp-location.yaml index c741f834a73d..392b6654ee71 100644 --- a/sdk/communication/communication-job-router-rest/tsp-location.yaml +++ b/sdk/communication/communication-job-router-rest/tsp-location.yaml @@ -1,7 +1,4 @@ -repo: - Azure/azure-rest-api-specs -additionalDirectories: [] -directory: - specification/communication/Communication.JobRouter -commit: - 1c04f51cbfa195fe177239cf63d00d3539006800 +directory: specification/communication/Communication.JobRouter +commit: d85dc63616d14d9790b224d46aad024e3461955b +repo: ../azure-rest-api-specs +additionalDirectories: