From 180bcc2fb7c9d5b25f77944eaa85cdd040122c5e Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Fri, 8 Nov 2024 13:15:39 +0000 Subject: [PATCH] CodeGen from PR 31037 in Azure/azure-rest-api-specs Merge 93293ed71578a7875d49a798f892bb426391095c into 59fa2c3fd854c9f5f2beb56220bcc21d979ec52d --- .../impact/armimpact/CHANGELOG.md | 8 + .../impact/armimpact/LICENSE.txt | 21 + .../impact/armimpact/README.md | 92 ++ .../impact/armimpact/autorest.md | 13 + sdk/resourcemanager/impact/armimpact/build.go | 7 + .../impact/armimpact/categories_client.go | 164 +++ sdk/resourcemanager/impact/armimpact/ci.yml | 28 + .../impact/armimpact/client_factory.go | 76 ++ .../impact/armimpact/connectors_client.go | 346 +++++ .../impact/armimpact/constants.go | 274 ++++ .../armimpact/fake/categories_server.go | 158 +++ .../armimpact/fake/connectors_server.go | 266 ++++ .../impact/armimpact/fake/insights_server.go | 230 ++++ .../impact/armimpact/fake/internal.go | 72 ++ .../armimpact/fake/operations_server.go | 96 ++ .../impact/armimpact/fake/server_factory.go | 97 ++ .../impact/armimpact/fake/time_rfc3339.go | 110 ++ .../armimpact/fake/workloadimpacts_server.go | 227 ++++ sdk/resourcemanager/impact/armimpact/go.mod | 11 + sdk/resourcemanager/impact/armimpact/go.sum | 12 + .../impact/armimpact/insights_client.go | 290 +++++ .../impact/armimpact/models.go | 451 +++++++ .../impact/armimpact/models_serde.go | 1146 +++++++++++++++++ .../impact/armimpact/operations_client.go | 88 ++ .../impact/armimpact/options.go | 100 ++ .../impact/armimpact/responses.go | 102 ++ .../impact/armimpact/time_rfc3339.go | 110 ++ .../armimpact/workloadimpacts_client.go | 283 ++++ 28 files changed, 4878 insertions(+) create mode 100644 sdk/resourcemanager/impact/armimpact/CHANGELOG.md create mode 100644 sdk/resourcemanager/impact/armimpact/LICENSE.txt create mode 100644 sdk/resourcemanager/impact/armimpact/README.md create mode 100644 sdk/resourcemanager/impact/armimpact/autorest.md create mode 100644 sdk/resourcemanager/impact/armimpact/build.go create mode 100644 sdk/resourcemanager/impact/armimpact/categories_client.go create mode 100644 sdk/resourcemanager/impact/armimpact/ci.yml create mode 100644 sdk/resourcemanager/impact/armimpact/client_factory.go create mode 100644 sdk/resourcemanager/impact/armimpact/connectors_client.go create mode 100644 sdk/resourcemanager/impact/armimpact/constants.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/categories_server.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/connectors_server.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/insights_server.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/internal.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/operations_server.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/server_factory.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/time_rfc3339.go create mode 100644 sdk/resourcemanager/impact/armimpact/fake/workloadimpacts_server.go create mode 100644 sdk/resourcemanager/impact/armimpact/go.mod create mode 100644 sdk/resourcemanager/impact/armimpact/go.sum create mode 100644 sdk/resourcemanager/impact/armimpact/insights_client.go create mode 100644 sdk/resourcemanager/impact/armimpact/models.go create mode 100644 sdk/resourcemanager/impact/armimpact/models_serde.go create mode 100644 sdk/resourcemanager/impact/armimpact/operations_client.go create mode 100644 sdk/resourcemanager/impact/armimpact/options.go create mode 100644 sdk/resourcemanager/impact/armimpact/responses.go create mode 100644 sdk/resourcemanager/impact/armimpact/time_rfc3339.go create mode 100644 sdk/resourcemanager/impact/armimpact/workloadimpacts_client.go diff --git a/sdk/resourcemanager/impact/armimpact/CHANGELOG.md b/sdk/resourcemanager/impact/armimpact/CHANGELOG.md new file mode 100644 index 000000000000..f6e196dbc27e --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 0.1.0 (2024-11-08) +### Other Changes + +The package of `github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact` is using our [next generation design principles](https://azure.github.io/azure-sdk/general_introduction.html). + +To learn more, please refer to our documentation [Quick Start](https://aka.ms/azsdk/go/mgmt). \ No newline at end of file diff --git a/sdk/resourcemanager/impact/armimpact/LICENSE.txt b/sdk/resourcemanager/impact/armimpact/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +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/resourcemanager/impact/armimpact/README.md b/sdk/resourcemanager/impact/armimpact/README.md new file mode 100644 index 000000000000..2c2860c67413 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/README.md @@ -0,0 +1,92 @@ +# Azure Impact Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact) + +The `armimpact` module provides operations for working with Azure Impact. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/impact/armimpact) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 or above (You could download and install the latest version of Go from [here](https://go.dev/doc/install). It will replace the existing Go on your machine. If you want to install multiple Go versions on the same machine, you could refer this [doc](https://go.dev/doc/manage-install).) + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Impact module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Impact. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Client Factory + +Azure Impact module consists of one or more clients. We provide a client factory which could be used to create any client in this module. + +```go +clientFactory, err := armimpact.NewClientFactory(, cred, nil) +``` + +You can use `ClientOptions` in package `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` to set endpoint to connect with public and sovereign clouds as well as Azure Stack. For more information, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +```go +options := arm.ClientOptions { + ClientOptions: azcore.ClientOptions { + Cloud: cloud.AzureChina, + }, +} +clientFactory, err := armimpact.NewClientFactory(, cred, &options) +``` + +## Clients + +A client groups a set of related APIs, providing access to its functionality. Create one or more clients to access the APIs you require using client factory. + +```go +client := clientFactory.NewCategoriesClient() +``` + +## Fakes + +The fake package contains types used for constructing in-memory fake servers used in unit tests. +This allows writing tests to cover various success/error conditions without the need for connecting to a live service. + +Please see https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/samples/fakes for details and examples on how to use fakes. + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Impact` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/impact/armimpact/autorest.md b/sdk/resourcemanager/impact/armimpact/autorest.md new file mode 100644 index 000000000000..53d10b4b9a12 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/autorest.md @@ -0,0 +1,13 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/impact/resource-manager/readme.md +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/impact/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 + +``` \ No newline at end of file diff --git a/sdk/resourcemanager/impact/armimpact/build.go b/sdk/resourcemanager/impact/armimpact/build.go new file mode 100644 index 000000000000..0c343e04d5ac --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate -alwaysSetBodyParamRequired -removeUnreferencedTypes resourcemanager/impact/armimpact + +package armimpact diff --git a/sdk/resourcemanager/impact/armimpact/categories_client.go b/sdk/resourcemanager/impact/armimpact/categories_client.go new file mode 100644 index 000000000000..1d7e1b809319 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/categories_client.go @@ -0,0 +1,164 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CategoriesClient contains the methods for the ImpactCategories group. +// Don't use this type directly, use NewCategoriesClient() instead. +type CategoriesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCategoriesClient creates a new instance of CategoriesClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewCategoriesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CategoriesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CategoriesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a ImpactCategory +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - impactCategoryName - Name of the impact category +// - options - CategoriesClientGetOptions contains the optional parameters for the CategoriesClient.Get method. +func (client *CategoriesClient) Get(ctx context.Context, impactCategoryName string, options *CategoriesClientGetOptions) (CategoriesClientGetResponse, error) { + var err error + const operationName = "CategoriesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, impactCategoryName, options) + if err != nil { + return CategoriesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CategoriesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CategoriesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CategoriesClient) getCreateRequest(ctx context.Context, impactCategoryName string, options *CategoriesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/impactCategories/{impactCategoryName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if impactCategoryName == "" { + return nil, errors.New("parameter impactCategoryName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{impactCategoryName}", url.PathEscape(impactCategoryName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CategoriesClient) getHandleResponse(resp *http.Response) (CategoriesClientGetResponse, error) { + result := CategoriesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Category); err != nil { + return CategoriesClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List ImpactCategory resources by subscription +// +// Generated from API version 2024-05-01-preview +// - options - CategoriesClientListBySubscriptionOptions contains the optional parameters for the CategoriesClient.NewListBySubscriptionPager +// method. +func (client *CategoriesClient) NewListBySubscriptionPager(options *CategoriesClientListBySubscriptionOptions) *runtime.Pager[CategoriesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CategoriesClientListBySubscriptionResponse]{ + More: func(page CategoriesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CategoriesClientListBySubscriptionResponse) (CategoriesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CategoriesClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CategoriesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CategoriesClient) listBySubscriptionCreateRequest(ctx context.Context, options *CategoriesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/impactCategories" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + if options != nil && options.CategoryName != nil { + reqQP.Set("categoryName", *options.CategoryName) + } + if options != nil && options.ResourceType != nil { + reqQP.Set("resourceType", *options.ResourceType) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CategoriesClient) listBySubscriptionHandleResponse(resp *http.Response) (CategoriesClientListBySubscriptionResponse, error) { + result := CategoriesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CategoryListResult); err != nil { + return CategoriesClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/ci.yml b/sdk/resourcemanager/impact/armimpact/ci.yml new file mode 100644 index 000000000000..73bb496eed7d --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/ci.yml @@ -0,0 +1,28 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/impact/armimpact/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/impact/armimpact/ + +extends: + template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + IncludeRelease: true + ServiceDirectory: 'resourcemanager/impact/armimpact' diff --git a/sdk/resourcemanager/impact/armimpact/client_factory.go b/sdk/resourcemanager/impact/armimpact/client_factory.go new file mode 100644 index 000000000000..a221e9357b1d --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/client_factory.go @@ -0,0 +1,76 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewCategoriesClient creates a new instance of CategoriesClient. +func (c *ClientFactory) NewCategoriesClient() *CategoriesClient { + return &CategoriesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewConnectorsClient creates a new instance of ConnectorsClient. +func (c *ClientFactory) NewConnectorsClient() *ConnectorsClient { + return &ConnectorsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewInsightsClient creates a new instance of InsightsClient. +func (c *ClientFactory) NewInsightsClient() *InsightsClient { + return &InsightsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewWorkloadImpactsClient creates a new instance of WorkloadImpactsClient. +func (c *ClientFactory) NewWorkloadImpactsClient() *WorkloadImpactsClient { + return &WorkloadImpactsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/sdk/resourcemanager/impact/armimpact/connectors_client.go b/sdk/resourcemanager/impact/armimpact/connectors_client.go new file mode 100644 index 000000000000..1af37f643443 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/connectors_client.go @@ -0,0 +1,346 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ConnectorsClient contains the methods for the Connectors group. +// Don't use this type directly, use NewConnectorsClient() instead. +type ConnectorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConnectorsClient creates a new instance of ConnectorsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewConnectorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConnectorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConnectorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a Connector +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - connectorName - The name of the connector +// - resource - Resource create parameters. +// - options - ConnectorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConnectorsClient.BeginCreateOrUpdate +// method. +func (client *ConnectorsClient) BeginCreateOrUpdate(ctx context.Context, connectorName string, resource Connector, options *ConnectorsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ConnectorsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, connectorName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConnectorsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConnectorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Connector +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +func (client *ConnectorsClient) createOrUpdate(ctx context.Context, connectorName string, resource Connector, options *ConnectorsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ConnectorsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, connectorName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ConnectorsClient) createOrUpdateCreateRequest(ctx context.Context, connectorName string, resource Connector, options *ConnectorsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if connectorName == "" { + return nil, errors.New("parameter connectorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectorName}", url.PathEscape(connectorName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a Connector +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - connectorName - The name of the connector +// - options - ConnectorsClientDeleteOptions contains the optional parameters for the ConnectorsClient.Delete method. +func (client *ConnectorsClient) Delete(ctx context.Context, connectorName string, options *ConnectorsClientDeleteOptions) (ConnectorsClientDeleteResponse, error) { + var err error + const operationName = "ConnectorsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, connectorName, options) + if err != nil { + return ConnectorsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectorsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConnectorsClientDeleteResponse{}, err + } + return ConnectorsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ConnectorsClient) deleteCreateRequest(ctx context.Context, connectorName string, options *ConnectorsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if connectorName == "" { + return nil, errors.New("parameter connectorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectorName}", url.PathEscape(connectorName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a Connector +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - connectorName - The name of the connector +// - options - ConnectorsClientGetOptions contains the optional parameters for the ConnectorsClient.Get method. +func (client *ConnectorsClient) Get(ctx context.Context, connectorName string, options *ConnectorsClientGetOptions) (ConnectorsClientGetResponse, error) { + var err error + const operationName = "ConnectorsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, connectorName, options) + if err != nil { + return ConnectorsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectorsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConnectorsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ConnectorsClient) getCreateRequest(ctx context.Context, connectorName string, options *ConnectorsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if connectorName == "" { + return nil, errors.New("parameter connectorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectorName}", url.PathEscape(connectorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ConnectorsClient) getHandleResponse(resp *http.Response) (ConnectorsClientGetResponse, error) { + result := ConnectorsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Connector); err != nil { + return ConnectorsClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List Connector resources by subscription ID +// +// Generated from API version 2024-05-01-preview +// - options - ConnectorsClientListBySubscriptionOptions contains the optional parameters for the ConnectorsClient.NewListBySubscriptionPager +// method. +func (client *ConnectorsClient) NewListBySubscriptionPager(options *ConnectorsClientListBySubscriptionOptions) *runtime.Pager[ConnectorsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ConnectorsClientListBySubscriptionResponse]{ + More: func(page ConnectorsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConnectorsClientListBySubscriptionResponse) (ConnectorsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConnectorsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ConnectorsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ConnectorsClient) listBySubscriptionCreateRequest(ctx context.Context, options *ConnectorsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ConnectorsClient) listBySubscriptionHandleResponse(resp *http.Response) (ConnectorsClientListBySubscriptionResponse, error) { + result := ConnectorsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectorListResult); err != nil { + return ConnectorsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Update a Connector +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - connectorName - The name of the connector +// - properties - The resource properties to be updated. +// - options - ConnectorsClientUpdateOptions contains the optional parameters for the ConnectorsClient.Update method. +func (client *ConnectorsClient) Update(ctx context.Context, connectorName string, properties ConnectorUpdate, options *ConnectorsClientUpdateOptions) (ConnectorsClientUpdateResponse, error) { + var err error + const operationName = "ConnectorsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, connectorName, properties, options) + if err != nil { + return ConnectorsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConnectorsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConnectorsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ConnectorsClient) updateCreateRequest(ctx context.Context, connectorName string, properties ConnectorUpdate, options *ConnectorsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/connectors/{connectorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if connectorName == "" { + return nil, errors.New("parameter connectorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectorName}", url.PathEscape(connectorName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ConnectorsClient) updateHandleResponse(resp *http.Response) (ConnectorsClientUpdateResponse, error) { + result := ConnectorsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Connector); err != nil { + return ConnectorsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/constants.go b/sdk/resourcemanager/impact/armimpact/constants.go new file mode 100644 index 000000000000..55c3dd13425d --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/constants.go @@ -0,0 +1,274 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +const ( + moduleName = "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + moduleVersion = "v0.1.0" +) + +// ActionType - Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// ConfidenceLevel - Degree of confidence on the impact being a platform issue. +type ConfidenceLevel string + +const ( + // ConfidenceLevelHigh - High confidence on azure being the source of impact + ConfidenceLevelHigh ConfidenceLevel = "High" + // ConfidenceLevelLow - Low confidence on azure being the source of impact + ConfidenceLevelLow ConfidenceLevel = "Low" + // ConfidenceLevelMedium - Medium confidence on azure being the source of impact + ConfidenceLevelMedium ConfidenceLevel = "Medium" +) + +// PossibleConfidenceLevelValues returns the possible values for the ConfidenceLevel const type. +func PossibleConfidenceLevelValues() []ConfidenceLevel { + return []ConfidenceLevel{ + ConfidenceLevelHigh, + ConfidenceLevelLow, + ConfidenceLevelMedium, + } +} + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// IncidentSource - List of incident interfaces. +type IncidentSource string + +const ( + // IncidentSourceAzureDevops - When source of Incident is AzureDevops + IncidentSourceAzureDevops IncidentSource = "AzureDevops" + // IncidentSourceICM - When source of Incident is Microsoft ICM + IncidentSourceICM IncidentSource = "ICM" + // IncidentSourceJira - When source of Incident is Jira + IncidentSourceJira IncidentSource = "Jira" + // IncidentSourceOther - When source of Incident is Other + IncidentSourceOther IncidentSource = "Other" + // IncidentSourceServiceNow - When source of Incident is ServiceNow + IncidentSourceServiceNow IncidentSource = "ServiceNow" +) + +// PossibleIncidentSourceValues returns the possible values for the IncidentSource const type. +func PossibleIncidentSourceValues() []IncidentSource { + return []IncidentSource{ + IncidentSourceAzureDevops, + IncidentSourceICM, + IncidentSourceJira, + IncidentSourceOther, + IncidentSourceServiceNow, + } +} + +// MetricUnit - List of unit of the metric. +type MetricUnit string + +const ( + // MetricUnitByteSeconds - When measurement is in ByteSeconds + MetricUnitByteSeconds MetricUnit = "ByteSeconds" + // MetricUnitBytes - When measurement is in Bytes + MetricUnitBytes MetricUnit = "Bytes" + // MetricUnitBytesPerSecond - When measurement is in BytesPerSecond + MetricUnitBytesPerSecond MetricUnit = "BytesPerSecond" + // MetricUnitCores - When measurement is in Cores + MetricUnitCores MetricUnit = "Cores" + // MetricUnitCount - When measurement is in Count + MetricUnitCount MetricUnit = "Count" + // MetricUnitCountPerSecond - When measurement is in CountPerSecond + MetricUnitCountPerSecond MetricUnit = "CountPerSecond" + // MetricUnitMilliCores - When measurement is in MilliCores + MetricUnitMilliCores MetricUnit = "MilliCores" + // MetricUnitMilliSeconds - When measurement is in MilliSeconds + MetricUnitMilliSeconds MetricUnit = "MilliSeconds" + // MetricUnitNanoCores - When measurement is in NanoCores + MetricUnitNanoCores MetricUnit = "NanoCores" + // MetricUnitOther - When measurement is in Other than listed + MetricUnitOther MetricUnit = "Other" + // MetricUnitPercent - When measurement is in Percent + MetricUnitPercent MetricUnit = "Percent" + // MetricUnitSeconds - When measurement is in Seconds + MetricUnitSeconds MetricUnit = "Seconds" +) + +// PossibleMetricUnitValues returns the possible values for the MetricUnit const type. +func PossibleMetricUnitValues() []MetricUnit { + return []MetricUnit{ + MetricUnitByteSeconds, + MetricUnitBytes, + MetricUnitBytesPerSecond, + MetricUnitCores, + MetricUnitCount, + MetricUnitCountPerSecond, + MetricUnitMilliCores, + MetricUnitMilliSeconds, + MetricUnitNanoCores, + MetricUnitOther, + MetricUnitPercent, + MetricUnitSeconds, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + OriginSystem Origin = "system" + OriginUser Origin = "user" + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// Platform - Enum for connector types +type Platform string + +const ( + // PlatformAzureMonitor - Type of Azure Monitor + PlatformAzureMonitor Platform = "AzureMonitor" +) + +// PossiblePlatformValues returns the possible values for the Platform const type. +func PossiblePlatformValues() []Platform { + return []Platform{ + PlatformAzureMonitor, + } +} + +// Protocol - List of protocols +type Protocol string + +const ( + // ProtocolFTP - When communication protocol is FTP + ProtocolFTP Protocol = "FTP" + // ProtocolHTTP - When communication protocol is HTTP + ProtocolHTTP Protocol = "HTTP" + // ProtocolHTTPS - When communication protocol is HTTPS + ProtocolHTTPS Protocol = "HTTPS" + // ProtocolOther - When communication protocol is Other + ProtocolOther Protocol = "Other" + // ProtocolRDP - When communication protocol is RDP + ProtocolRDP Protocol = "RDP" + // ProtocolSSH - When communication protocol is SSH + ProtocolSSH Protocol = "SSH" + // ProtocolTCP - When communication protocol is TCP + ProtocolTCP Protocol = "TCP" + // ProtocolUDP - When communication protocol is UDP + ProtocolUDP Protocol = "UDP" +) + +// PossibleProtocolValues returns the possible values for the Protocol const type. +func PossibleProtocolValues() []Protocol { + return []Protocol{ + ProtocolFTP, + ProtocolHTTP, + ProtocolHTTPS, + ProtocolOther, + ProtocolRDP, + ProtocolSSH, + ProtocolTCP, + ProtocolUDP, + } +} + +// ProvisioningState - Provisioning state of the resource. +type ProvisioningState string + +const ( + // ProvisioningStateCanceled - Provisioning Canceled + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateFailed - Provisioning Failed + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Provisioning Succeeded + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + } +} + +// Toolset - List of azure interfaces. +type Toolset string + +const ( + // ToolsetARM - If communication toolset is ARM + ToolsetARM Toolset = "ARM" + // ToolsetAnsible - If communication toolset is Ansible + ToolsetAnsible Toolset = "Ansible" + // ToolsetChef - If communication toolset is Chef + ToolsetChef Toolset = "Chef" + // ToolsetOther - If communication toolset is Other + ToolsetOther Toolset = "Other" + // ToolsetPortal - If communication toolset is Portal + ToolsetPortal Toolset = "Portal" + // ToolsetPuppet - If communication toolset is Puppet + ToolsetPuppet Toolset = "Puppet" + // ToolsetSDK - If communication toolset is SDK + ToolsetSDK Toolset = "SDK" + // ToolsetShell - If communication toolset is Shell + ToolsetShell Toolset = "Shell" + // ToolsetTerraform - If communication toolset is Terraform + ToolsetTerraform Toolset = "Terraform" +) + +// PossibleToolsetValues returns the possible values for the Toolset const type. +func PossibleToolsetValues() []Toolset { + return []Toolset{ + ToolsetARM, + ToolsetAnsible, + ToolsetChef, + ToolsetOther, + ToolsetPortal, + ToolsetPuppet, + ToolsetSDK, + ToolsetShell, + ToolsetTerraform, + } +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/categories_server.go b/sdk/resourcemanager/impact/armimpact/fake/categories_server.go new file mode 100644 index 000000000000..cda20703fa9f --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/categories_server.go @@ -0,0 +1,158 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + "net/http" + "net/url" + "regexp" +) + +// CategoriesServer is a fake server for instances of the armimpact.CategoriesClient type. +type CategoriesServer struct { + // Get is the fake for method CategoriesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, impactCategoryName string, options *armimpact.CategoriesClientGetOptions) (resp azfake.Responder[armimpact.CategoriesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method CategoriesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armimpact.CategoriesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armimpact.CategoriesClientListBySubscriptionResponse]) +} + +// NewCategoriesServerTransport creates a new instance of CategoriesServerTransport with the provided implementation. +// The returned CategoriesServerTransport instance is connected to an instance of armimpact.CategoriesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCategoriesServerTransport(srv *CategoriesServer) *CategoriesServerTransport { + return &CategoriesServerTransport{ + srv: srv, + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armimpact.CategoriesClientListBySubscriptionResponse]](), + } +} + +// CategoriesServerTransport connects instances of armimpact.CategoriesClient to instances of CategoriesServer. +// Don't use this type directly, use NewCategoriesServerTransport instead. +type CategoriesServerTransport struct { + srv *CategoriesServer + newListBySubscriptionPager *tracker[azfake.PagerResponder[armimpact.CategoriesClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for CategoriesServerTransport. +func (c *CategoriesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "CategoriesClient.Get": + resp, err = c.dispatchGet(req) + case "CategoriesClient.NewListBySubscriptionPager": + resp, err = c.dispatchNewListBySubscriptionPager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (c *CategoriesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/impactCategories/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + impactCategoryNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("impactCategoryName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), impactCategoryNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Category, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CategoriesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/impactCategories` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + categoryNameUnescaped, err := url.QueryUnescape(qp.Get("categoryName")) + if err != nil { + return nil, err + } + categoryNameParam := getOptional(categoryNameUnescaped) + resourceTypeUnescaped, err := url.QueryUnescape(qp.Get("resourceType")) + if err != nil { + return nil, err + } + resourceTypeParam := getOptional(resourceTypeUnescaped) + var options *armimpact.CategoriesClientListBySubscriptionOptions + if categoryNameParam != nil || resourceTypeParam != nil { + options = &armimpact.CategoriesClientListBySubscriptionOptions{ + CategoryName: categoryNameParam, + ResourceType: resourceTypeParam, + } + } + resp := c.srv.NewListBySubscriptionPager(options) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armimpact.CategoriesClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/connectors_server.go b/sdk/resourcemanager/impact/armimpact/fake/connectors_server.go new file mode 100644 index 000000000000..35e9720f1ff8 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/connectors_server.go @@ -0,0 +1,266 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + "net/http" + "net/url" + "regexp" +) + +// ConnectorsServer is a fake server for instances of the armimpact.ConnectorsClient type. +type ConnectorsServer struct { + // BeginCreateOrUpdate is the fake for method ConnectorsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, connectorName string, resource armimpact.Connector, options *armimpact.ConnectorsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armimpact.ConnectorsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ConnectorsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, connectorName string, options *armimpact.ConnectorsClientDeleteOptions) (resp azfake.Responder[armimpact.ConnectorsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ConnectorsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, connectorName string, options *armimpact.ConnectorsClientGetOptions) (resp azfake.Responder[armimpact.ConnectorsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method ConnectorsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armimpact.ConnectorsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armimpact.ConnectorsClientListBySubscriptionResponse]) + + // Update is the fake for method ConnectorsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, connectorName string, properties armimpact.ConnectorUpdate, options *armimpact.ConnectorsClientUpdateOptions) (resp azfake.Responder[armimpact.ConnectorsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewConnectorsServerTransport creates a new instance of ConnectorsServerTransport with the provided implementation. +// The returned ConnectorsServerTransport instance is connected to an instance of armimpact.ConnectorsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewConnectorsServerTransport(srv *ConnectorsServer) *ConnectorsServerTransport { + return &ConnectorsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armimpact.ConnectorsClientCreateOrUpdateResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armimpact.ConnectorsClientListBySubscriptionResponse]](), + } +} + +// ConnectorsServerTransport connects instances of armimpact.ConnectorsClient to instances of ConnectorsServer. +// Don't use this type directly, use NewConnectorsServerTransport instead. +type ConnectorsServerTransport struct { + srv *ConnectorsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armimpact.ConnectorsClientCreateOrUpdateResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armimpact.ConnectorsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for ConnectorsServerTransport. +func (c *ConnectorsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "ConnectorsClient.BeginCreateOrUpdate": + resp, err = c.dispatchBeginCreateOrUpdate(req) + case "ConnectorsClient.Delete": + resp, err = c.dispatchDelete(req) + case "ConnectorsClient.Get": + resp, err = c.dispatchGet(req) + case "ConnectorsClient.NewListBySubscriptionPager": + resp, err = c.dispatchNewListBySubscriptionPager(req) + case "ConnectorsClient.Update": + resp, err = c.dispatchUpdate(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (c *ConnectorsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := c.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/connectors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armimpact.Connector](req) + if err != nil { + return nil, err + } + connectorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdate(req.Context(), connectorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + c.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + c.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (c *ConnectorsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if c.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/connectors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + connectorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Delete(req.Context(), connectorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConnectorsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/connectors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + connectorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), connectorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Connector, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConnectorsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/connectors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armimpact.ConnectorsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *ConnectorsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if c.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/connectors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armimpact.ConnectorUpdate](req) + if err != nil { + return nil, err + } + connectorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Update(req.Context(), connectorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Connector, req) + if err != nil { + return nil, err + } + return resp, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/insights_server.go b/sdk/resourcemanager/impact/armimpact/fake/insights_server.go new file mode 100644 index 000000000000..162ac9750657 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/insights_server.go @@ -0,0 +1,230 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + "net/http" + "net/url" + "regexp" +) + +// InsightsServer is a fake server for instances of the armimpact.InsightsClient type. +type InsightsServer struct { + // Create is the fake for method InsightsClient.Create + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Create func(ctx context.Context, workloadImpactName string, insightName string, resource armimpact.Insight, options *armimpact.InsightsClientCreateOptions) (resp azfake.Responder[armimpact.InsightsClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method InsightsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, workloadImpactName string, insightName string, options *armimpact.InsightsClientDeleteOptions) (resp azfake.Responder[armimpact.InsightsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method InsightsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, workloadImpactName string, insightName string, options *armimpact.InsightsClientGetOptions) (resp azfake.Responder[armimpact.InsightsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method InsightsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(workloadImpactName string, options *armimpact.InsightsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armimpact.InsightsClientListBySubscriptionResponse]) +} + +// NewInsightsServerTransport creates a new instance of InsightsServerTransport with the provided implementation. +// The returned InsightsServerTransport instance is connected to an instance of armimpact.InsightsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewInsightsServerTransport(srv *InsightsServer) *InsightsServerTransport { + return &InsightsServerTransport{ + srv: srv, + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armimpact.InsightsClientListBySubscriptionResponse]](), + } +} + +// InsightsServerTransport connects instances of armimpact.InsightsClient to instances of InsightsServer. +// Don't use this type directly, use NewInsightsServerTransport instead. +type InsightsServerTransport struct { + srv *InsightsServer + newListBySubscriptionPager *tracker[azfake.PagerResponder[armimpact.InsightsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for InsightsServerTransport. +func (i *InsightsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "InsightsClient.Create": + resp, err = i.dispatchCreate(req) + case "InsightsClient.Delete": + resp, err = i.dispatchDelete(req) + case "InsightsClient.Get": + resp, err = i.dispatchGet(req) + case "InsightsClient.NewListBySubscriptionPager": + resp, err = i.dispatchNewListBySubscriptionPager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (i *InsightsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if i.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/insights/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armimpact.Insight](req) + if err != nil { + return nil, err + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + insightNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("insightName")]) + if err != nil { + return nil, err + } + respr, errRespr := i.srv.Create(req.Context(), workloadImpactNameParam, insightNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Insight, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *InsightsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if i.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/insights/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + insightNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("insightName")]) + if err != nil { + return nil, err + } + respr, errRespr := i.srv.Delete(req.Context(), workloadImpactNameParam, insightNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *InsightsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if i.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/insights/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + insightNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("insightName")]) + if err != nil { + return nil, err + } + respr, errRespr := i.srv.Get(req.Context(), workloadImpactNameParam, insightNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Insight, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *InsightsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if i.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := i.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/insights` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + resp := i.srv.NewListBySubscriptionPager(workloadImpactNameParam, nil) + newListBySubscriptionPager = &resp + i.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armimpact.InsightsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + i.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + i.newListBySubscriptionPager.remove(req) + } + return resp, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/internal.go b/sdk/resourcemanager/impact/armimpact/fake/internal.go new file mode 100644 index 000000000000..94e060e89dbd --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/internal.go @@ -0,0 +1,72 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func contains[T comparable](s []T, v T) bool { + for _, vv := range s { + if vv == v { + return true + } + } + return false +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/operations_server.go b/sdk/resourcemanager/impact/armimpact/fake/operations_server.go new file mode 100644 index 000000000000..3c58130d15d9 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/operations_server.go @@ -0,0 +1,96 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + "net/http" +) + +// OperationsServer is a fake server for instances of the armimpact.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armimpact.OperationsClientListOptions) (resp azfake.PagerResponder[armimpact.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armimpact.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armimpact.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armimpact.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armimpact.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "OperationsClient.NewListPager": + resp, err = o.dispatchNewListPager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armimpact.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/server_factory.go b/sdk/resourcemanager/impact/armimpact/fake/server_factory.go new file mode 100644 index 000000000000..b35f969c3dc3 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/server_factory.go @@ -0,0 +1,97 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armimpact.ClientFactory type. +type ServerFactory struct { + CategoriesServer CategoriesServer + ConnectorsServer ConnectorsServer + InsightsServer InsightsServer + OperationsServer OperationsServer + WorkloadImpactsServer WorkloadImpactsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armimpact.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armimpact.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trCategoriesServer *CategoriesServerTransport + trConnectorsServer *ConnectorsServerTransport + trInsightsServer *InsightsServerTransport + trOperationsServer *OperationsServerTransport + trWorkloadImpactsServer *WorkloadImpactsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "CategoriesClient": + initServer(s, &s.trCategoriesServer, func() *CategoriesServerTransport { return NewCategoriesServerTransport(&s.srv.CategoriesServer) }) + resp, err = s.trCategoriesServer.Do(req) + case "ConnectorsClient": + initServer(s, &s.trConnectorsServer, func() *ConnectorsServerTransport { return NewConnectorsServerTransport(&s.srv.ConnectorsServer) }) + resp, err = s.trConnectorsServer.Do(req) + case "InsightsClient": + initServer(s, &s.trInsightsServer, func() *InsightsServerTransport { return NewInsightsServerTransport(&s.srv.InsightsServer) }) + resp, err = s.trInsightsServer.Do(req) + case "OperationsClient": + initServer(s, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "WorkloadImpactsClient": + initServer(s, &s.trWorkloadImpactsServer, func() *WorkloadImpactsServerTransport { + return NewWorkloadImpactsServerTransport(&s.srv.WorkloadImpactsServer) + }) + resp, err = s.trWorkloadImpactsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func initServer[T any](s *ServerFactoryTransport, dst **T, src func() *T) { + s.trMu.Lock() + if *dst == nil { + *dst = src() + } + s.trMu.Unlock() +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/time_rfc3339.go b/sdk/resourcemanager/impact/armimpact/fake/time_rfc3339.go new file mode 100644 index 000000000000..81f308b0d343 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/time_rfc3339.go @@ -0,0 +1,110 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) + +const ( + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` +) + +type dateTimeRFC3339 time.Time + +func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t dateTimeRFC3339) MarshalText() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = dateTimeRFC3339(p) + return err +} + +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + +func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*dateTimeRFC3339)(t) +} + +func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux dateTimeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/sdk/resourcemanager/impact/armimpact/fake/workloadimpacts_server.go b/sdk/resourcemanager/impact/armimpact/fake/workloadimpacts_server.go new file mode 100644 index 000000000000..983244eac8ed --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/fake/workloadimpacts_server.go @@ -0,0 +1,227 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact" + "net/http" + "net/url" + "regexp" +) + +// WorkloadImpactsServer is a fake server for instances of the armimpact.WorkloadImpactsClient type. +type WorkloadImpactsServer struct { + // BeginCreate is the fake for method WorkloadImpactsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, workloadImpactName string, resource armimpact.WorkloadImpact, options *armimpact.WorkloadImpactsClientBeginCreateOptions) (resp azfake.PollerResponder[armimpact.WorkloadImpactsClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method WorkloadImpactsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, workloadImpactName string, options *armimpact.WorkloadImpactsClientDeleteOptions) (resp azfake.Responder[armimpact.WorkloadImpactsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method WorkloadImpactsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, workloadImpactName string, options *armimpact.WorkloadImpactsClientGetOptions) (resp azfake.Responder[armimpact.WorkloadImpactsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method WorkloadImpactsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armimpact.WorkloadImpactsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armimpact.WorkloadImpactsClientListBySubscriptionResponse]) +} + +// NewWorkloadImpactsServerTransport creates a new instance of WorkloadImpactsServerTransport with the provided implementation. +// The returned WorkloadImpactsServerTransport instance is connected to an instance of armimpact.WorkloadImpactsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWorkloadImpactsServerTransport(srv *WorkloadImpactsServer) *WorkloadImpactsServerTransport { + return &WorkloadImpactsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armimpact.WorkloadImpactsClientCreateResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armimpact.WorkloadImpactsClientListBySubscriptionResponse]](), + } +} + +// WorkloadImpactsServerTransport connects instances of armimpact.WorkloadImpactsClient to instances of WorkloadImpactsServer. +// Don't use this type directly, use NewWorkloadImpactsServerTransport instead. +type WorkloadImpactsServerTransport struct { + srv *WorkloadImpactsServer + beginCreate *tracker[azfake.PollerResponder[armimpact.WorkloadImpactsClientCreateResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armimpact.WorkloadImpactsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for WorkloadImpactsServerTransport. +func (w *WorkloadImpactsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + var resp *http.Response + var err error + + switch method { + case "WorkloadImpactsClient.BeginCreate": + resp, err = w.dispatchBeginCreate(req) + case "WorkloadImpactsClient.Delete": + resp, err = w.dispatchDelete(req) + case "WorkloadImpactsClient.Get": + resp, err = w.dispatchGet(req) + case "WorkloadImpactsClient.NewListBySubscriptionPager": + resp, err = w.dispatchNewListBySubscriptionPager(req) + default: + err = fmt.Errorf("unhandled API %s", method) + } + + if err != nil { + return nil, err + } + + return resp, nil +} + +func (w *WorkloadImpactsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if w.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := w.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armimpact.WorkloadImpact](req) + if err != nil { + return nil, err + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginCreate(req.Context(), workloadImpactNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + w.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + w.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + w.beginCreate.remove(req) + } + + return resp, nil +} + +func (w *WorkloadImpactsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if w.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Delete(req.Context(), workloadImpactNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WorkloadImpactsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if w.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + workloadImpactNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workloadImpactName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Get(req.Context(), workloadImpactNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).WorkloadImpact, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WorkloadImpactsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := w.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Impact/workloadImpacts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if matches == nil || len(matches) < 1 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := w.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + w.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armimpact.WorkloadImpactsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + w.newListBySubscriptionPager.remove(req) + } + return resp, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/go.mod b/sdk/resourcemanager/impact/armimpact/go.mod new file mode 100644 index 000000000000..7620a509a180 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/go.mod @@ -0,0 +1,11 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/impact/armimpact + +go 1.18 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 // indirect + golang.org/x/net v0.20.0 // indirect + golang.org/x/text v0.14.0 // indirect +) diff --git a/sdk/resourcemanager/impact/armimpact/go.sum b/sdk/resourcemanager/impact/armimpact/go.sum new file mode 100644 index 000000000000..03ce617a1873 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/go.sum @@ -0,0 +1,12 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2 h1:c4k2FIYIh4xtwqrQwV0Ct1v5+ehlNXj5NI/MWVsiTkQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.9.2/go.mod h1:5FDJtLEO/GxwNgUxbwrY3LP0pEoThTQJtk2oysdXHxM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2 h1:LqbJ/WzJUwBf8UiaSzgX7aMclParm9/5Vgp+TY51uBQ= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.5.2/go.mod h1:yInRyqWXAuaPrgI7p70+lDDgh3mlBohis29jGMISnmc= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/sdk/resourcemanager/impact/armimpact/insights_client.go b/sdk/resourcemanager/impact/armimpact/insights_client.go new file mode 100644 index 000000000000..2ed8df7ab839 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/insights_client.go @@ -0,0 +1,290 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// InsightsClient contains the methods for the Insights group. +// Don't use this type directly, use NewInsightsClient() instead. +type InsightsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewInsightsClient creates a new instance of InsightsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewInsightsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*InsightsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &InsightsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Create Insight resource, This is Admin only operation +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - insightName - Name of the insight +// - resource - Resource create parameters. +// - options - InsightsClientCreateOptions contains the optional parameters for the InsightsClient.Create method. +func (client *InsightsClient) Create(ctx context.Context, workloadImpactName string, insightName string, resource Insight, options *InsightsClientCreateOptions) (InsightsClientCreateResponse, error) { + var err error + const operationName = "InsightsClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, workloadImpactName, insightName, resource, options) + if err != nil { + return InsightsClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InsightsClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return InsightsClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *InsightsClient) createCreateRequest(ctx context.Context, workloadImpactName string, insightName string, resource Insight, options *InsightsClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + if insightName == "" { + return nil, errors.New("parameter insightName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{insightName}", url.PathEscape(insightName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *InsightsClient) createHandleResponse(resp *http.Response) (InsightsClientCreateResponse, error) { + result := InsightsClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Insight); err != nil { + return InsightsClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Delete Insight resource, This is Admin only operation +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - insightName - Name of the insight +// - options - InsightsClientDeleteOptions contains the optional parameters for the InsightsClient.Delete method. +func (client *InsightsClient) Delete(ctx context.Context, workloadImpactName string, insightName string, options *InsightsClientDeleteOptions) (InsightsClientDeleteResponse, error) { + var err error + const operationName = "InsightsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, workloadImpactName, insightName, options) + if err != nil { + return InsightsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InsightsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return InsightsClientDeleteResponse{}, err + } + return InsightsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *InsightsClient) deleteCreateRequest(ctx context.Context, workloadImpactName string, insightName string, options *InsightsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + if insightName == "" { + return nil, errors.New("parameter insightName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{insightName}", url.PathEscape(insightName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get Insight resources by workloadImpactName and insightName +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - insightName - Name of the insight +// - options - InsightsClientGetOptions contains the optional parameters for the InsightsClient.Get method. +func (client *InsightsClient) Get(ctx context.Context, workloadImpactName string, insightName string, options *InsightsClientGetOptions) (InsightsClientGetResponse, error) { + var err error + const operationName = "InsightsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, workloadImpactName, insightName, options) + if err != nil { + return InsightsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return InsightsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return InsightsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *InsightsClient) getCreateRequest(ctx context.Context, workloadImpactName string, insightName string, options *InsightsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights/{insightName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + if insightName == "" { + return nil, errors.New("parameter insightName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{insightName}", url.PathEscape(insightName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *InsightsClient) getHandleResponse(resp *http.Response) (InsightsClientGetResponse, error) { + result := InsightsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Insight); err != nil { + return InsightsClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List Insight resources by workloadImpactName +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - options - InsightsClientListBySubscriptionOptions contains the optional parameters for the InsightsClient.NewListBySubscriptionPager +// method. +func (client *InsightsClient) NewListBySubscriptionPager(workloadImpactName string, options *InsightsClientListBySubscriptionOptions) *runtime.Pager[InsightsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[InsightsClientListBySubscriptionResponse]{ + More: func(page InsightsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *InsightsClientListBySubscriptionResponse) (InsightsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "InsightsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, workloadImpactName, options) + }, nil) + if err != nil { + return InsightsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *InsightsClient) listBySubscriptionCreateRequest(ctx context.Context, workloadImpactName string, options *InsightsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}/insights" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *InsightsClient) listBySubscriptionHandleResponse(resp *http.Response) (InsightsClientListBySubscriptionResponse, error) { + result := InsightsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InsightListResult); err != nil { + return InsightsClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/models.go b/sdk/resourcemanager/impact/armimpact/models.go new file mode 100644 index 000000000000..076e3418e475 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/models.go @@ -0,0 +1,451 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import "time" + +// Category - ImpactCategory resource +type Category struct { + // The resource-specific properties for this resource. + Properties *CategoryProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CategoryListResult - The response of a ImpactCategory list operation. +type CategoryListResult struct { + // REQUIRED; The ImpactCategory items on this page + Value []*Category + + // The link to the next page of items + NextLink *string +} + +// CategoryProperties - Impact category properties. +type CategoryProperties struct { + // REQUIRED; Unique ID of the category + CategoryID *string + + // Description of the category + Description *string + + // Unique ID of the parent category + ParentCategoryID *string + + // The workloadImpact properties which are required when reporting with the impact category + RequiredImpactProperties []*RequiredImpactProperties + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ProvisioningState +} + +// ClientIncidentDetails - Client incident details ex: incidentId , incident source +type ClientIncidentDetails struct { + // Client incident id. ex : id of the incident created to investigate and address the impact if any. + ClientIncidentID *string + + // Client incident source. ex : source system name where the incident is created + ClientIncidentSource *IncidentSource +} + +// Connectivity - Details about connectivity issue. Applicable when root resource causing the issue is not identified. For +// example, when a VM is impacted due to a network issue, the impacted resource could be VM or the +// network. In such cases, the connectivity field will have the details about both VM and network. +type Connectivity struct { + // Port number for the connection + Port *int32 + + // Protocol used for the connection + Protocol *Protocol + + // Source from which the connection was attempted + Source *SourceOrTarget + + // target which connection was attempted + Target *SourceOrTarget +} + +// Connector - A connector is a resource that can be used to proactively report impacts against workloads in Azure to Microsoft. +type Connector struct { + // The resource-specific properties for this resource. + Properties *ConnectorProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ConnectorListResult - The response of a Connector list operation. +type ConnectorListResult struct { + // REQUIRED; The Connector items on this page + Value []*Connector + + // The link to the next page of items + NextLink *string +} + +// ConnectorProperties - Details of the Connector. +type ConnectorProperties struct { + // REQUIRED; connector type + ConnectorType *Platform + + // READ-ONLY; unique id of the connector. + ConnectorID *string + + // READ-ONLY; last run time stamp of this connector in UTC time zone + LastRunTimeStamp *time.Time + + // READ-ONLY; tenant id of this connector + TenantID *string + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ProvisioningState +} + +// ConnectorPropertiesUpdate - Details of the Connector. +type ConnectorPropertiesUpdate struct { + // connector type + ConnectorType *Platform +} + +// ConnectorUpdate - A connector is a resource that can be used to proactively report impacts against workloads in Azure to +// Microsoft. +type ConnectorUpdate struct { + // The resource-specific properties for this resource. + Properties *ConnectorPropertiesUpdate + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// Content - Article details of the insight like title, description etc +type Content struct { + // REQUIRED; Description of the insight + Description *string + + // REQUIRED; Title of the insight + Title *string +} + +// Details - details of of the impact for which insight has been generated. +type Details struct { + // REQUIRED; Azure Id of the impact. + ImpactID *string + + // REQUIRED; List of impacted Azure resources. + ImpactedResourceID *string + + // REQUIRED; Time at which impact was started according to reported impact. + StartTime *time.Time + + // Time at which impact was ended according to reported impact. + EndTime *time.Time +} + +// ErrorDetailProperties - ARM error code and error message associated with the impact +type ErrorDetailProperties struct { + // ARM Error code associated with the impact. + ErrorCode *string + + // ARM Error Message associated with the impact + ErrorMessage *string +} + +// ExpectedValueRange - Max and Min Threshold values for the metric +type ExpectedValueRange struct { + // REQUIRED; Max threshold value for the metric + Max *float64 + + // REQUIRED; Min threshold value for the metric + Min *float64 +} + +// Insight resource +type Insight struct { + // The resource-specific properties for this resource. + Properties *InsightProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// InsightListResult - The response of a Insight list operation. +type InsightListResult struct { + // REQUIRED; The Insight items on this page + Value []*Insight + + // The link to the next page of items + NextLink *string +} + +// InsightProperties - Impact category properties. +type InsightProperties struct { + // REQUIRED; category of the insight. + Category *string + + // REQUIRED; Contains title & description for the insight + Content *Content + + // REQUIRED; details of of the impact for which insight has been generated. + Impact *Details + + // REQUIRED; unique id of the insight. + InsightUniqueID *string + + // additional details of the insight. + AdditionalDetails any + + // Identifier of the event that has been correlated with this insight. This can be used to aggregate insights for the same + // event. + EventID *string + + // Time of the event, which has been correlated the impact. + EventTime *time.Time + + // Identifier that can be used to group similar insights. + GroupID *string + + // status of the insight. example resolved, repaired, other. + Status *string + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ProvisioningState +} + +// Operation - Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane + // operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for this particular operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results (if there are any). + NextLink *string + + // READ-ONLY; List of operations supported by the resource provider + Value []*Operation +} + +// Performance - Details about impacted performance metrics. Applicable for performance related impact +type Performance struct { + // Observed value for the metric + Actual *float64 + + // Threshold value for the metric + Expected *float64 + + // Max and Min Threshold values for the metric + ExpectedValueRange *ExpectedValueRange + + // Name of the Metric examples: Disk, IOPs, CPU, GPU, Memory, details can be found from /impactCategories API + MetricName *string + + // Unit of the metric ex: Bytes, Percentage, Count, Seconds, Milliseconds, Bytes/Second, Count/Second, etc.., Other + Unit *MetricUnit +} + +// RequiredImpactProperties - Required impact properties +type RequiredImpactProperties struct { + // REQUIRED; Name of the property + Name *string + + // Allowed values values for the property + AllowedValues []*string +} + +// SourceOrTarget - Resource details +type SourceOrTarget struct { + // Azure resource id, example /subscription/{subscription}/resourceGroup/{rg}/Microsoft.compute/virtualMachine/{vmName} + AzureResourceID *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// Workload - Information about the impacted workload +type Workload struct { + // the scenario for the workload + Context *string + + // Tool used to interact with Azure. SDK, AzPortal, etc.., Other + Toolset *Toolset +} + +// WorkloadImpact - Workload Impact properties +type WorkloadImpact struct { + // The resource-specific properties for this resource. + Properties *WorkloadImpactProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// WorkloadImpactListResult - The response of a WorkloadImpact list operation. +type WorkloadImpactListResult struct { + // REQUIRED; The WorkloadImpact items on this page + Value []*WorkloadImpact + + // The link to the next page of items + NextLink *string +} + +// WorkloadImpactProperties - Workload impact properties +type WorkloadImpactProperties struct { + // REQUIRED; Category of the impact, details can found from /impactCategories API + ImpactCategory *string + + // REQUIRED; Azure resource id of the impacted resource + ImpactedResourceID *string + + // REQUIRED; Time at which impact was observed + StartDateTime *time.Time + + // Additional fields related to impact, applicable fields per resource type are list under /impactCategories API + AdditionalProperties any + + // The ARM correlation ids, this is important field for control plane related impacts + ArmCorrelationIDs []*string + + // Client incident details ex: incidentId , incident source + ClientIncidentDetails *ClientIncidentDetails + + // Degree of confidence on the impact being a platform issue + ConfidenceLevel *ConfidenceLevel + + // Details about connectivity issue. Applicable when root resource causing the issue is not identified. For example, when + // a VM is impacted due to a network issue, the impacted resource is identified as + // the VM, but the root cause is the network. In such cases, the connectivity field will have the details about the network + // issue + Connectivity *Connectivity + + // Time at which impact has ended + EndDateTime *time.Time + + // ARM error code and error message associated with the impact + ErrorDetails *ErrorDetailProperties + + // A detailed description of the impact + ImpactDescription *string + + // Use this field to group impacts + ImpactGroupID *string + + // Details about performance issue. Applicable for performance impacts. + Performance []*Performance + + // Information about the impacted workload + Workload *Workload + + // READ-ONLY; Unique ID of the impact (UUID) + ImpactUniqueID *string + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ProvisioningState + + // READ-ONLY; Time at which impact is reported + ReportedTimeUTC *time.Time +} diff --git a/sdk/resourcemanager/impact/armimpact/models_serde.go b/sdk/resourcemanager/impact/armimpact/models_serde.go new file mode 100644 index 000000000000..35cb65ffd56b --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/models_serde.go @@ -0,0 +1,1146 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Category. +func (c Category) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Category. +func (c *Category) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CategoryListResult. +func (c CategoryListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CategoryListResult. +func (c *CategoryListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CategoryProperties. +func (c CategoryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "categoryId", c.CategoryID) + populate(objectMap, "description", c.Description) + populate(objectMap, "parentCategoryId", c.ParentCategoryID) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "requiredImpactProperties", c.RequiredImpactProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CategoryProperties. +func (c *CategoryProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "categoryId": + err = unpopulate(val, "CategoryID", &c.CategoryID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "parentCategoryId": + err = unpopulate(val, "ParentCategoryID", &c.ParentCategoryID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "requiredImpactProperties": + err = unpopulate(val, "RequiredImpactProperties", &c.RequiredImpactProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ClientIncidentDetails. +func (c ClientIncidentDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientIncidentId", c.ClientIncidentID) + populate(objectMap, "clientIncidentSource", c.ClientIncidentSource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientIncidentDetails. +func (c *ClientIncidentDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientIncidentId": + err = unpopulate(val, "ClientIncidentID", &c.ClientIncidentID) + delete(rawMsg, key) + case "clientIncidentSource": + err = unpopulate(val, "ClientIncidentSource", &c.ClientIncidentSource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Connectivity. +func (c Connectivity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", c.Port) + populate(objectMap, "protocol", c.Protocol) + populate(objectMap, "source", c.Source) + populate(objectMap, "target", c.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Connectivity. +func (c *Connectivity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "port": + err = unpopulate(val, "Port", &c.Port) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &c.Protocol) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &c.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Connector. +func (c Connector) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Connector. +func (c *Connector) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectorListResult. +func (c ConnectorListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectorListResult. +func (c *ConnectorListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectorProperties. +func (c ConnectorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectorId", c.ConnectorID) + populate(objectMap, "connectorType", c.ConnectorType) + populateDateTimeRFC3339(objectMap, "lastRunTimeStamp", c.LastRunTimeStamp) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "tenantId", c.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectorProperties. +func (c *ConnectorProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectorId": + err = unpopulate(val, "ConnectorID", &c.ConnectorID) + delete(rawMsg, key) + case "connectorType": + err = unpopulate(val, "ConnectorType", &c.ConnectorType) + delete(rawMsg, key) + case "lastRunTimeStamp": + err = unpopulateDateTimeRFC3339(val, "LastRunTimeStamp", &c.LastRunTimeStamp) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &c.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectorPropertiesUpdate. +func (c ConnectorPropertiesUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectorType", c.ConnectorType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectorPropertiesUpdate. +func (c *ConnectorPropertiesUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectorType": + err = unpopulate(val, "ConnectorType", &c.ConnectorType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectorUpdate. +func (c ConnectorUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectorUpdate. +func (c *ConnectorUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Content. +func (c Content) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", c.Description) + populate(objectMap, "title", c.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Content. +func (c *Content) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &c.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Details. +func (d Details) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "endTime", d.EndTime) + populate(objectMap, "impactId", d.ImpactID) + populate(objectMap, "impactedResourceId", d.ImpactedResourceID) + populateDateTimeRFC3339(objectMap, "startTime", d.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Details. +func (d *Details) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateDateTimeRFC3339(val, "EndTime", &d.EndTime) + delete(rawMsg, key) + case "impactId": + err = unpopulate(val, "ImpactID", &d.ImpactID) + delete(rawMsg, key) + case "impactedResourceId": + err = unpopulate(val, "ImpactedResourceID", &d.ImpactedResourceID) + delete(rawMsg, key) + case "startTime": + err = unpopulateDateTimeRFC3339(val, "StartTime", &d.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetailProperties. +func (e ErrorDetailProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorCode", e.ErrorCode) + populate(objectMap, "errorMessage", e.ErrorMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetailProperties. +func (e *ErrorDetailProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorCode": + err = unpopulate(val, "ErrorCode", &e.ErrorCode) + delete(rawMsg, key) + case "errorMessage": + err = unpopulate(val, "ErrorMessage", &e.ErrorMessage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExpectedValueRange. +func (e ExpectedValueRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "max", e.Max) + populate(objectMap, "min", e.Min) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExpectedValueRange. +func (e *ExpectedValueRange) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "max": + err = unpopulate(val, "Max", &e.Max) + delete(rawMsg, key) + case "min": + err = unpopulate(val, "Min", &e.Min) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Insight. +func (i Insight) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", i.ID) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "systemData", i.SystemData) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Insight. +func (i *Insight) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &i.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &i.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InsightListResult. +func (i InsightListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InsightListResult. +func (i *InsightListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InsightProperties. +func (i InsightProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "additionalDetails", i.AdditionalDetails) + populate(objectMap, "category", i.Category) + populate(objectMap, "content", i.Content) + populate(objectMap, "eventId", i.EventID) + populateDateTimeRFC3339(objectMap, "eventTime", i.EventTime) + populate(objectMap, "groupId", i.GroupID) + populate(objectMap, "impact", i.Impact) + populate(objectMap, "insightUniqueId", i.InsightUniqueID) + populate(objectMap, "provisioningState", i.ProvisioningState) + populate(objectMap, "status", i.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InsightProperties. +func (i *InsightProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalDetails": + err = unpopulate(val, "AdditionalDetails", &i.AdditionalDetails) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &i.Category) + delete(rawMsg, key) + case "content": + err = unpopulate(val, "Content", &i.Content) + delete(rawMsg, key) + case "eventId": + err = unpopulate(val, "EventID", &i.EventID) + delete(rawMsg, key) + case "eventTime": + err = unpopulateDateTimeRFC3339(val, "EventTime", &i.EventTime) + delete(rawMsg, key) + case "groupId": + err = unpopulate(val, "GroupID", &i.GroupID) + delete(rawMsg, key) + case "impact": + err = unpopulate(val, "Impact", &i.Impact) + delete(rawMsg, key) + case "insightUniqueId": + err = unpopulate(val, "InsightUniqueID", &i.InsightUniqueID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &i.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &i.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Performance. +func (p Performance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actual", p.Actual) + populate(objectMap, "expected", p.Expected) + populate(objectMap, "expectedValueRange", p.ExpectedValueRange) + populate(objectMap, "metricName", p.MetricName) + populate(objectMap, "unit", p.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Performance. +func (p *Performance) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actual": + err = unpopulate(val, "Actual", &p.Actual) + delete(rawMsg, key) + case "expected": + err = unpopulate(val, "Expected", &p.Expected) + delete(rawMsg, key) + case "expectedValueRange": + err = unpopulate(val, "ExpectedValueRange", &p.ExpectedValueRange) + delete(rawMsg, key) + case "metricName": + err = unpopulate(val, "MetricName", &p.MetricName) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &p.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequiredImpactProperties. +func (r RequiredImpactProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowedValues", r.AllowedValues) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequiredImpactProperties. +func (r *RequiredImpactProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowedValues": + err = unpopulate(val, "AllowedValues", &r.AllowedValues) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SourceOrTarget. +func (s SourceOrTarget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureResourceId", s.AzureResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SourceOrTarget. +func (s *SourceOrTarget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureResourceId": + err = unpopulate(val, "AzureResourceID", &s.AzureResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateDateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateDateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateDateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateDateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Workload. +func (w Workload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "context", w.Context) + populate(objectMap, "toolset", w.Toolset) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Workload. +func (w *Workload) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "context": + err = unpopulate(val, "Context", &w.Context) + delete(rawMsg, key) + case "toolset": + err = unpopulate(val, "Toolset", &w.Toolset) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkloadImpact. +func (w WorkloadImpact) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkloadImpact. +func (w *WorkloadImpact) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkloadImpactListResult. +func (w WorkloadImpactListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkloadImpactListResult. +func (w *WorkloadImpactListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &w.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &w.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkloadImpactProperties. +func (w WorkloadImpactProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "additionalProperties", w.AdditionalProperties) + populate(objectMap, "armCorrelationIds", w.ArmCorrelationIDs) + populate(objectMap, "clientIncidentDetails", w.ClientIncidentDetails) + populate(objectMap, "confidenceLevel", w.ConfidenceLevel) + populate(objectMap, "connectivity", w.Connectivity) + populateDateTimeRFC3339(objectMap, "endDateTime", w.EndDateTime) + populate(objectMap, "errorDetails", w.ErrorDetails) + populate(objectMap, "impactCategory", w.ImpactCategory) + populate(objectMap, "impactDescription", w.ImpactDescription) + populate(objectMap, "impactGroupId", w.ImpactGroupID) + populate(objectMap, "impactUniqueId", w.ImpactUniqueID) + populate(objectMap, "impactedResourceId", w.ImpactedResourceID) + populate(objectMap, "performance", w.Performance) + populate(objectMap, "provisioningState", w.ProvisioningState) + populateDateTimeRFC3339(objectMap, "reportedTimeUtc", w.ReportedTimeUTC) + populateDateTimeRFC3339(objectMap, "startDateTime", w.StartDateTime) + populate(objectMap, "workload", w.Workload) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkloadImpactProperties. +func (w *WorkloadImpactProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalProperties": + err = unpopulate(val, "AdditionalProperties", &w.AdditionalProperties) + delete(rawMsg, key) + case "armCorrelationIds": + err = unpopulate(val, "ArmCorrelationIDs", &w.ArmCorrelationIDs) + delete(rawMsg, key) + case "clientIncidentDetails": + err = unpopulate(val, "ClientIncidentDetails", &w.ClientIncidentDetails) + delete(rawMsg, key) + case "confidenceLevel": + err = unpopulate(val, "ConfidenceLevel", &w.ConfidenceLevel) + delete(rawMsg, key) + case "connectivity": + err = unpopulate(val, "Connectivity", &w.Connectivity) + delete(rawMsg, key) + case "endDateTime": + err = unpopulateDateTimeRFC3339(val, "EndDateTime", &w.EndDateTime) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &w.ErrorDetails) + delete(rawMsg, key) + case "impactCategory": + err = unpopulate(val, "ImpactCategory", &w.ImpactCategory) + delete(rawMsg, key) + case "impactDescription": + err = unpopulate(val, "ImpactDescription", &w.ImpactDescription) + delete(rawMsg, key) + case "impactGroupId": + err = unpopulate(val, "ImpactGroupID", &w.ImpactGroupID) + delete(rawMsg, key) + case "impactUniqueId": + err = unpopulate(val, "ImpactUniqueID", &w.ImpactUniqueID) + delete(rawMsg, key) + case "impactedResourceId": + err = unpopulate(val, "ImpactedResourceID", &w.ImpactedResourceID) + delete(rawMsg, key) + case "performance": + err = unpopulate(val, "Performance", &w.Performance) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + case "reportedTimeUtc": + err = unpopulateDateTimeRFC3339(val, "ReportedTimeUTC", &w.ReportedTimeUTC) + delete(rawMsg, key) + case "startDateTime": + err = unpopulateDateTimeRFC3339(val, "StartDateTime", &w.StartDateTime) + delete(rawMsg, key) + case "workload": + err = unpopulate(val, "Workload", &w.Workload) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/sdk/resourcemanager/impact/armimpact/operations_client.go b/sdk/resourcemanager/impact/armimpact/operations_client.go new file mode 100644 index 000000000000..41b7d5c5e5ea --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/operations_client.go @@ -0,0 +1,88 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// +// Generated from API version 2024-05-01-preview +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Impact/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/sdk/resourcemanager/impact/armimpact/options.go b/sdk/resourcemanager/impact/armimpact/options.go new file mode 100644 index 000000000000..6c3d18a95bf3 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/options.go @@ -0,0 +1,100 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +// CategoriesClientGetOptions contains the optional parameters for the CategoriesClient.Get method. +type CategoriesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CategoriesClientListBySubscriptionOptions contains the optional parameters for the CategoriesClient.NewListBySubscriptionPager +// method. +type CategoriesClientListBySubscriptionOptions struct { + // Filter by category name + CategoryName *string + + // Filter by resource type + ResourceType *string +} + +// ConnectorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConnectorsClient.BeginCreateOrUpdate +// method. +type ConnectorsClientBeginCreateOrUpdateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// ConnectorsClientDeleteOptions contains the optional parameters for the ConnectorsClient.Delete method. +type ConnectorsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ConnectorsClientGetOptions contains the optional parameters for the ConnectorsClient.Get method. +type ConnectorsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ConnectorsClientListBySubscriptionOptions contains the optional parameters for the ConnectorsClient.NewListBySubscriptionPager +// method. +type ConnectorsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ConnectorsClientUpdateOptions contains the optional parameters for the ConnectorsClient.Update method. +type ConnectorsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// InsightsClientCreateOptions contains the optional parameters for the InsightsClient.Create method. +type InsightsClientCreateOptions struct { + // placeholder for future optional parameters +} + +// InsightsClientDeleteOptions contains the optional parameters for the InsightsClient.Delete method. +type InsightsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// InsightsClientGetOptions contains the optional parameters for the InsightsClient.Get method. +type InsightsClientGetOptions struct { + // placeholder for future optional parameters +} + +// InsightsClientListBySubscriptionOptions contains the optional parameters for the InsightsClient.NewListBySubscriptionPager +// method. +type InsightsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// WorkloadImpactsClientBeginCreateOptions contains the optional parameters for the WorkloadImpactsClient.BeginCreate method. +type WorkloadImpactsClientBeginCreateOptions struct { + // Resumes the LRO from the provided token. + ResumeToken string +} + +// WorkloadImpactsClientDeleteOptions contains the optional parameters for the WorkloadImpactsClient.Delete method. +type WorkloadImpactsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// WorkloadImpactsClientGetOptions contains the optional parameters for the WorkloadImpactsClient.Get method. +type WorkloadImpactsClientGetOptions struct { + // placeholder for future optional parameters +} + +// WorkloadImpactsClientListBySubscriptionOptions contains the optional parameters for the WorkloadImpactsClient.NewListBySubscriptionPager +// method. +type WorkloadImpactsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} diff --git a/sdk/resourcemanager/impact/armimpact/responses.go b/sdk/resourcemanager/impact/armimpact/responses.go new file mode 100644 index 000000000000..bc4ea0fbbf96 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/responses.go @@ -0,0 +1,102 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +// CategoriesClientGetResponse contains the response from method CategoriesClient.Get. +type CategoriesClientGetResponse struct { + // ImpactCategory resource + Category +} + +// CategoriesClientListBySubscriptionResponse contains the response from method CategoriesClient.NewListBySubscriptionPager. +type CategoriesClientListBySubscriptionResponse struct { + // The response of a ImpactCategory list operation. + CategoryListResult +} + +// ConnectorsClientCreateOrUpdateResponse contains the response from method ConnectorsClient.BeginCreateOrUpdate. +type ConnectorsClientCreateOrUpdateResponse struct { + // A connector is a resource that can be used to proactively report impacts against workloads in Azure to Microsoft. + Connector +} + +// ConnectorsClientDeleteResponse contains the response from method ConnectorsClient.Delete. +type ConnectorsClientDeleteResponse struct { + // placeholder for future response values +} + +// ConnectorsClientGetResponse contains the response from method ConnectorsClient.Get. +type ConnectorsClientGetResponse struct { + // A connector is a resource that can be used to proactively report impacts against workloads in Azure to Microsoft. + Connector +} + +// ConnectorsClientListBySubscriptionResponse contains the response from method ConnectorsClient.NewListBySubscriptionPager. +type ConnectorsClientListBySubscriptionResponse struct { + // The response of a Connector list operation. + ConnectorListResult +} + +// ConnectorsClientUpdateResponse contains the response from method ConnectorsClient.Update. +type ConnectorsClientUpdateResponse struct { + // A connector is a resource that can be used to proactively report impacts against workloads in Azure to Microsoft. + Connector +} + +// InsightsClientCreateResponse contains the response from method InsightsClient.Create. +type InsightsClientCreateResponse struct { + // Insight resource + Insight +} + +// InsightsClientDeleteResponse contains the response from method InsightsClient.Delete. +type InsightsClientDeleteResponse struct { + // placeholder for future response values +} + +// InsightsClientGetResponse contains the response from method InsightsClient.Get. +type InsightsClientGetResponse struct { + // Insight resource + Insight +} + +// InsightsClientListBySubscriptionResponse contains the response from method InsightsClient.NewListBySubscriptionPager. +type InsightsClientListBySubscriptionResponse struct { + // The response of a Insight list operation. + InsightListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// WorkloadImpactsClientCreateResponse contains the response from method WorkloadImpactsClient.BeginCreate. +type WorkloadImpactsClientCreateResponse struct { + // Workload Impact properties + WorkloadImpact +} + +// WorkloadImpactsClientDeleteResponse contains the response from method WorkloadImpactsClient.Delete. +type WorkloadImpactsClientDeleteResponse struct { + // placeholder for future response values +} + +// WorkloadImpactsClientGetResponse contains the response from method WorkloadImpactsClient.Get. +type WorkloadImpactsClientGetResponse struct { + // Workload Impact properties + WorkloadImpact +} + +// WorkloadImpactsClientListBySubscriptionResponse contains the response from method WorkloadImpactsClient.NewListBySubscriptionPager. +type WorkloadImpactsClientListBySubscriptionResponse struct { + // The response of a WorkloadImpact list operation. + WorkloadImpactListResult +} diff --git a/sdk/resourcemanager/impact/armimpact/time_rfc3339.go b/sdk/resourcemanager/impact/armimpact/time_rfc3339.go new file mode 100644 index 000000000000..853c3e7949b9 --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/time_rfc3339.go @@ -0,0 +1,110 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "regexp" + "strings" + "time" +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(?:Z|z|\+|-)(?:\d+:\d+)*"*$`) + +const ( + utcDateTime = "2006-01-02T15:04:05.999999999" + utcDateTimeJSON = `"` + utcDateTime + `"` + utcDateTimeNoT = "2006-01-02 15:04:05.999999999" + utcDateTimeJSONNoT = `"` + utcDateTimeNoT + `"` + dateTimeNoT = `2006-01-02 15:04:05.999999999Z07:00` + dateTimeJSON = `"` + time.RFC3339Nano + `"` + dateTimeJSONNoT = `"` + dateTimeNoT + `"` +) + +type dateTimeRFC3339 time.Time + +func (t dateTimeRFC3339) MarshalJSON() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t dateTimeRFC3339) MarshalText() ([]byte, error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *dateTimeRFC3339) UnmarshalJSON(data []byte) error { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = dateTimeJSON + } else if tzOffset { + layout = dateTimeJSONNoT + } else if hasT { + layout = utcDateTimeJSON + } else { + layout = utcDateTimeJSONNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) UnmarshalText(data []byte) error { + tzOffset := tzOffsetRegex.Match(data) + hasT := strings.Contains(string(data), "T") || strings.Contains(string(data), "t") + var layout string + if tzOffset && hasT { + layout = time.RFC3339Nano + } else if tzOffset { + layout = dateTimeNoT + } else if hasT { + layout = utcDateTime + } else { + layout = utcDateTimeNoT + } + return t.Parse(layout, string(data)) +} + +func (t *dateTimeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = dateTimeRFC3339(p) + return err +} + +func (t dateTimeRFC3339) String() string { + return time.Time(t).Format(time.RFC3339Nano) +} + +func populateDateTimeRFC3339(m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + return + } else if reflect.ValueOf(t).IsNil() { + return + } + m[k] = (*dateTimeRFC3339)(t) +} + +func unpopulateDateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux dateTimeRFC3339 + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + *t = (*time.Time)(&aux) + return nil +} diff --git a/sdk/resourcemanager/impact/armimpact/workloadimpacts_client.go b/sdk/resourcemanager/impact/armimpact/workloadimpacts_client.go new file mode 100644 index 000000000000..de110537a12a --- /dev/null +++ b/sdk/resourcemanager/impact/armimpact/workloadimpacts_client.go @@ -0,0 +1,283 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) AutoRest Code Generator. DO NOT EDIT. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armimpact + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// WorkloadImpactsClient contains the methods for the WorkloadImpacts group. +// Don't use this type directly, use NewWorkloadImpactsClient() instead. +type WorkloadImpactsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWorkloadImpactsClient creates a new instance of WorkloadImpactsClient with the specified values. +// - subscriptionID - The ID of the target subscription. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewWorkloadImpactsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WorkloadImpactsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WorkloadImpactsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a WorkloadImpact +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - resource - Resource create parameters. +// - options - WorkloadImpactsClientBeginCreateOptions contains the optional parameters for the WorkloadImpactsClient.BeginCreate +// method. +func (client *WorkloadImpactsClient) BeginCreate(ctx context.Context, workloadImpactName string, resource WorkloadImpact, options *WorkloadImpactsClientBeginCreateOptions) (*runtime.Poller[WorkloadImpactsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, workloadImpactName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WorkloadImpactsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WorkloadImpactsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a WorkloadImpact +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +func (client *WorkloadImpactsClient) create(ctx context.Context, workloadImpactName string, resource WorkloadImpact, options *WorkloadImpactsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "WorkloadImpactsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, workloadImpactName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *WorkloadImpactsClient) createCreateRequest(ctx context.Context, workloadImpactName string, resource WorkloadImpact, options *WorkloadImpactsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a WorkloadImpact +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - options - WorkloadImpactsClientDeleteOptions contains the optional parameters for the WorkloadImpactsClient.Delete method. +func (client *WorkloadImpactsClient) Delete(ctx context.Context, workloadImpactName string, options *WorkloadImpactsClientDeleteOptions) (WorkloadImpactsClientDeleteResponse, error) { + var err error + const operationName = "WorkloadImpactsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, workloadImpactName, options) + if err != nil { + return WorkloadImpactsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkloadImpactsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return WorkloadImpactsClientDeleteResponse{}, err + } + return WorkloadImpactsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WorkloadImpactsClient) deleteCreateRequest(ctx context.Context, workloadImpactName string, options *WorkloadImpactsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Get a WorkloadImpact +// If the operation fails it returns an *azcore.ResponseError type. +// +// Generated from API version 2024-05-01-preview +// - workloadImpactName - workloadImpact resource +// - options - WorkloadImpactsClientGetOptions contains the optional parameters for the WorkloadImpactsClient.Get method. +func (client *WorkloadImpactsClient) Get(ctx context.Context, workloadImpactName string, options *WorkloadImpactsClientGetOptions) (WorkloadImpactsClientGetResponse, error) { + var err error + const operationName = "WorkloadImpactsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, workloadImpactName, options) + if err != nil { + return WorkloadImpactsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkloadImpactsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WorkloadImpactsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WorkloadImpactsClient) getCreateRequest(ctx context.Context, workloadImpactName string, options *WorkloadImpactsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts/{workloadImpactName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if workloadImpactName == "" { + return nil, errors.New("parameter workloadImpactName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workloadImpactName}", url.PathEscape(workloadImpactName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WorkloadImpactsClient) getHandleResponse(resp *http.Response) (WorkloadImpactsClientGetResponse, error) { + result := WorkloadImpactsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkloadImpact); err != nil { + return WorkloadImpactsClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List WorkloadImpact resources by subscription ID +// +// Generated from API version 2024-05-01-preview +// - options - WorkloadImpactsClientListBySubscriptionOptions contains the optional parameters for the WorkloadImpactsClient.NewListBySubscriptionPager +// method. +func (client *WorkloadImpactsClient) NewListBySubscriptionPager(options *WorkloadImpactsClientListBySubscriptionOptions) *runtime.Pager[WorkloadImpactsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[WorkloadImpactsClientListBySubscriptionResponse]{ + More: func(page WorkloadImpactsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WorkloadImpactsClientListBySubscriptionResponse) (WorkloadImpactsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WorkloadImpactsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return WorkloadImpactsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *WorkloadImpactsClient) listBySubscriptionCreateRequest(ctx context.Context, options *WorkloadImpactsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Impact/workloadImpacts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2024-05-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *WorkloadImpactsClient) listBySubscriptionHandleResponse(resp *http.Response) (WorkloadImpactsClientListBySubscriptionResponse, error) { + result := WorkloadImpactsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkloadImpactListResult); err != nil { + return WorkloadImpactsClientListBySubscriptionResponse{}, err + } + return result, nil +}