From ec5f22fa8a6e9d3ac7260699b9e5979439b4f014 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Wed, 18 Dec 2024 10:49:47 +0000 Subject: [PATCH] CodeGen from PR 31921 in Azure/azure-rest-api-specs Merge b10bb3a26d6df59188c0779c25c8bbbc8ca6bb76 into 416353cabfea1fc7a1c7c46ba3340408a2618de1 --- sdk/qumulo/arm-qumulo/LICENSE | 21 + sdk/qumulo/arm-qumulo/README.md | 102 +++ sdk/qumulo/arm-qumulo/api-extractor.json | 18 + sdk/qumulo/arm-qumulo/eslint.config.mjs | 17 + sdk/qumulo/arm-qumulo/package.json | 91 +++ sdk/qumulo/arm-qumulo/sample.env | 1 + .../arm-qumulo/src/api/fileSystems/index.ts | 340 ++++++++++ sdk/qumulo/arm-qumulo/src/api/index.ts | 26 + .../arm-qumulo/src/api/operations/index.ts | 56 ++ sdk/qumulo/arm-qumulo/src/api/options.ts | 34 + .../arm-qumulo/src/api/storageContext.ts | 56 ++ .../src/classic/fileSystems/index.ts | 147 ++++ sdk/qumulo/arm-qumulo/src/classic/index.ts | 5 + .../src/classic/operations/index.ts | 31 + .../src/helpers/serializerHelpers.ts | 40 ++ sdk/qumulo/arm-qumulo/src/index.ts | 54 ++ sdk/qumulo/arm-qumulo/src/logger.ts | 5 + sdk/qumulo/arm-qumulo/src/models/index.ts | 31 + sdk/qumulo/arm-qumulo/src/models/models.ts | 627 ++++++++++++++++++ .../arm-qumulo/src/restorePollerHelpers.ts | 174 +++++ .../src/static-helpers/pagingHelpers.ts | 274 ++++++++ .../src/static-helpers/pollingHelpers.ts | 137 ++++ sdk/qumulo/arm-qumulo/src/storageClient.ts | 49 ++ .../arm-qumulo/test/public/sampleTest.spec.ts | 21 + .../test/public/utils/recordedClient.ts | 29 + .../arm-qumulo/tsconfig.browser.config.json | 10 + sdk/qumulo/arm-qumulo/tsconfig.json | 16 + sdk/qumulo/arm-qumulo/tsp-location.yaml | 4 + .../arm-qumulo/vitest.browser.config.ts | 38 ++ sdk/qumulo/arm-qumulo/vitest.config.ts | 34 + 30 files changed, 2488 insertions(+) create mode 100644 sdk/qumulo/arm-qumulo/LICENSE create mode 100644 sdk/qumulo/arm-qumulo/README.md create mode 100644 sdk/qumulo/arm-qumulo/api-extractor.json create mode 100644 sdk/qumulo/arm-qumulo/eslint.config.mjs create mode 100644 sdk/qumulo/arm-qumulo/package.json create mode 100644 sdk/qumulo/arm-qumulo/sample.env create mode 100644 sdk/qumulo/arm-qumulo/src/api/fileSystems/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/api/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/api/operations/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/api/options.ts create mode 100644 sdk/qumulo/arm-qumulo/src/api/storageContext.ts create mode 100644 sdk/qumulo/arm-qumulo/src/classic/fileSystems/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/classic/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/classic/operations/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/helpers/serializerHelpers.ts create mode 100644 sdk/qumulo/arm-qumulo/src/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/logger.ts create mode 100644 sdk/qumulo/arm-qumulo/src/models/index.ts create mode 100644 sdk/qumulo/arm-qumulo/src/models/models.ts create mode 100644 sdk/qumulo/arm-qumulo/src/restorePollerHelpers.ts create mode 100644 sdk/qumulo/arm-qumulo/src/static-helpers/pagingHelpers.ts create mode 100644 sdk/qumulo/arm-qumulo/src/static-helpers/pollingHelpers.ts create mode 100644 sdk/qumulo/arm-qumulo/src/storageClient.ts create mode 100644 sdk/qumulo/arm-qumulo/test/public/sampleTest.spec.ts create mode 100644 sdk/qumulo/arm-qumulo/test/public/utils/recordedClient.ts create mode 100644 sdk/qumulo/arm-qumulo/tsconfig.browser.config.json create mode 100644 sdk/qumulo/arm-qumulo/tsconfig.json create mode 100644 sdk/qumulo/arm-qumulo/tsp-location.yaml create mode 100644 sdk/qumulo/arm-qumulo/vitest.browser.config.ts create mode 100644 sdk/qumulo/arm-qumulo/vitest.config.ts diff --git a/sdk/qumulo/arm-qumulo/LICENSE b/sdk/qumulo/arm-qumulo/LICENSE new file mode 100644 index 000000000000..7d5934740965 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/qumulo/arm-qumulo/README.md b/sdk/qumulo/arm-qumulo/README.md new file mode 100644 index 000000000000..cd504a2e9599 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/README.md @@ -0,0 +1,102 @@ +# Azure Storage client library for JavaScript + +This package contains an isomorphic SDK (runs both in Node.js and in browsers) for Azure Storage client. + + + +Key links: + +- [Source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/qumulo/arm-qumulo) +- [Package (NPM)](https://www.npmjs.com/package/@azure/arm-qumulo) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-qumulo?view=azure-node-preview) + +## Getting started + +### Currently supported environments + +- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) +- Latest versions of Safari, Chrome, Edge and Firefox. + +See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. + +### Prerequisites + +- An [Azure subscription][azure_sub]. + +### Install the `@azure/arm-qumulo` package + +Install the Azure Storage client library for JavaScript with `npm`: + +```bash +npm install @azure/arm-qumulo +``` + +### Create and authenticate a `StorageClient` + +To create a client object to access the Azure Storage API, you will need the `endpoint` of your Azure Storage resource and a `credential`. The Azure Storage client can use Azure Active Directory credentials to authenticate. +You can find the endpoint for your Azure Storage resource in the [Azure Portal][azure_portal]. + +You can authenticate with Azure Active Directory using a credential from the [@azure/identity][azure_identity] library or [an existing AAD Token](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token). + +To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the `@azure/identity` package: + +```bash +npm install @azure/identity +``` + +You will also need to **register a new AAD application and grant access to Azure Storage** by assigning the suitable role to your service principal (note: roles such as `"Owner"` will not grant the necessary permissions). + +For more information about how to create an Azure AD Application check out [this guide](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal). + +```javascript +const { StorageClient } = require("@azure/arm-qumulo"); +const { DefaultAzureCredential } = require("@azure/identity"); +// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential. See https://aka.ms/azsdk/js/identity/examples for more details. + +const subscriptionId = "00000000-0000-0000-0000-000000000000"; +const client = new StorageClient(new DefaultAzureCredential(), subscriptionId); + +// For client-side applications running in the browser, use this code instead: +// const credential = new InteractiveBrowserCredential({ +// tenantId: "", +// clientId: "" +// }); +// const client = new StorageClient(credential, subscriptionId); +``` + + +### JavaScript Bundle +To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling). + +## Key concepts + +### StorageClient + +`StorageClient` is the primary interface for developers using the Azure Storage client library. Explore the methods on this client object to understand the different features of the Azure Storage service that you can access. + +## Troubleshooting + +### Logging + +Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: + +```javascript +const { setLogLevel } = require("@azure/logger"); +setLogLevel("info"); +``` + +For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). + + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +## Related projects + +- [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js) + +[azure_sub]: https://azure.microsoft.com/free/ +[azure_portal]: https://portal.azure.com +[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity +[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential diff --git a/sdk/qumulo/arm-qumulo/api-extractor.json b/sdk/qumulo/arm-qumulo/api-extractor.json new file mode 100644 index 000000000000..3e73a52d4202 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/api-extractor.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "./dist/esm/index.d.ts", + "docModel": { "enabled": true }, + "apiReport": { "enabled": true, "reportFolder": "./review" }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/arm-qumulo.d.ts" + }, + "messages": { + "tsdocMessageReporting": { "default": { "logLevel": "none" } }, + "extractorMessageReporting": { + "ae-missing-release-tag": { "logLevel": "none" }, + "ae-unresolved-link": { "logLevel": "none" } + } + } +} diff --git a/sdk/qumulo/arm-qumulo/eslint.config.mjs b/sdk/qumulo/arm-qumulo/eslint.config.mjs new file mode 100644 index 000000000000..113bdc3eaf5f --- /dev/null +++ b/sdk/qumulo/arm-qumulo/eslint.config.mjs @@ -0,0 +1,17 @@ +import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; + +export default [ + ...azsdkEslint.configs.recommended, + { + rules: { + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "@azure/azure-sdk/ts-package-json-module": "off", + "@azure/azure-sdk/ts-package-json-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off", + "tsdoc/syntax": "warn" + } + } +]; diff --git a/sdk/qumulo/arm-qumulo/package.json b/sdk/qumulo/arm-qumulo/package.json new file mode 100644 index 000000000000..8d9c79cccf15 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/package.json @@ -0,0 +1,91 @@ +{ + "name": "@azure/arm-qumulo", + "version": "1.0.0-beta.1", + "description": "A generated SDK for StorageClient.", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, + "autoPublish": false, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./models": "./src/models/index.ts" + }, + "dialects": ["esm", "commonjs"], + "esmDialects": ["browser", "react-native"], + "selfLink": false + }, + "type": "module", + "keywords": ["node", "azure", "cloud", "typescript", "browser", "isomorphic"], + "author": "Microsoft Corporation", + "license": "MIT", + "files": ["dist", "README.md", "LICENSE", "review/*", "CHANGELOG.md"], + "sdk-type": "mgmt", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/qumulo/arm-qumulo/README.md", + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "//metadata": { + "constantPaths": [ + { + "path": "src/api/storageContext.ts", + "prefix": "userAgentInfo" + } + ] + }, + "dependencies": { + "@azure/core-util": "^1.9.2", + "@azure-rest/core-client": "^2.3.1", + "@azure/core-auth": "^1.6.0", + "@azure/core-rest-pipeline": "^1.5.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.6.2", + "@azure/core-lro": "^3.1.0", + "@azure/abort-controller": "^2.1.2" + }, + "devDependencies": { + "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", + "@types/node": "^18.0.0", + "eslint": "^9.9.0", + "typescript": "~5.6.2", + "@azure/identity": "^4.2.1", + "@vitest/browser": "^2.0.5", + "@vitest/coverage-istanbul": "^2.0.5", + "playwright": "^1.41.2", + "vitest": "^2.0.5", + "@azure-tools/test-credential": "^2.0.0", + "@azure-tools/test-recorder": "^4.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0" + }, + "scripts": { + "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "extract-api": "dev-tool run vendored rimraf review && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "pack": "npm pack 2>&1", + "lint": "eslint package.json api-extractor.json src test", + "lint:fix": "eslint package.json api-extractor.json src test --fix --fix-type [problem,suggestion]", + "unit-test": "npm run unit-test:node && npm run unit-test:browser", + "unit-test:browser": "npm run build:test && dev-tool run test:vitest --browser", + "unit-test:node": "dev-tool run test:vitest", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "build:samples": "echo skipped", + "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "execute:samples": "echo skipped", + "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" ", + "generate:client": "echo skipped", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", + "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", + "build": "npm run clean && dev-tool run build-package && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && dev-tool run build-package && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "update-snippets": "echo skipped" + } +} diff --git a/sdk/qumulo/arm-qumulo/sample.env b/sdk/qumulo/arm-qumulo/sample.env new file mode 100644 index 000000000000..508439fc7d62 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/sample.env @@ -0,0 +1 @@ +# Feel free to add your own environment variables. \ No newline at end of file diff --git a/sdk/qumulo/arm-qumulo/src/api/fileSystems/index.ts b/sdk/qumulo/arm-qumulo/src/api/fileSystems/index.ts new file mode 100644 index 000000000000..920130b8aa06 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/api/fileSystems/index.ts @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + StorageContext as Client, + FileSystemsCreateOrUpdateOptionalParams, + FileSystemsDeleteOptionalParams, + FileSystemsGetOptionalParams, + FileSystemsListByResourceGroupOptionalParams, + FileSystemsListBySubscriptionOptionalParams, + FileSystemsUpdateOptionalParams, +} from "../index.js"; +import { + FileSystemResource, + fileSystemResourceSerializer, + fileSystemResourceDeserializer, + FileSystemResourceUpdate, + fileSystemResourceUpdateSerializer, + _FileSystemResourceListResult, + _fileSystemResourceListResultDeserializer, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { getLongRunningPoller } from "../../static-helpers/pollingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PollerLike, OperationState } from "@azure/core-lro"; + +export function _fileSystemsGetSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + options: FileSystemsGetOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", + subscriptionId, + resourceGroupName, + fileSystemName, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _fileSystemsGetDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fileSystemResourceDeserializer(result.body); +} + +/** Get a FileSystemResource */ +export async function fileSystemsGet( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + options: FileSystemsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _fileSystemsGetSend( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + options, + ); + return _fileSystemsGetDeserialize(result); +} + +export function _fileSystemsCreateOrUpdateSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + resource: FileSystemResource, + options: FileSystemsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", + subscriptionId, + resourceGroupName, + fileSystemName, + ) + .put({ + ...operationOptionsToRequestParameters(options), + body: fileSystemResourceSerializer(resource), + }); +} + +export async function _fileSystemsCreateOrUpdateDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200", "201"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fileSystemResourceDeserializer(result.body); +} + +/** Create a FileSystemResource */ +export function fileSystemsCreateOrUpdate( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + resource: FileSystemResource, + options: FileSystemsCreateOrUpdateOptionalParams = { requestOptions: {} }, +): PollerLike, FileSystemResource> { + return getLongRunningPoller( + context, + _fileSystemsCreateOrUpdateDeserialize, + ["200", "201"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _fileSystemsCreateOrUpdateSend( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + resource, + options, + ), + resourceLocationConfig: "azure-async-operation", + }, + ) as PollerLike, FileSystemResource>; +} + +export function _fileSystemsUpdateSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + properties: FileSystemResourceUpdate, + options: FileSystemsUpdateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", + subscriptionId, + resourceGroupName, + fileSystemName, + ) + .patch({ + ...operationOptionsToRequestParameters(options), + body: fileSystemResourceUpdateSerializer(properties), + }); +} + +export async function _fileSystemsUpdateDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fileSystemResourceDeserializer(result.body); +} + +/** Update a FileSystemResource */ +export async function fileSystemsUpdate( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + properties: FileSystemResourceUpdate, + options: FileSystemsUpdateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _fileSystemsUpdateSend( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + properties, + options, + ); + return _fileSystemsUpdateDeserialize(result); +} + +export function _fileSystemsDeleteSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + options: FileSystemsDeleteOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", + subscriptionId, + resourceGroupName, + fileSystemName, + ) + .delete({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _fileSystemsDeleteDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "204", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return; +} + +/** Delete a FileSystemResource */ +export function fileSystemsDelete( + context: Client, + subscriptionId: string, + resourceGroupName: string, + fileSystemName: string, + options: FileSystemsDeleteOptionalParams = { requestOptions: {} }, +): PollerLike, void> { + return getLongRunningPoller( + context, + _fileSystemsDeleteDeserialize, + ["202", "204", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _fileSystemsDeleteSend( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + options, + ), + resourceLocationConfig: "location", + }, + ) as PollerLike, void>; +} + +export function _fileSystemsListByResourceGroupSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + options: FileSystemsListByResourceGroupOptionalParams = { + requestOptions: {}, + }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems", + subscriptionId, + resourceGroupName, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _fileSystemsListByResourceGroupDeserialize( + result: PathUncheckedResponse, +): Promise<_FileSystemResourceListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _fileSystemResourceListResultDeserializer(result.body); +} + +/** List FileSystemResource resources by resource group */ +export function fileSystemsListByResourceGroup( + context: Client, + subscriptionId: string, + resourceGroupName: string, + options: FileSystemsListByResourceGroupOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => + _fileSystemsListByResourceGroupSend( + context, + subscriptionId, + resourceGroupName, + options, + ), + _fileSystemsListByResourceGroupDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} + +export function _fileSystemsListBySubscriptionSend( + context: Client, + subscriptionId: string, + options: FileSystemsListBySubscriptionOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/providers/Qumulo.Storage/fileSystems", + subscriptionId, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _fileSystemsListBySubscriptionDeserialize( + result: PathUncheckedResponse, +): Promise<_FileSystemResourceListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _fileSystemResourceListResultDeserializer(result.body); +} + +/** List FileSystemResource resources by subscription ID */ +export function fileSystemsListBySubscription( + context: Client, + subscriptionId: string, + options: FileSystemsListBySubscriptionOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _fileSystemsListBySubscriptionSend(context, subscriptionId, options), + _fileSystemsListBySubscriptionDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/sdk/qumulo/arm-qumulo/src/api/index.ts b/sdk/qumulo/arm-qumulo/src/api/index.ts new file mode 100644 index 000000000000..6a6fef8af798 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/api/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + OperationsListOptionalParams, + FileSystemsGetOptionalParams, + FileSystemsCreateOrUpdateOptionalParams, + FileSystemsUpdateOptionalParams, + FileSystemsDeleteOptionalParams, + FileSystemsListByResourceGroupOptionalParams, + FileSystemsListBySubscriptionOptionalParams, +} from "./options.js"; +export { + createStorage, + StorageContext, + StorageClientOptionalParams, +} from "./storageContext.js"; +export { + fileSystemsGet, + fileSystemsCreateOrUpdate, + fileSystemsUpdate, + fileSystemsDelete, + fileSystemsListByResourceGroup, + fileSystemsListBySubscription, +} from "./fileSystems/index.js"; +export { operationsList } from "./operations/index.js"; diff --git a/sdk/qumulo/arm-qumulo/src/api/operations/index.ts b/sdk/qumulo/arm-qumulo/src/api/operations/index.ts new file mode 100644 index 000000000000..e0921dea53a7 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/api/operations/index.ts @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + StorageContext as Client, + OperationsListOptionalParams, +} from "../index.js"; +import { + _OperationListResult, + _operationListResultDeserializer, + Operation, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; + +export function _operationsListSend( + context: Client, + options: OperationsListOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/providers/Qumulo.Storage/operations") + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _operationsListDeserialize( + result: PathUncheckedResponse, +): Promise<_OperationListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _operationListResultDeserializer(result.body); +} + +/** List the operations for the provider */ +export function operationsList( + context: Client, + options: OperationsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _operationsListSend(context, options), + _operationsListDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/sdk/qumulo/arm-qumulo/src/api/options.ts b/sdk/qumulo/arm-qumulo/src/api/options.ts new file mode 100644 index 000000000000..5b841e20acc7 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/api/options.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { OperationOptions } from "@azure-rest/core-client"; + +/** Optional parameters. */ +export interface OperationsListOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface FileSystemsGetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface FileSystemsCreateOrUpdateOptionalParams + extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; +} + +/** Optional parameters. */ +export interface FileSystemsUpdateOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface FileSystemsDeleteOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; +} + +/** Optional parameters. */ +export interface FileSystemsListByResourceGroupOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface FileSystemsListBySubscriptionOptionalParams + extends OperationOptions {} diff --git a/sdk/qumulo/arm-qumulo/src/api/storageContext.ts b/sdk/qumulo/arm-qumulo/src/api/storageContext.ts new file mode 100644 index 000000000000..6f8b6edd4801 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/api/storageContext.ts @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { logger } from "../logger.js"; +import { KnownVersions } from "../models/models.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; + +export interface StorageContext extends Client {} + +/** Optional parameters for the client. */ +export interface StorageClientOptionalParams extends ClientOptions { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion?: string; +} + +export function createStorage( + credential: TokenCredential, + options: StorageClientOptionalParams = {}, +): StorageContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentInfo = `azsdk-js-arm-qumulo/1.0.0-beta.1`; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api ${userAgentInfo}` + : `azsdk-js-api ${userAgentInfo}`; + const { apiVersion: _, ...updatedOptions } = { + ...options, + userAgentOptions: { userAgentPrefix }, + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, + credentials: { + scopes: options.credentials?.scopes ?? [`${endpointUrl}/.default`], + }, + }; + const clientContext = getClient(endpointUrl, credential, updatedOptions); + clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + const apiVersion = options.apiVersion ?? "2024-06-19"; + clientContext.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")) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return clientContext; +} diff --git a/sdk/qumulo/arm-qumulo/src/classic/fileSystems/index.ts b/sdk/qumulo/arm-qumulo/src/classic/fileSystems/index.ts new file mode 100644 index 000000000000..e27bd7774cca --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/classic/fileSystems/index.ts @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { StorageContext } from "../../api/storageContext.js"; +import { + fileSystemsGet, + fileSystemsCreateOrUpdate, + fileSystemsUpdate, + fileSystemsDelete, + fileSystemsListByResourceGroup, + fileSystemsListBySubscription, +} from "../../api/fileSystems/index.js"; +import { + FileSystemResource, + FileSystemResourceUpdate, +} from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; +import { PollerLike, OperationState } from "@azure/core-lro"; +import { + FileSystemsGetOptionalParams, + FileSystemsCreateOrUpdateOptionalParams, + FileSystemsUpdateOptionalParams, + FileSystemsDeleteOptionalParams, + FileSystemsListByResourceGroupOptionalParams, + FileSystemsListBySubscriptionOptionalParams, +} from "../../api/options.js"; + +/** Interface representing a FileSystems operations. */ +export interface FileSystemsOperations { + /** Get a FileSystemResource */ + get: ( + resourceGroupName: string, + fileSystemName: string, + options?: FileSystemsGetOptionalParams, + ) => Promise; + /** Create a FileSystemResource */ + createOrUpdate: ( + resourceGroupName: string, + fileSystemName: string, + resource: FileSystemResource, + options?: FileSystemsCreateOrUpdateOptionalParams, + ) => PollerLike, FileSystemResource>; + /** Update a FileSystemResource */ + update: ( + resourceGroupName: string, + fileSystemName: string, + properties: FileSystemResourceUpdate, + options?: FileSystemsUpdateOptionalParams, + ) => Promise; + /** Delete a FileSystemResource */ + delete: ( + resourceGroupName: string, + fileSystemName: string, + options?: FileSystemsDeleteOptionalParams, + ) => PollerLike, void>; + /** List FileSystemResource resources by resource group */ + listByResourceGroup: ( + resourceGroupName: string, + options?: FileSystemsListByResourceGroupOptionalParams, + ) => PagedAsyncIterableIterator; + /** List FileSystemResource resources by subscription ID */ + listBySubscription: ( + options?: FileSystemsListBySubscriptionOptionalParams, + ) => PagedAsyncIterableIterator; +} + +export function getFileSystems( + context: StorageContext, + subscriptionId: string, +) { + return { + get: ( + resourceGroupName: string, + fileSystemName: string, + options?: FileSystemsGetOptionalParams, + ) => + fileSystemsGet( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + options, + ), + createOrUpdate: ( + resourceGroupName: string, + fileSystemName: string, + resource: FileSystemResource, + options?: FileSystemsCreateOrUpdateOptionalParams, + ) => + fileSystemsCreateOrUpdate( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + resource, + options, + ), + update: ( + resourceGroupName: string, + fileSystemName: string, + properties: FileSystemResourceUpdate, + options?: FileSystemsUpdateOptionalParams, + ) => + fileSystemsUpdate( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + properties, + options, + ), + delete: ( + resourceGroupName: string, + fileSystemName: string, + options?: FileSystemsDeleteOptionalParams, + ) => + fileSystemsDelete( + context, + subscriptionId, + resourceGroupName, + fileSystemName, + options, + ), + listByResourceGroup: ( + resourceGroupName: string, + options?: FileSystemsListByResourceGroupOptionalParams, + ) => + fileSystemsListByResourceGroup( + context, + subscriptionId, + resourceGroupName, + options, + ), + listBySubscription: ( + options?: FileSystemsListBySubscriptionOptionalParams, + ) => fileSystemsListBySubscription(context, subscriptionId, options), + }; +} + +export function getFileSystemsOperations( + context: StorageContext, + subscriptionId: string, +): FileSystemsOperations { + return { + ...getFileSystems(context, subscriptionId), + }; +} diff --git a/sdk/qumulo/arm-qumulo/src/classic/index.ts b/sdk/qumulo/arm-qumulo/src/classic/index.ts new file mode 100644 index 000000000000..532dfb11a951 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/classic/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { FileSystemsOperations } from "./fileSystems/index.js"; +export { OperationsOperations } from "./operations/index.js"; diff --git a/sdk/qumulo/arm-qumulo/src/classic/operations/index.ts b/sdk/qumulo/arm-qumulo/src/classic/operations/index.ts new file mode 100644 index 000000000000..83dc476a142c --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/classic/operations/index.ts @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { StorageContext } from "../../api/storageContext.js"; +import { operationsList } from "../../api/operations/index.js"; +import { Operation } from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; +import { OperationsListOptionalParams } from "../../api/options.js"; + +/** Interface representing a Operations operations. */ +export interface OperationsOperations { + /** List the operations for the provider */ + list: ( + options?: OperationsListOptionalParams, + ) => PagedAsyncIterableIterator; +} + +export function getOperations(context: StorageContext) { + return { + list: (options?: OperationsListOptionalParams) => + operationsList(context, options), + }; +} + +export function getOperationsOperations( + context: StorageContext, +): OperationsOperations { + return { + ...getOperations(context), + }; +} diff --git a/sdk/qumulo/arm-qumulo/src/helpers/serializerHelpers.ts b/sdk/qumulo/arm-qumulo/src/helpers/serializerHelpers.ts new file mode 100644 index 000000000000..4baaac77c8be --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/sdk/qumulo/arm-qumulo/src/index.ts b/sdk/qumulo/arm-qumulo/src/index.ts new file mode 100644 index 000000000000..a0abe21bed3a --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/index.ts @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./static-helpers/pagingHelpers.js"; + +export { StorageClient } from "./storageClient.js"; +export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; +export { + FileSystemResource, + FileSystemResourceProperties, + MarketplaceDetails, + KnownMarketplaceSubscriptionStatus, + MarketplaceSubscriptionStatus, + KnownProvisioningState, + ProvisioningState, + UserDetails, + ManagedServiceIdentity, + KnownManagedServiceIdentityType, + ManagedServiceIdentityType, + UserAssignedIdentity, + TrackedResource, + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, + FileSystemResourceUpdate, + FileSystemResourceUpdateProperties, + Operation, + OperationDisplay, + KnownOrigin, + Origin, + KnownActionType, + ActionType, + KnownVersions, +} from "./models/index.js"; +export { + OperationsListOptionalParams, + FileSystemsGetOptionalParams, + FileSystemsCreateOrUpdateOptionalParams, + FileSystemsUpdateOptionalParams, + FileSystemsDeleteOptionalParams, + FileSystemsListByResourceGroupOptionalParams, + FileSystemsListBySubscriptionOptionalParams, + StorageClientOptionalParams, +} from "./api/index.js"; +export { + FileSystemsOperations, + OperationsOperations, +} from "./classic/index.js"; +export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/sdk/qumulo/arm-qumulo/src/logger.ts b/sdk/qumulo/arm-qumulo/src/logger.ts new file mode 100644 index 000000000000..931f1716c223 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("arm-qumulo"); diff --git a/sdk/qumulo/arm-qumulo/src/models/index.ts b/sdk/qumulo/arm-qumulo/src/models/index.ts new file mode 100644 index 000000000000..606d1d1a4c1a --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/models/index.ts @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + FileSystemResource, + FileSystemResourceProperties, + MarketplaceDetails, + KnownMarketplaceSubscriptionStatus, + MarketplaceSubscriptionStatus, + KnownProvisioningState, + ProvisioningState, + UserDetails, + ManagedServiceIdentity, + KnownManagedServiceIdentityType, + ManagedServiceIdentityType, + UserAssignedIdentity, + TrackedResource, + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, + FileSystemResourceUpdate, + FileSystemResourceUpdateProperties, + Operation, + OperationDisplay, + KnownOrigin, + Origin, + KnownActionType, + ActionType, + KnownVersions, +} from "./models.js"; diff --git a/sdk/qumulo/arm-qumulo/src/models/models.ts b/sdk/qumulo/arm-qumulo/src/models/models.ts new file mode 100644 index 000000000000..1010fefd3c5a --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/models/models.ts @@ -0,0 +1,627 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface FileSystemResource extends TrackedResource { + /** The resource-specific properties for this resource. */ + properties?: FileSystemResourceProperties; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentity; +} + +export function fileSystemResourceSerializer(item: FileSystemResource): any { + return { + tags: item["tags"], + location: item["location"], + properties: !item["properties"] + ? item["properties"] + : fileSystemResourcePropertiesSerializer(item["properties"]), + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentitySerializer(item["identity"]), + }; +} + +export function fileSystemResourceDeserializer(item: any): FileSystemResource { + return { + tags: item["tags"], + location: item["location"], + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + properties: !item["properties"] + ? item["properties"] + : fileSystemResourcePropertiesDeserializer(item["properties"]), + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentityDeserializer(item["identity"]), + }; +} + +/** Properties specific to the Qumulo File System resource */ +export interface FileSystemResourceProperties { + /** Marketplace details */ + marketplaceDetails: MarketplaceDetails; + /** Provisioning State of the resource */ + readonly provisioningState?: ProvisioningState; + /** Storage Sku */ + storageSku: string; + /** User Details */ + userDetails: UserDetails; + /** Delegated subnet id for Vnet injection */ + delegatedSubnetId: string; + /** File system Id of the resource */ + clusterLoginUrl?: string; + /** Private IPs of the resource */ + privateIPs?: string[]; + /** Initial administrator password of the resource */ + adminPassword: string; + /** Availability zone */ + availabilityZone?: string; +} + +export function fileSystemResourcePropertiesSerializer( + item: FileSystemResourceProperties, +): any { + return { + marketplaceDetails: marketplaceDetailsSerializer( + item["marketplaceDetails"], + ), + storageSku: item["storageSku"], + userDetails: userDetailsSerializer(item["userDetails"]), + delegatedSubnetId: item["delegatedSubnetId"], + clusterLoginUrl: item["clusterLoginUrl"], + privateIPs: !item["privateIPs"] + ? item["privateIPs"] + : item["privateIPs"].map((p: any) => { + return p; + }), + adminPassword: item["adminPassword"], + availabilityZone: item["availabilityZone"], + }; +} + +export function fileSystemResourcePropertiesDeserializer( + item: any, +): FileSystemResourceProperties { + return { + marketplaceDetails: marketplaceDetailsDeserializer( + item["marketplaceDetails"], + ), + provisioningState: item["provisioningState"], + storageSku: item["storageSku"], + userDetails: userDetailsDeserializer(item["userDetails"]), + delegatedSubnetId: item["delegatedSubnetId"], + clusterLoginUrl: item["clusterLoginUrl"], + privateIPs: !item["privateIPs"] + ? item["privateIPs"] + : item["privateIPs"].map((p: any) => { + return p; + }), + adminPassword: item["adminPassword"], + availabilityZone: item["availabilityZone"], + }; +} + +/** MarketplaceDetails of Qumulo FileSystem resource */ +export interface MarketplaceDetails { + /** Marketplace Subscription Id */ + marketplaceSubscriptionId?: string; + /** Plan Id */ + planId: string; + /** Offer Id */ + offerId: string; + /** Publisher Id */ + publisherId?: string; + /** Term Unit */ + termUnit?: string; + /** Marketplace subscription status */ + readonly marketplaceSubscriptionStatus?: MarketplaceSubscriptionStatus; +} + +export function marketplaceDetailsSerializer(item: MarketplaceDetails): any { + return { + marketplaceSubscriptionId: item["marketplaceSubscriptionId"], + planId: item["planId"], + offerId: item["offerId"], + publisherId: item["publisherId"], + termUnit: item["termUnit"], + }; +} + +export function marketplaceDetailsDeserializer(item: any): MarketplaceDetails { + return { + marketplaceSubscriptionId: item["marketplaceSubscriptionId"], + planId: item["planId"], + offerId: item["offerId"], + publisherId: item["publisherId"], + termUnit: item["termUnit"], + marketplaceSubscriptionStatus: item["marketplaceSubscriptionStatus"], + }; +} + +/** Marketplace subscription status of the file system resource */ +export enum KnownMarketplaceSubscriptionStatus { + /** Fulfillment has not started */ + PendingFulfillmentStart = "PendingFulfillmentStart", + /** Marketplace offer is subscribed */ + Subscribed = "Subscribed", + /** Marketplace offer is suspended because of non payment */ + Suspended = "Suspended", + /** Marketplace offer is unsubscribed */ + Unsubscribed = "Unsubscribed", +} + +/** + * Marketplace subscription status of the file system resource \ + * {@link KnownMarketplaceSubscriptionStatus} can be used interchangeably with MarketplaceSubscriptionStatus, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **PendingFulfillmentStart**: Fulfillment has not started \ + * **Subscribed**: Marketplace offer is subscribed \ + * **Suspended**: Marketplace offer is suspended because of non payment \ + * **Unsubscribed**: Marketplace offer is unsubscribed + */ +export type MarketplaceSubscriptionStatus = string; + +/** Provisioning State of the File system resource */ +export enum KnownProvisioningState { + /** File system resource creation request accepted */ + Accepted = "Accepted", + /** File system resource creation started */ + Creating = "Creating", + /** File system resource is being updated */ + Updating = "Updating", + /** File system resource deletion started */ + Deleting = "Deleting", + /** File system resource creation successful */ + Succeeded = "Succeeded", + /** File system resource creation failed */ + Failed = "Failed", + /** File system resource creation canceled */ + Canceled = "Canceled", + /** File system resource is deleted */ + Deleted = "Deleted", +} + +/** + * Provisioning State of the File system resource \ + * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Accepted**: File system resource creation request accepted \ + * **Creating**: File system resource creation started \ + * **Updating**: File system resource is being updated \ + * **Deleting**: File system resource deletion started \ + * **Succeeded**: File system resource creation successful \ + * **Failed**: File system resource creation failed \ + * **Canceled**: File system resource creation canceled \ + * **Deleted**: File system resource is deleted + */ +export type ProvisioningState = string; + +/** User Details of Qumulo FileSystem resource */ +export interface UserDetails { + /** User Email */ + email: string; +} + +export function userDetailsSerializer(item: UserDetails): any { + return { email: item["email"] }; +} + +export function userDetailsDeserializer(item: any): UserDetails { + return { + email: item["email"], + }; +} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentity { + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; + /** The type of managed identity assigned to this resource. */ + type: ManagedServiceIdentityType; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +export function managedServiceIdentitySerializer( + item: ManagedServiceIdentity, +): any { + return { + type: item["type"], + userAssignedIdentities: !item["userAssignedIdentities"] + ? item["userAssignedIdentities"] + : userAssignedIdentityRecordSerializer(item["userAssignedIdentities"]), + }; +} + +export function managedServiceIdentityDeserializer( + item: any, +): ManagedServiceIdentity { + return { + principalId: item["principalId"], + tenantId: item["tenantId"], + type: item["type"], + userAssignedIdentities: !item["userAssignedIdentities"] + ? item["userAssignedIdentities"] + : userAssignedIdentityRecordDeserializer(item["userAssignedIdentities"]), + }; +} + +/** Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). */ +export enum KnownManagedServiceIdentityType { + /** No managed identity. */ + None = "None", + /** System assigned managed identity. */ + SystemAssigned = "SystemAssigned", + /** User assigned managed identity. */ + UserAssigned = "UserAssigned", + /** System and user assigned managed identity. */ + "SystemAssigned,UserAssigned" = "SystemAssigned,UserAssigned", +} + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). \ + * {@link KnownManagedServiceIdentityType} can be used interchangeably with ManagedServiceIdentityType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **None**: No managed identity. \ + * **SystemAssigned**: System assigned managed identity. \ + * **UserAssigned**: User assigned managed identity. \ + * **SystemAssigned,UserAssigned**: System and user assigned managed identity. + */ +export type ManagedServiceIdentityType = string; + +export function userAssignedIdentityRecordSerializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : userAssignedIdentitySerializer(item[key]); + }); + return result; +} + +export function userAssignedIdentityRecordDeserializer( + item: Record, +): Record { + const result: Record = {}; + Object.keys(item).map((key) => { + result[key] = !item[key] + ? item[key] + : userAssignedIdentityDeserializer(item[key]); + }); + return result; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentity { + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; +} + +export function userAssignedIdentitySerializer( + item: UserAssignedIdentity, +): any { + return item; +} + +export function userAssignedIdentityDeserializer( + item: any, +): UserAssignedIdentity { + return { + principalId: item["principalId"], + clientId: item["clientId"], + }; +} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResource extends Resource { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +export function trackedResourceSerializer(item: TrackedResource): any { + return { tags: item["tags"], location: item["location"] }; +} + +export function trackedResourceDeserializer(item: any): TrackedResource { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + tags: item["tags"], + location: item["location"], + }; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface Resource { + /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ + readonly id?: string; + /** The name of the resource */ + readonly name?: string; + /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ + readonly type?: string; + /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ + readonly systemData?: SystemData; +} + +export function resourceSerializer(item: Resource): any { + return item; +} + +export function resourceDeserializer(item: any): Resource { + return { + id: item["id"], + name: item["name"], + type: item["type"], + systemData: !item["systemData"] + ? item["systemData"] + : systemDataDeserializer(item["systemData"]), + }; +} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** The type of identity that created the resource. */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** The type of identity that last modified the resource. */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date; +} + +export function systemDataDeserializer(item: any): SystemData { + return { + createdBy: item["createdBy"], + createdByType: item["createdByType"], + createdAt: !item["createdAt"] + ? item["createdAt"] + : new Date(item["createdAt"]), + lastModifiedBy: item["lastModifiedBy"], + lastModifiedByType: item["lastModifiedByType"], + lastModifiedAt: !item["lastModifiedAt"] + ? item["lastModifiedAt"] + : new Date(item["lastModifiedAt"]), + }; +} + +/** The kind of entity that created the resource. */ +export enum KnownCreatedByType { + /** The entity was created by a user. */ + User = "User", + /** The entity was created by an application. */ + Application = "Application", + /** The entity was created by a managed identity. */ + ManagedIdentity = "ManagedIdentity", + /** The entity was created by a key. */ + Key = "Key", +} + +/** + * The kind of entity that created the resource. \ + * {@link KnowncreatedByType} can be used interchangeably with createdByType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **User**: The entity was created by a user. \ + * **Application**: The entity was created by an application. \ + * **ManagedIdentity**: The entity was created by a managed identity. \ + * **Key**: The entity was created by a key. + */ +export type CreatedByType = string; + +/** The type used for update operations of the FileSystemResource. */ +export interface FileSystemResourceUpdate { + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentity; + /** Resource tags. */ + tags?: Record; + /** The updatable properties of the FileSystemResource. */ + properties?: FileSystemResourceUpdateProperties; +} + +export function fileSystemResourceUpdateSerializer( + item: FileSystemResourceUpdate, +): any { + return { + identity: !item["identity"] + ? item["identity"] + : managedServiceIdentitySerializer(item["identity"]), + tags: item["tags"], + properties: !item["properties"] + ? item["properties"] + : fileSystemResourceUpdatePropertiesSerializer(item["properties"]), + }; +} + +/** The updatable properties of the FileSystemResource. */ +export interface FileSystemResourceUpdateProperties { + /** Marketplace details */ + marketplaceDetails?: MarketplaceDetails; + /** User Details */ + userDetails?: UserDetails; + /** Delegated subnet id for Vnet injection */ + delegatedSubnetId?: string; +} + +export function fileSystemResourceUpdatePropertiesSerializer( + item: FileSystemResourceUpdateProperties, +): any { + return { + marketplaceDetails: !item["marketplaceDetails"] + ? item["marketplaceDetails"] + : marketplaceDetailsSerializer(item["marketplaceDetails"]), + userDetails: !item["userDetails"] + ? item["userDetails"] + : userDetailsSerializer(item["userDetails"]), + delegatedSubnetId: item["delegatedSubnetId"], + }; +} + +/** The response of a FileSystemResource list operation. */ +export interface _FileSystemResourceListResult { + /** The FileSystemResource items on this page */ + value: FileSystemResource[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _fileSystemResourceListResultDeserializer( + item: any, +): _FileSystemResourceListResult { + return { + value: fileSystemResourceArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function fileSystemResourceArraySerializer( + result: Array, +): any[] { + return result.map((item) => { + return fileSystemResourceSerializer(item); + }); +} + +export function fileSystemResourceArrayDeserializer( + result: Array, +): any[] { + return result.map((item) => { + return fileSystemResourceDeserializer(item); + }); +} + +/** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */ +export interface _OperationListResult { + /** The Operation items on this page */ + value: Operation[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _operationListResultDeserializer( + item: any, +): _OperationListResult { + return { + value: operationArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function operationArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return operationDeserializer(item); + }); +} + +/** Details of a REST API operation, returned from the Resource Provider Operations API */ +export interface Operation { + /** The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" */ + readonly name?: string; + /** Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane operations. */ + readonly isDataAction?: boolean; + /** Localized display information for this particular operation. */ + display?: OperationDisplay; + /** The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" */ + readonly origin?: Origin; + /** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ + readonly actionType?: ActionType; +} + +export function operationDeserializer(item: any): Operation { + return { + name: item["name"], + isDataAction: item["isDataAction"], + display: !item["display"] + ? item["display"] + : operationDisplayDeserializer(item["display"]), + origin: item["origin"], + actionType: item["actionType"], + }; +} + +/** Localized display information for and operation. */ +export interface OperationDisplay { + /** The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". */ + readonly provider?: string; + /** The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". */ + readonly resource?: string; + /** The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". */ + readonly operation?: string; + /** The short, localized friendly description of the operation; suitable for tool tips and detailed views. */ + readonly description?: string; +} + +export function operationDisplayDeserializer(item: any): OperationDisplay { + return { + provider: item["provider"], + resource: item["resource"], + operation: item["operation"], + description: item["description"], + }; +} + +/** The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" */ +export enum KnownOrigin { + /** Indicates the operation is initiated by a user. */ + user = "user", + /** Indicates the operation is initiated by a system. */ + system = "system", + /** Indicates the operation is initiated by a user or system. */ + "user,system" = "user,system", +} + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" \ + * {@link KnownOrigin} can be used interchangeably with Origin, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **user**: Indicates the operation is initiated by a user. \ + * **system**: Indicates the operation is initiated by a system. \ + * **user,system**: Indicates the operation is initiated by a user or system. + */ +export type Origin = string; + +/** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ +export enum KnownActionType { + /** Actions are for internal-only APIs. */ + Internal = "Internal", +} + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. \ + * {@link KnownActionType} can be used interchangeably with ActionType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Internal**: Actions are for internal-only APIs. + */ +export type ActionType = string; + +/** The available API versions. */ +export enum KnownVersions { + /** The 2024-06-19 Stable API version. */ + v2_stable = "2024-06-19", +} diff --git a/sdk/qumulo/arm-qumulo/src/restorePollerHelpers.ts b/sdk/qumulo/arm-qumulo/src/restorePollerHelpers.ts new file mode 100644 index 000000000000..90f8197d396c --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/restorePollerHelpers.ts @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { StorageClient } from "./storageClient.js"; +import { + _fileSystemsCreateOrUpdateDeserialize, + _fileSystemsDeleteDeserialize, +} from "./api/fileSystems/index.js"; +import { getLongRunningPoller } from "./static-helpers/pollingHelpers.js"; +import { + OperationOptions, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { + PollerLike, + OperationState, + deserializeState, + ResourceLocationConfig, +} from "@azure/core-lro"; + +export interface RestorePollerOptions< + TResult, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +> extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** Deserialization function for raw response body */ + processResponseBody?: (result: TResponse) => Promise; +} + +/** + * Creates a poller from the serialized state of another poller. This can be + * useful when you want to create pollers on a different host or a poller + * needs to be constructed after the original one is not in scope. + */ +export function restorePoller( + client: StorageClient, + serializedState: string, + sourceOperation: ( + ...args: any[] + ) => PollerLike, TResult>, + options?: RestorePollerOptions, +): PollerLike, TResult> { + const pollerConfig = deserializeState(serializedState).config; + const { initialRequestUrl, requestMethod, metadata } = pollerConfig; + if (!initialRequestUrl || !requestMethod) { + throw new Error( + `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, + ); + } + const resourceLocationConfig = metadata?.["resourceLocationConfig"] as + | ResourceLocationConfig + | undefined; + const { deserializer, expectedStatuses = [] } = + getDeserializationHelper(initialRequestUrl, requestMethod) ?? {}; + const deserializeHelper = options?.processResponseBody ?? deserializer; + if (!deserializeHelper) { + throw new Error( + `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, + ); + } + return getLongRunningPoller( + (client as any)["_client"] ?? client, + deserializeHelper as (result: TResponse) => Promise, + expectedStatuses, + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + resourceLocationConfig, + restoreFrom: serializedState, + initialRequestUrl, + }, + ); +} + +interface DeserializationHelper { + deserializer: Function; + expectedStatuses: string[]; +} + +const deserializeMap: Record = { + "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}": + { + deserializer: _fileSystemsCreateOrUpdateDeserialize, + expectedStatuses: ["200", "201"], + }, + "DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}": + { + deserializer: _fileSystemsDeleteDeserialize, + expectedStatuses: ["202", "204", "200"], + }, +}; + +function getDeserializationHelper( + urlStr: string, + method: string, +): DeserializationHelper | undefined { + const path = new URL(urlStr).pathname; + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: DeserializationHelper | undefined; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(deserializeMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/sdk/qumulo/arm-qumulo/src/static-helpers/pagingHelpers.ts b/sdk/qumulo/arm-qumulo/src/static-helpers/pagingHelpers.ts new file mode 100644 index 000000000000..97a81e74e301 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/static-helpers/pagingHelpers.ts @@ -0,0 +1,274 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; + +/** + * Options for the byPage method + */ +export interface PageSettings { + /** + * A reference to a specific page to start iterating from. + */ + continuationToken?: string; +} + +/** + * An interface that describes a page of results. + */ +export type ContinuablePage = TPage & { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +}; + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; +} + +/** + * An interface that describes how to communicate with the service. + */ +export interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * Link to the first page of results. + */ + firstPageLink?: string; + /** + * A method that returns a page of results. + */ + getPage: ( + pageLink?: string, + ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: ( + settings?: TPageSettings, + ) => AsyncIterableIterator>; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => TElement[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => PromiseLike, + expectedStatuses: string[], + options: BuildPagedAsyncIteratorOptions = {}, +): PagedAsyncIterableIterator { + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; + const pagedResult: PagedResult = { + getPage: async (pageLink?: string) => { + const result = + pageLink === undefined + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + checkPagingRequest(result, expectedStatuses); + const results = await processResponseBody(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName) as TPage; + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }, + }; + return getPagedAsyncIterator(pagedResult); +} + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ + +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult, + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {}, +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink, + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { + throw new RestError( + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, + ); + } + + if (nextLink === null) { + return undefined; + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + if (!Array.isArray(value)) { + throw new RestError( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest( + response: PathUncheckedResponse, + expectedStatuses: string[], +): void { + if (!expectedStatuses.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/sdk/qumulo/arm-qumulo/src/static-helpers/pollingHelpers.ts b/sdk/qumulo/arm-qumulo/src/static-helpers/pollingHelpers.ts new file mode 100644 index 000000000000..2edbf783be53 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/static-helpers/pollingHelpers.ts @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PollerLike, + OperationState, + ResourceLocationConfig, + RunningOperation, + createHttpPoller, + OperationResponse, +} from "@azure/core-lro"; + +import { + Client, + PathUncheckedResponse, + createRestError, +} from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; + +export interface GetLongRunningPollerOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * The potential location of the result of the LRO if specified by the LRO extension in the swagger. + */ + resourceLocationConfig?: ResourceLocationConfig; + /** + * The original url of the LRO + * Should not be null when restoreFrom is set + */ + initialRequestUrl?: string; + /** + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. + */ + restoreFrom?: string; + /** + * The function to get the initial response + */ + getInitialResponse?: () => PromiseLike; +} +export function getLongRunningPoller< + TResponse extends PathUncheckedResponse, + TResult = void, +>( + client: Client, + processResponseBody: (result: TResponse) => Promise, + expectedStatuses: string[], + options: GetLongRunningPollerOptions, +): PollerLike, TResult> { + const { restoreFrom, getInitialResponse } = options; + if (!restoreFrom && !getInitialResponse) { + throw new Error( + "Either restoreFrom or getInitialResponse must be specified", + ); + } + let initialResponse: TResponse | undefined = undefined; + const pollAbortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + if (!getInitialResponse) { + throw new Error( + "getInitialResponse is required when initializing a new poller", + ); + } + initialResponse = await getInitialResponse(); + return getLroResponse(initialResponse, expectedStatuses); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { + abortSignal?: AbortSignalLike; + }, + ) => { + // The poll request would both listen to the user provided abort signal and the poller's own abort signal + function abortListener(): void { + pollAbortController.abort(); + } + const abortSignal = pollAbortController.signal; + if (options.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (pollOptions?.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (!abortSignal.aborted) { + options.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + pollOptions?.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client.pathUnchecked(path).get({ abortSignal }); + } finally { + options.abortSignal?.removeEventListener("abort", abortListener); + pollOptions?.abortSignal?.removeEventListener("abort", abortListener); + } + + return getLroResponse(response as TResponse, expectedStatuses); + }, + }; + return createHttpPoller(poller, { + intervalInMs: options?.updateIntervalInMs, + resourceLocationConfig: options?.resourceLocationConfig, + restoreFrom: options?.restoreFrom, + processResult: (result: unknown) => { + return processResponseBody(result as TResponse); + }, + }); +} +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @param deserializeFn - deserialize function to convert Rest response to modular output + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResponse, + expectedStatuses: string[], +): OperationResponse { + if (!expectedStatuses.includes(response.status)) { + throw createRestError(response); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/sdk/qumulo/arm-qumulo/src/storageClient.ts b/sdk/qumulo/arm-qumulo/src/storageClient.ts new file mode 100644 index 000000000000..f2821530e9a0 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/src/storageClient.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + getOperationsOperations, + OperationsOperations, +} from "./classic/operations/index.js"; +import { + getFileSystemsOperations, + FileSystemsOperations, +} from "./classic/fileSystems/index.js"; +import { + createStorage, + StorageContext, + StorageClientOptionalParams, +} from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; + +export { StorageClientOptionalParams } from "./api/storageContext.js"; + +export class StorageClient { + private _client: StorageContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + constructor( + credential: TokenCredential, + subscriptionId: string, + options: StorageClientOptionalParams = {}, + ) { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : `azsdk-js-client`; + this._client = createStorage(credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); + this.pipeline = this._client.pipeline; + this.operations = getOperationsOperations(this._client); + this.fileSystems = getFileSystemsOperations(this._client, subscriptionId); + } + + /** The operation groups for Operations */ + public readonly operations: OperationsOperations; + /** The operation groups for FileSystems */ + public readonly fileSystems: FileSystemsOperations; +} diff --git a/sdk/qumulo/arm-qumulo/test/public/sampleTest.spec.ts b/sdk/qumulo/arm-qumulo/test/public/sampleTest.spec.ts new file mode 100644 index 000000000000..d4919ac91ac5 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/test/public/sampleTest.spec.ts @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createRecorder } from "./utils/recordedClient.js"; +import { assert, beforeEach, afterEach, it, describe } from "vitest"; + +describe("My test", () => { + // let recorder: Recorder; + + beforeEach(async function () { + // recorder = await createRecorder(this); + }); + + afterEach(async function () { + // await recorder.stop(); + }); + + it("sample test", async function () { + assert.equal(1, 1); + }); +}); diff --git a/sdk/qumulo/arm-qumulo/test/public/utils/recordedClient.ts b/sdk/qumulo/arm-qumulo/test/public/utils/recordedClient.ts new file mode 100644 index 000000000000..6e425fdcfdf9 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/test/public/utils/recordedClient.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + Recorder, + RecorderStartOptions, + VitestTestContext, +} from "@azure-tools/test-recorder"; + +const replaceableVariables: Record = { + SUBSCRIPTION_ID: "azure_subscription_id", +}; + +const recorderEnvSetup: RecorderStartOptions = { + envSetupForPlayback: replaceableVariables, +}; + +/** + * creates the recorder and reads the environment variables from the `.env` file. + * Should be called first in the test suite to make sure environment variables are + * read before they are being used. + */ +export async function createRecorder( + context: VitestTestContext, +): Promise { + const recorder = new Recorder(context); + await recorder.start(recorderEnvSetup); + return recorder; +} diff --git a/sdk/qumulo/arm-qumulo/tsconfig.browser.config.json b/sdk/qumulo/arm-qumulo/tsconfig.browser.config.json new file mode 100644 index 000000000000..091177fcb991 --- /dev/null +++ b/sdk/qumulo/arm-qumulo/tsconfig.browser.config.json @@ -0,0 +1,10 @@ +{ + "extends": "./.tshy/build.json", + "include": ["src/**/*.ts", "src/**/*.mts", "test/**/*.spec.ts"], + "exclude": ["test/**/node/**/*.ts"], + "compilerOptions": { + "outDir": "./dist-test/browser", + "rootDir": ".", + "skipLibCheck": true + } +} diff --git a/sdk/qumulo/arm-qumulo/tsconfig.json b/sdk/qumulo/arm-qumulo/tsconfig.json new file mode 100644 index 000000000000..72266609583d --- /dev/null +++ b/sdk/qumulo/arm-qumulo/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../tsconfig", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "skipLibCheck": true + }, + "include": [ + "src/**/*.ts", + "src/**/*.mts", + "src/**/*.cts", + "test/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/sdk/qumulo/arm-qumulo/tsp-location.yaml b/sdk/qumulo/arm-qumulo/tsp-location.yaml new file mode 100644 index 000000000000..a5ffb04db40c --- /dev/null +++ b/sdk/qumulo/arm-qumulo/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/liftrqumulo/Qumulo.Storage.Management +commit: dec06f3f49684c5565dd4eb1a3a8a92b141fbab7 +repo: ../azure-rest-api-specs +additionalDirectories: diff --git a/sdk/qumulo/arm-qumulo/vitest.browser.config.ts b/sdk/qumulo/arm-qumulo/vitest.browser.config.ts new file mode 100644 index 000000000000..da68c1d231aa --- /dev/null +++ b/sdk/qumulo/arm-qumulo/vitest.browser.config.ts @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; + +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); + +export default defineConfig({ + define: { + "process.env": process.env, + }, + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", + }, + browser: { + enabled: true, + headless: true, + name: "chromium", + provider: "playwright", + }, + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["dist-test/browser/**/*.spec.js"], + coverage: { + include: ["dist-test/browser/**/*.spec.js"], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage-browser", + }, + testTimeout: 1200000, + hookTimeout: 1200000, + }, +}); diff --git a/sdk/qumulo/arm-qumulo/vitest.config.ts b/sdk/qumulo/arm-qumulo/vitest.config.ts new file mode 100644 index 000000000000..2cf5d0e02c2e --- /dev/null +++ b/sdk/qumulo/arm-qumulo/vitest.config.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; + +export default defineConfig({ + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", + }, + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["test/**/*.spec.ts"], + exclude: ["test/**/browser/*.spec.ts"], + coverage: { + include: ["src/**/*.ts"], + exclude: [ + "src/**/*-browser.mts", + "src/**/*-react-native.mts", + "vitest*.config.ts", + "samples-dev/**/*.ts", + ], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage", + }, + testTimeout: 1200000, + hookTimeout: 1200000, + }, +});