Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 15 additions & 3 deletions src/Aspire.Hosting.Radius/RadiusExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ public static IResourceBuilder<RadiusEnvironmentResource> ConfigureRadiusInfrast
/// instead of combining that method with <c>WithContainerImage</c>.
/// </remarks>
[Experimental("ASPIRERADIUS057", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
[AspireExport]
[AspireExportIgnore(Reason = "The generic WithContainerImage overload exports this operation for all .NET program resources.")]
public static IResourceBuilder<ProjectResource> WithContainerImage(
this IResourceBuilder<ProjectResource> builder,
string image) =>
Expand All @@ -144,15 +144,27 @@ public static IResourceBuilder<ProjectResource> WithContainerImage(
/// </summary>
/// <typeparam name="T">The .NET program resource type.</typeparam>
/// <param name="builder">The .NET program resource builder.</param>
/// <param name="image">A fully-qualified image reference in <c>[registry/]image[:tag]</c> form.</param>
/// <param name="image">
/// A fully-qualified image reference in <c>[registry/]image[:tag]</c> form
/// (for example <c>localhost:5001/apiservice:latest</c>). When the tag is omitted,
/// <c>latest</c> is used.
/// </param>
/// <returns>The same resource builder for chaining.</returns>
/// <remarks>
/// <para>
/// The Radius publisher does not yet build or push images for .NET program resources
/// (tracked at https://github.com/microsoft/aspire/issues/16844). Build and push the image to a
/// registry the target cluster can pull from, then attach it with this method; without it,
/// <c>aspire publish</c> against a Radius environment fails with a remediation message.
/// </para>
/// <para>
/// The attached image is treated as a final artifact and is not modified by Aspire.
/// Include any files required by <c>PublishWithContainerFiles</c> when building the image
/// instead of combining that method with <c>WithContainerImage</c>.
/// </para>
/// </remarks>
[Experimental("ASPIRERADIUS057", UrlFormat = "https://aka.ms/aspire/diagnostics/{0}")]
[AspireExport("withDotnetProgramContainerImage", MethodName = "withContainerImage")]
[AspireExport]
public static IResourceBuilder<T> WithContainerImage<T>(
this IResourceBuilder<T> builder,
string image)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BREAK capability-return-type-changed Aspire.Hosting.Radius Aspire.Hosting.Radius/withContainerImage -- https://github.com/microsoft/aspire/issues/21803 -- Generalized the retained capability to IDotnetProgramResource while preserving the concrete fluent API for legacy and modern .NET resources.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<ProjectReference Include="..\..\src\Aspire.Hosting.RemoteHost\Aspire.Hosting.RemoteHost.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.JavaScript\Aspire.Hosting.JavaScript.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Kubernetes\Aspire.Hosting.Kubernetes.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Radius\Aspire.Hosting.Radius.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Azure.Kubernetes\Aspire.Hosting.Azure.Kubernetes.csproj" />
<ProjectReference Include="..\Aspire.TestUtilities\Aspire.TestUtilities.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,73 @@ await Verify(new
});
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Generate_RadiusWithContainerImage_PreservesConcreteFluentMethods(bool includeDotnet)
{
const string capabilityId = "Aspire.Hosting.Radius/withContainerImage";
var assemblies = new List<Assembly> { typeof(DistributedApplication).Assembly, typeof(RadiusExtensions).Assembly };
var resourceTypes = new List<Type> { typeof(ProjectResource), typeof(CSharpAppResource) };
if (includeDotnet)
{
assemblies.Add(typeof(DotnetProjectHostingExtensions).Assembly);
resourceTypes.Add(typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource));
}

var result = AtsCapabilityScanner.ScanAssemblies(assemblies);
var capability = Assert.Single(result.Capabilities,
c => c.CapabilityId.StartsWith("Aspire.Hosting.Radius/", StringComparison.Ordinal) &&
c.MethodName == "withContainerImage");

Assert.Equal(capabilityId, capability.CapabilityId);
Assert.Equal(GetAtsTypeId(typeof(IDotnetProgramResource)), capability.TargetTypeId);
Assert.Equal(capability.TargetTypeId, capability.ReturnType.TypeId);
Assert.True(capability.ReturnsBuilder);
Assert.True(capability.IsExperimental);
var image = Assert.Single(capability.Parameters);
Assert.Equal("image", image.Name);
Assert.Equal(AtsConstants.String, image.Type?.TypeId);
Assert.False(image.IsOptional);
Assert.Equal(
resourceTypes.Select(GetAtsTypeId).Order(StringComparer.Ordinal),
capability.ExpandedTargetTypes.Select(t => t.TypeId).Order(StringComparer.Ordinal));
var diagnostic = Assert.Single(result.Diagnostics, d => d.Message.Contains(capabilityId, StringComparison.Ordinal));
Assert.Equal(AtsDiagnosticSeverity.Info, diagnostic.Severity);

var code = _generator.GenerateDistributedApplication(result.ToAtsContext())["aspire.mts"].ReplaceLineEndings("\n");
var declarations = new List<string>();
foreach (var resourceType in resourceTypes)
{
foreach (var suffix in new[] { "", "Promise" })
{
var name = resourceType.Name + suffix;
// Generated declarations have the shape:
// export interface ProjectResourcePromise extends PromiseLike<ProjectResource> { ... }
var declaration = Regex.Match(code, $@"^export interface {name}(?: extends [^\n]+)? \{{.*?^\}}",
RegexOptions.Multiline | RegexOptions.Singleline);
Assert.True(declaration.Success, $"Missing generated interface {name}.");
var method = Assert.Single(declaration.Value.Split('\n'),
line => line.TrimStart().StartsWith("withContainerImage(", StringComparison.Ordinal));
Assert.Equal($" withContainerImage(image: string): {resourceType.Name}Promise;", method);
declarations.Add($"interface {name} {{\n{method}\n}}");
}

var implementation = Regex.Match(code, $@"^class {resourceType.Name}Impl\b.*?^\}}",
RegexOptions.Multiline | RegexOptions.Singleline);
Assert.True(implementation.Success, $"Missing generated implementation for {resourceType.Name}.");
var invocation = Regex.Match(implementation.Value, @"^ private async _withContainerImageInternal\(.*?^ \}",
RegexOptions.Multiline | RegexOptions.Singleline);
Assert.True(invocation.Success, $"Missing generated image invocation for {resourceType.Name}.");
var dispatchCall = Assert.Single(invocation.Value.Split('\n'),
line => line.TrimStart().StartsWith("'Aspire.Hosting.Radius/", StringComparison.Ordinal));
Assert.Equal($"'{capabilityId}',", dispatchCall.Trim());
declarations.Add(invocation.Value);
}

await Verify(string.Join("\n\n", declarations), "ts").UseParameters(includeDotnet);
}

