Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement mgmt resource #47944

Open
wants to merge 53 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
f041f24
wip
live1206 Jan 16, 2025
badf1a5
wip
live1206 Jan 20, 2025
69fa28a
wip
live1206 Jan 21, 2025
615fec1
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Jan 21, 2025
d136be2
wip
live1206 Jan 23, 2025
a040627
wip
live1206 Jan 26, 2025
0296a71
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Jan 26, 2025
fda752a
generate operation methods for Resource
live1206 Jan 27, 2025
580508a
add package back
live1206 Jan 27, 2025
ba12225
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Feb 6, 2025
ef83882
update to latest MGC
live1206 Feb 6, 2025
120e164
fix test
live1206 Feb 6, 2025
e4bbde0
Merge branch 'main' into implement-mgmt-resource
live1206 Feb 7, 2025
b2842c4
Add test for ResourceProvider
live1206 Feb 8, 2025
5f5cee9
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Feb 8, 2025
41cf53c
Add RequestPath
live1206 Feb 8, 2025
7bba967
remove unused property
live1206 Feb 10, 2025
5d3a879
address comments
live1206 Feb 11, 2025
2fe508f
Include custom code for convenience methods
live1206 Feb 11, 2025
d9fd368
add TODO
live1206 Feb 11, 2025
17b2a0f
merge from main
live1206 Feb 13, 2025
45a10a7
implement resource LRO
live1206 Feb 13, 2025
b06fb59
implement LRO for resource
live1206 Feb 14, 2025
c98e231
Implement IOperationSouce and generated MgmtTypeSpec can build now
live1206 Feb 14, 2025
848e6d7
update test data
live1206 Feb 14, 2025
0db68cb
Add test for OperationSourceProvider
live1206 Feb 14, 2025
2b15650
update tests
live1206 Feb 14, 2025
51bd7f3
cleanup
live1206 Feb 14, 2025
a8b2b8f
update
live1206 Feb 14, 2025
dc2b83d
cleanup
live1206 Feb 14, 2025
adbcc1c
Address comments
live1206 Feb 15, 2025
bb92673
Add Mgmt-TypeSpec generation to Generate.ps1
live1206 Feb 15, 2025
af9bd9c
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Feb 18, 2025
c5ca437
Update eng/packages/http-client-csharp/generator/Azure.Generator/src/…
live1206 Feb 19, 2025
3ed339d
update
live1206 Feb 19, 2025
d800d35
Merge branch 'main' into implement-mgmt-resource
live1206 Feb 24, 2025
8d78f7f
fix build
live1206 Feb 24, 2025
8fbc8aa
update to use CanonicalView
live1206 Feb 24, 2025
081696d
update test
live1206 Feb 24, 2025
f9e8afd
Use ModelSerializationExtensions.WireOptions instead of new instance
live1206 Feb 24, 2025
8d7b831
update test
live1206 Feb 24, 2025
4dcccc7
Address comments
live1206 Feb 25, 2025
d00ee3a
typo
live1206 Feb 25, 2025
0086b11
Merge remote-tracking branch 'origin/main' into implement-mgmt-resource
live1206 Feb 25, 2025
e34db7b
resolve comments
live1206 Feb 26, 2025
417af63
fix build
live1206 Feb 26, 2025
965e951
update test
live1206 Feb 27, 2025
579dd9b
separate tests for ResourceClientProvider
live1206 Feb 27, 2025
682e704
Add TODO
live1206 Feb 27, 2025
22e08c6
fix tests
live1206 Feb 28, 2025
541193c
Move resource related logic to ResourceBuilder
live1206 Feb 28, 2025
20cdaaf
Remove clientProvider and implement client methods in Resource directly
live1206 Mar 1, 2025
78b5cb5
update
live1206 Mar 1, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions eng/Packages.Data.props
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@
<PackageReference Update="Azure.Messaging.EventGrid" Version="4.17.0" />
<PackageReference Update="Azure.Messaging.EventHubs.Processor" Version="5.11.6" />
<PackageReference Update="Azure.Messaging.ServiceBus" Version="7.18.2" />
<PackageReference Update="Azure.ResourceManager" Version="1.13.0" />
<PackageReference Update="Azure.ResourceManager.Compute" Version="1.7.0-beta.1" />
<PackageReference Update="Azure.ResourceManager.CognitiveServices" Version="1.3.0" />
<PackageReference Update="Azure.ResourceManager.KeyVault" Version="1.1.0" />
Expand Down
37 changes: 32 additions & 5 deletions eng/packages/http-client-csharp/eng/scripts/Generate.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ if (-not $LaunchOnly) {
Write-Host "Generating BasicTypeSpec" -ForegroundColor Cyan
$testProjectsLocalDir = Join-Path $packageRoot 'generator' 'TestProjects' 'Local'

$unbrandedTypespecTestProject = Join-Path $testProjectsLocalDir "Basic-TypeSpec"
$unbrandedTypespecTestProject = $unbrandedTypespecTestProject
$basicTypespecTestProject = Join-Path $testProjectsLocalDir "Basic-TypeSpec"

Invoke (Get-TspCommand "$unbrandedTypespecTestProject/Basic-TypeSpec.tsp" $unbrandedTypespecTestProject -forceNewProject $ForceNewProject)
Invoke (Get-TspCommand "$basicTypespecTestProject/Basic-TypeSpec.tsp" $basicTypespecTestProject -forceNewProject $ForceNewProject)

# exit if the generation failed
if ($LASTEXITCODE -ne 0) {
Expand All @@ -36,6 +35,28 @@ if (-not $LaunchOnly) {
exit $LASTEXITCODE
}
}

if ($null -eq $filter -or $filter -eq "Mgmt-TypeSpec") {
Write-Host "Generating MgmtTypeSpec" -ForegroundColor Cyan
$testProjectsLocalDir = Join-Path $packageRoot 'generator' 'TestProjects' 'Local'

$mgmtTypespecTestProject = Join-Path $testProjectsLocalDir "Mgmt-TypeSpec"

Invoke (Get-TspCommand "$mgmtTypespecTestProject/main.tsp" $mgmtTypespecTestProject -forceNewProject $ForceNewProject)

# exit if the generation failed
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
}

Write-Host "Building MgmtTypeSpec" -ForegroundColor Cyan
Invoke "dotnet build $packageRoot/generator/TestProjects/Local/Mgmt-TypeSpec/src/MgmtTypeSpec.csproj"

# exit if the generation failed
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
}
}
}