[Fact]
public void Generate_KubernetesPersistentVolumeMount_UsesOptionsObject()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
interface ProjectResource {
withContainerImage(image: string): ProjectResourcePromise;
}

interface ProjectResourcePromise {
withContainerImage(image: string): ProjectResourcePromise;
}

private async _withContainerImageInternal(image: string): Promise<ProjectResource> {
const rpcArgs: Record<string, unknown> = { builder: this._handle, image };
const result = await this._client.invokeCapability<ProjectResourceHandle>(
'Aspire.Hosting.Radius/withContainerImage',
rpcArgs
);
return new ProjectResourceImpl(result, this._client);
}

interface CSharpAppResource {
withContainerImage(image: string): CSharpAppResourcePromise;
}

interface CSharpAppResourcePromise {
withContainerImage(image: string): CSharpAppResourcePromise;
}

private async _withContainerImageInternal(image: string): Promise<CSharpAppResource> {
const rpcArgs: Record<string, unknown> = { builder: this._handle, image };
const result = await this._client.invokeCapability<CSharpAppResourceHandle>(
'Aspire.Hosting.Radius/withContainerImage',
rpcArgs
);
return new CSharpAppResourceImpl(result, this._client);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
interface ProjectResource {
withContainerImage(image: string): ProjectResourcePromise;
}

interface ProjectResourcePromise {
withContainerImage(image: string): ProjectResourcePromise;
}

private async _withContainerImageInternal(image: string): Promise<ProjectResource> {
const rpcArgs: Record<string, unknown> = { builder: this._handle, image };
const result = await this._client.invokeCapability<ProjectResourceHandle>(
'Aspire.Hosting.Radius/withContainerImage',
rpcArgs
);
return new ProjectResourceImpl(result, this._client);
}

interface CSharpAppResource {
withContainerImage(image: string): CSharpAppResourcePromise;
}

interface CSharpAppResourcePromise {
withContainerImage(image: string): CSharpAppResourcePromise;
}

private async _withContainerImageInternal(image: string): Promise<CSharpAppResource> {
const rpcArgs: Record<string, unknown> = { builder: this._handle, image };
const result = await this._client.invokeCapability<CSharpAppResourceHandle>(
'Aspire.Hosting.Radius/withContainerImage',
rpcArgs
);
return new CSharpAppResourceImpl(result, this._client);
}

interface DotnetProjectResource {
withContainerImage(image: string): DotnetProjectResourcePromise;
}

interface DotnetProjectResourcePromise {
withContainerImage(image: string): DotnetProjectResourcePromise;
}

private async _withContainerImageInternal(image: string): Promise<DotnetProjectResource> {
const rpcArgs: Record<string, unknown> = { builder: this._handle, image };
const result = await this._client.invokeCapability<DotnetProjectResourceHandle>(
'Aspire.Hosting.Radius/withContainerImage',
rpcArgs
);
return new DotnetProjectResourceImpl(result, this._client);
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<ProjectReference Include="..\..\src\Aspire.Hosting.CodeGeneration.Python\Aspire.Hosting.CodeGeneration.Python.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.CodeGeneration.Rust\Aspire.Hosting.CodeGeneration.Rust.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.CodeGeneration.TypeScript\Aspire.Hosting.CodeGeneration.TypeScript.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Dotnet\Aspire.Hosting.Dotnet.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Radius\Aspire.Hosting.Radius.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.Kubernetes\Aspire.Hosting.Kubernetes.csproj" />
<ProjectReference Include="..\..\src\Aspire.Hosting.RemoteHost\Aspire.Hosting.RemoteHost.csproj" Aliases="global,RemoteHost" />
<ProjectReference Include="..\..\src\Aspire.Hosting\Aspire.Hosting.csproj" />
Expand Down
48 changes: 48 additions & 0 deletions tests/Aspire.Hosting.RemoteHost.Tests/CapabilityDispatcherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,54 @@ namespace Aspire.Hosting.RemoteHost.Tests;

public class CapabilityDispatcherTests
{
[Theory]
[InlineData("project")]
[InlineData("csharp")]
[InlineData("dotnet")]
public async Task Invoke_RadiusWithContainerImage_PreservesBuilderAndReplacesImage(string resourceKind)
{
var builder = DistributedApplication.CreateBuilder();
IResourceBuilder<IDotnetProgramResource> resource = resourceKind switch
{
"project" => builder.AddResource(new ProjectResource("api")),
"csharp" => builder.AddResource(new CSharpAppResource("api")),
"dotnet" => builder.AddResource(new global::Aspire.Hosting.Dotnet.DotnetProjectResource("api", ".")),
_ => throw new ArgumentOutOfRangeException(nameof(resourceKind))
};
await using var handles = new HandleRegistry();
var dispatcher = new CapabilityDispatcher(handles, CreateTestMarshaller(handles),
[typeof(DistributedApplication).Assembly, typeof(RadiusExtensions).Assembly, typeof(DotnetProjectHostingExtensions).Assembly]);
var handleId = handles.Register(resource, AtsTypeMapping.DeriveTypeId(resource.Resource.GetType()));

foreach (var image in new[] { "localhost:5001/api:v1", "ghcr.io/owner/api:v2" })
{
var result = await dispatcher.InvokeAsync("Aspire.Hosting.Radius/withContainerImage", new JsonObject
{
["builder"] = new JsonObject { ["$handle"] = handleId },
["image"] = image
});

Assert.NotNull(result);
var returnedHandleId = result["$handle"]!.GetValue<string>();
Assert.True(handles.TryGet(returnedHandleId, out var returnedBuilder, out _));
Assert.Same(resource, returnedBuilder);
Assert.Same(resource.Resource, Assert.IsAssignableFrom<IResourceBuilder<IResource>>(returnedBuilder).Resource);
var annotation = Assert.Single(resource.Resource.Annotations.OfType<ContainerImageAnnotation>());
if (image == "localhost:5001/api:v1")
{
Assert.Equal("localhost:5001", annotation.Registry);
Assert.Equal("api", annotation.Image);
Assert.Equal("v1", annotation.Tag);
}
else
{
Assert.Equal("ghcr.io", annotation.Registry);
Assert.Equal("owner/api", annotation.Image);
Assert.Equal("v2", annotation.Tag);
}
}
}

[Fact]
[RequiresTools(["python3"])]
[SkipOnPlatform(TestPlatforms.Windows, "Uses the Unix Python executable.")]
Expand Down
Loading