$specsDirectory = "$packageRoot/node_modules/@typespec/http-specs"
Expand Down Expand Up @@ -174,14 +195,20 @@ if ($null -eq $filter) {
Write-Host "Writing new launch settings" -ForegroundColor Cyan
$mgcExe = "`$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.exe"
$sampleExe = "`$(SolutionDir)/../generator/artifacts/bin/SamplePlugin/Debug/net8.0/Microsoft.Generator.CSharp.exe"
$unbrandedSpec = "TestProjects/Local/Basic-TypeSpec"
$basicSpec = "TestProjects/Local/Basic-TypeSpec"
$mgmtSpec = "TestProjects/Local/Mgmt-TypeSpec"

$launchSettings = @{}
$launchSettings.Add("profiles", @{})
$launchSettings["profiles"].Add("Basic-TypeSpec", @{})
$launchSettings["profiles"]["Basic-TypeSpec"].Add("commandLineArgs", "`$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.dll `$(SolutionDir)/$unbrandedSpec -p AzureClientPlugin")
$launchSettings["profiles"]["Basic-TypeSpec"].Add("commandLineArgs", "`$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.dll `$(SolutionDir)/$basicSpec -p AzureClientPlugin")
$launchSettings["profiles"]["Basic-TypeSpec"].Add("commandName", "Executable")
$launchSettings["profiles"]["Basic-TypeSpec"].Add("executablePath", "dotnet")

$launchSettings["profiles"].Add("Mgmt-TypeSpec", @{})
$launchSettings["profiles"]["Mgmt-TypeSpec"].Add("commandLineArgs", "`$(SolutionDir)/../dist/generator/Microsoft.Generator.CSharp.dll `$(SolutionDir)/$mgmtSpec -p AzureClientPlugin")
$launchSettings["profiles"]["Mgmt-TypeSpec"].Add("commandName", "Executable")
$launchSettings["profiles"]["Mgmt-TypeSpec"].Add("executablePath", "dotnet")

foreach ($kvp in $spectorLaunchProjects.GetEnumerator()) {
$launchSettings["profiles"].Add($kvp.Key, @{})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.ResourceManager;
using Azure.Generator.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.TypeSpec.Generator;
Expand Down Expand Up @@ -29,7 +30,13 @@ public class AzureClientPlugin : ScmCodeModelPlugin
/// <inheritdoc/>
public override AzureOutputLibrary OutputLibrary => _azureOutputLibrary ??= new();

internal ResourceDetection ResourceDetection { get; } = new();
// TODO: remove these once we can get resource hierarchy natively from TypeSpec input
private ResourceDetection? _resourceDetection;
internal ResourceDetection ResourceDetection => _resourceDetection ??= new();

private ResourceBuilder? _resourceBuilder;
/// <inheritdoc/>
internal ResourceBuilder ResourceBuilder => _resourceBuilder ??= new();

/// <summary>
/// The Azure client plugin to generate the Azure client SDK.
Expand All @@ -55,6 +62,8 @@ public override void Configure()
AddVisitor(new NamespaceVisitor());
if (IsAzureArm.Value)
{
// Include Azure.ResourceManager
AddMetadataReference(MetadataReference.CreateFromFile(typeof(ArmClient).Assembly.Location));
AddVisitor(new RestClientVisitor());
AddVisitor(new ResourceVisitor());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,96 +1,69 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Generator.Mgmt.Models;
using Azure.Generator.Providers;
using Azure.Generator.Utilities;
using Microsoft.TypeSpec.Generator.ClientModel;
using Microsoft.TypeSpec.Generator.Input;
using Microsoft.TypeSpec.Generator.Providers;
using System.Collections.Generic;
using System.Linq;

namespace Azure.Generator
{
/// <inheritdoc/>
public class AzureOutputLibrary : ScmOutputLibrary
{
// TODO: categorize clients into operationSets, which contains operations sharing the same Path
private Dictionary<string, OperationSet> _pathToOperationSetMap;
private Dictionary<string, HashSet<OperationSet>> _resourceDataBySpecNameMap;
private Dictionary<string, InputModelType> _inputTypeMap;

/// <inheritdoc/>
public AzureOutputLibrary()
{
_pathToOperationSetMap = CategorizeClients();
_resourceDataBySpecNameMap = EnsureResourceDataMap();
_inputTypeMap = AzureClientPlugin.Instance.InputLibrary.InputNamespace.Models.OfType<InputModelType>().ToDictionary(model => model.Name);
}

private Dictionary<string, HashSet<OperationSet>> EnsureResourceDataMap()
{
var result = new Dictionary<string, HashSet<OperationSet>>();
foreach (var operationSet in _pathToOperationSetMap.Values)
{
if (AzureClientPlugin.Instance.ResourceDetection.TryGetResourceDataSchema(operationSet, out var resourceSpecName, out var resourceSchema))
{
// if this operation set corresponds to a SDK resource, we add it to the map
if (!result.TryGetValue(resourceSpecName!, out HashSet<OperationSet>? value))
{
value = new HashSet<OperationSet>();
result.Add(resourceSpecName!, value);
}
value.Add(operationSet);
}
}
private LongRunningOperationProvider? _armOperation;
internal LongRunningOperationProvider ArmOperation => _armOperation ??= new LongRunningOperationProvider(false);

return result;
}
private LongRunningOperationProvider? _genericArmOperation;
internal LongRunningOperationProvider GenericArmOperation => _genericArmOperation ??= new LongRunningOperationProvider(true);

private Dictionary<string, OperationSet> CategorizeClients()
private IReadOnlyList<TypeProvider> BuildResources()
{
var result = new Dictionary<string, OperationSet>();
foreach (var inputClient in AzureClientPlugin.Instance.InputLibrary.InputNamespace.Clients)
var result = new List<TypeProvider>();
foreach ((InputClient client, string requestPath, bool isSingleton, string requestType, string specName) in AzureClientPlugin.Instance.ResourceBuilder.BuildResourceClients())
{
var requestPathList = new HashSet<string>();
foreach (var operation in inputClient.Operations)
{
var path = operation.GetHttpPath();
requestPathList.Add(path);
if (result.TryGetValue(path, out var operationSet))
{
operationSet.Add(operation);
}
else
{
operationSet = new OperationSet(path, inputClient)
{
operation
};
result.Add(path, operationSet);
}
}
var resourceData = AzureClientPlugin.Instance.TypeFactory.CreateModel(_inputTypeMap[specName])!;
var resource = CreateResourceCore(client, requestPath, specName, resourceData, requestType, isSingleton);
AzureClientPlugin.Instance.AddTypeToKeep(resource.Name);
result.Add(resource);
}

// TODO: add operation set for the partial resources here

return result;
}

/// <summary>
/// Create a resource client provider
/// </summary>
/// <param name="inputClient"></param>
/// <param name="requestPath"></param>
/// <param name="schemaName"></param>
/// <param name="resourceData"></param>
/// <param name="resourceType"></param>
/// <param name="isSingleton"></param>
/// <returns></returns>
public virtual TypeProvider CreateResourceCore(InputClient inputClient, string requestPath, string schemaName, ModelProvider resourceData, string resourceType, bool isSingleton)
=> new ResourceClientProvider(inputClient, requestPath, schemaName, resourceData, resourceType, isSingleton);

/// <inheritdoc/>
// TODO: generate resources and collections
// TODO: generate collections
protected override TypeProvider[] BuildTypeProviders()
{
var baseProviders = base.BuildTypeProviders();
if (AzureClientPlugin.Instance.IsAzureArm.Value == true)
{
var armOperation = new MgmtLongRunningOperationProvider(false);
var genericArmOperation = new MgmtLongRunningOperationProvider(true);

// TODO: remove them once they are referenced in Resource operation implementation
AzureClientPlugin.Instance.AddTypeToKeep(armOperation.Name);
AzureClientPlugin.Instance.AddTypeToKeep(genericArmOperation.Name);
return [.. base.BuildTypeProviders(), new RequestContextExtensionsDefinition(), armOperation, genericArmOperation];
var resources = BuildResources();
return [.. baseProviders, new RequestContextExtensionsDefinition(), ArmOperation, GenericArmOperation, .. resources, .. resources.Select(r => ((ResourceClientProvider)r).Source)];
}
return [.. base.BuildTypeProviders(), new RequestContextExtensionsDefinition()];
return [.. baseProviders, new RequestContextExtensionsDefinition()];
}

internal bool IsResource(string name) => _resourceDataBySpecNameMap.ContainsKey(name);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;
using Azure.Generator.Utilities;
using Microsoft.TypeSpec.Generator.Input;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Azure.Generator.Mgmt.Models
{
Expand All @@ -17,12 +15,12 @@ namespace Azure.Generator.Mgmt.Models
/// </summary>
internal class OperationSet : IReadOnlyCollection<InputOperation>, IEquatable<OperationSet>
{
private readonly InputClient? _inputClient;

/// <summary>
/// The raw request path of string of the operations in this <see cref="OperationSet"/>
/// </summary>
public string RequestPath { get; }
public RequestPath RequestPath { get; }

public InputClient InputClient { get; }

/// <summary>
/// The operation set
Expand All @@ -31,9 +29,9 @@ internal class OperationSet : IReadOnlyCollection<InputOperation>, IEquatable<Op

public int Count => _operations.Count;

public OperationSet(string requestPath, InputClient? inputClient)
public OperationSet(RequestPath requestPath, InputClient inputClient)
{
_inputClient = inputClient;
InputClient = inputClient;
RequestPath = requestPath;
_operations = new HashSet<InputOperation>();
}
Expand All @@ -46,7 +44,7 @@ public OperationSet(string requestPath, InputClient? inputClient)
public void Add(InputOperation operation)
{
var path = operation.GetHttpPath();
if (path != RequestPath)
if (!path.Equals(RequestPath))
throw new InvalidOperationException($"Cannot add operation with path {path} to OperationSet with path {RequestPath}");
_operations.Add(operation);
}
Expand All @@ -68,43 +66,6 @@ public bool Equals([AllowNull] OperationSet other)
return RequestPath == other.RequestPath;
}

/// <summary>
/// Get the operation with the given verb.
/// We cannot have two operations with the same verb under the same request path, therefore this method is only returning one operation or null
/// </summary>
/// <param name="method"></param>
/// <returns></returns>
public InputOperation? GetOperation(RequestMethod method)
{
foreach (var operation in _operations)
{
if (operation.HttpMethod == method.ToString())
return operation;
}

return null;
}

private InputOperation? FindBestOperation()
{
// first we try GET operation
var getOperation = FindOperation(RequestMethod.Get);
if (getOperation != null)
return getOperation;
// if no GET operation, we return PUT operation
var putOperation = FindOperation(RequestMethod.Put);
if (putOperation != null)
return putOperation;

// if no PUT or GET, we just return the first one
return _operations.FirstOrDefault();
}

public InputOperation? FindOperation(RequestMethod method)
{
return this.FirstOrDefault(operation => operation.HttpMethod == method.ToString());
}

public override string? ToString()
{
return RequestPath;
Expand Down
Loading
Loading