Skip to content

Implementing a more modular API #1627

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
24 changes: 24 additions & 0 deletions examples/clientset/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// See https://aka.ms/new-console-template for more information
using k8s;
using k8s.ClientSets;
using System.Threading.Tasks;

namespace clientset
{
internal class Program
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);

ClientSet clientSet = new ClientSet(client);
var list = await clientSet.CoreV1.Pod.ListNamespacedPodAsync("default").ConfigureAwait(false);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ListAsync?

i prefer the style in your proposal, it is simpler

Copy link
Contributor Author

@ayrloong ayrloong Apr 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used x-kuberneter-action to define the method name. Can you help me see if there is any problem with this?https://github.com/kubernetes-client/csharp/pull/1627/files#diff-9501625d7da40bd1b40cb3b43406f26d00f5aa65c65f4877b1eaec2d40f792a0R169

foreach (var item in list)
{
System.Console.WriteLine(item.Metadata.Name);
}
}
}

}
6 changes: 6 additions & 0 deletions examples/clientset/clientset.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>

</Project>
6 changes: 5 additions & 1 deletion src/KubernetesClient.Aot/KubernetesClient.Aot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
<Compile Include="..\KubernetesClient\Models\V1Status.cs" />

</ItemGroup>
<ItemGroup>
<Compile Include="..\KubernetesClient\ClientSets\ClientSet.cs" />
<Compile Include="..\KubernetesClient\ClientSets\ResourceClient.cs"/>
</ItemGroup>
<ItemGroup>
<Compile Include="..\KubernetesClient\AbstractKubernetes.cs" />
<Compile Include="..\KubernetesClient\GeneratedApiVersion.cs" />
Expand Down Expand Up @@ -107,4 +111,4 @@
<ItemGroup>
<ProjectReference Include="..\LibKubernetesGenerator\generators\LibKubernetesGenerator\LibKubernetesGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>
</Project>
5 changes: 4 additions & 1 deletion src/KubernetesClient.Classic/KubernetesClient.Classic.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@
<Compile Include="..\KubernetesClient\Autorest\HttpRequestMessageWrapper.cs" />
<Compile Include="..\KubernetesClient\Autorest\HttpResponseMessageWrapper.cs" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\KubernetesClient\ClientSets\ClientSet.cs" />
<Compile Include="..\KubernetesClient\ClientSets\ResourceClient.cs"/>
</ItemGroup>
<ItemGroup>
<Compile Include="..\KubernetesClient\FileSystem.cs" />
<Compile Include="..\KubernetesClient\IKubernetes.cs" />
Expand Down
8 changes: 4 additions & 4 deletions src/KubernetesClient/AbstractKubernetes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace k8s;

public abstract partial class AbstractKubernetes
{
private static class HttpMethods
internal static class HttpMethods
{
public static readonly HttpMethod Delete = HttpMethod.Delete;
public static readonly HttpMethod Get = HttpMethod.Get;
Expand All @@ -23,7 +23,7 @@ private static class HttpMethods

}

private sealed class QueryBuilder
internal sealed class QueryBuilder
{
private readonly List<string> parameters = new List<string>();

Expand Down Expand Up @@ -99,7 +99,7 @@ private MediaTypeHeaderValue GetHeader(V1Patch body)
}
}

protected abstract Task<HttpOperationResponse<T>> CreateResultAsync<T>(HttpRequestMessage httpRequest, HttpResponseMessage httpResponse, bool? watch, CancellationToken cancellationToken);
internal abstract Task<HttpOperationResponse<T>> CreateResultAsync<T>(HttpRequestMessage httpRequest, HttpResponseMessage httpResponse, bool? watch, CancellationToken cancellationToken);

protected abstract Task<HttpResponseMessage> SendRequest<T>(string relativeUri, HttpMethod method, IReadOnlyDictionary<string, IReadOnlyList<string>> customHeaders, T body, CancellationToken cancellationToken);
internal abstract Task<HttpResponseMessage> SendRequest<T>(string relativeUri, HttpMethod method, IReadOnlyDictionary<string, IReadOnlyList<string>> customHeaders, T body, CancellationToken cancellationToken);
}
6 changes: 6 additions & 0 deletions src/KubernetesClient/ClientSets/ClientSet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace k8s.ClientSets;

public partial class ClientSet
{

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 4 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

}

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / e2e

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

Check warning on line 6 in src/KubernetesClient/ClientSets/ClientSet.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

11 changes: 11 additions & 0 deletions src/KubernetesClient/ClientSets/ResourceClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace k8s.ClientSets;

public abstract class ResourceClient
{
protected Kubernetes Client { get; }

public ResourceClient(IKubernetes kubernetes)
{
Client = (Kubernetes)kubernetes;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did not quite get here,
anyway to avoid cast, why not force input Kubernetes?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that IKubernetes is typically registered in the DI container, I relied on dependency injection instead of manually providing Kubernetes

}
}
1 change: 1 addition & 0 deletions src/KubernetesClient/GenericClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@

public async Task<T> CreateAsync<T>(T obj, CancellationToken cancel = default)
where T : IKubernetesObject
{

Check warning on line 33 in src/KubernetesClient/GenericClient.cs

View workflow job for this annotation

GitHub Actions / e2e

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 33 in src/KubernetesClient/GenericClient.cs

View workflow job for this annotation

GitHub Actions / e2e

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 33 in src/KubernetesClient/GenericClient.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

Check warning on line 33 in src/KubernetesClient/GenericClient.cs

View workflow job for this annotation

GitHub Actions / MSBuild build

An opening brace should not be followed by a blank line. (https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1505.md)

var resp = await kubernetes.CustomObjects.CreateClusterCustomObjectWithHttpMessagesAsync<T>(obj, group, version, plural, cancellationToken: cancel).ConfigureAwait(false);
return resp.Body;
}
Expand Down
14 changes: 7 additions & 7 deletions src/KubernetesClient/Kubernetes.WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@ public partial class Kubernetes
/// <inheritdoc/>
public Task<WebSocket> WebSocketNamespacedPodExecAsync(string name, string @namespace = "default",
string command = null, string container = null, bool stderr = true, bool stdin = true, bool stdout = true,
bool tty = true, string webSocketSubProtol = null, Dictionary<string, List<string>> customHeaders = null,
bool tty = true, string webSocketSubProtocol = null, Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
return WebSocketNamespacedPodExecAsync(name, @namespace, new string[] { command }, container, stderr, stdin,
stdout, tty, webSocketSubProtol, customHeaders, cancellationToken);
stdout, tty, webSocketSubProtocol, customHeaders, cancellationToken);
}

/// <inheritdoc/>
public virtual async Task<IStreamDemuxer> MuxedStreamNamespacedPodExecAsync(
string name,
string @namespace = "default", IEnumerable<string> command = null, string container = null,
bool stderr = true, bool stdin = true, bool stdout = true, bool tty = true,
string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol,
string webSocketSubProtocol = WebSocketProtocol.V4BinaryWebsocketProtocol,
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
Expand All @@ -45,7 +45,7 @@ public virtual async Task<IStreamDemuxer> MuxedStreamNamespacedPodExecAsync(
public virtual Task<WebSocket> WebSocketNamespacedPodExecAsync(string name, string @namespace = "default",
IEnumerable<string> command = null, string container = null, bool stderr = true, bool stdin = true,
bool stdout = true, bool tty = true,
string webSocketSubProtol = WebSocketProtocol.V4BinaryWebsocketProtocol,
string webSocketSubProtocol = WebSocketProtocol.V4BinaryWebsocketProtocol,
Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
Expand Down Expand Up @@ -114,7 +114,7 @@ public virtual Task<WebSocket> WebSocketNamespacedPodExecAsync(string name, stri
uriBuilder.Query =
query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it

return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders,
return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtocol, customHeaders,
cancellationToken);
}

Expand Down Expand Up @@ -173,7 +173,7 @@ public Task<WebSocket> WebSocketNamespacedPodPortForwardAsync(string name, strin
/// <inheritdoc/>
public Task<WebSocket> WebSocketNamespacedPodAttachAsync(string name, string @namespace,
string container = default, bool stderr = true, bool stdin = false, bool stdout = true,
bool tty = false, string webSocketSubProtol = null, Dictionary<string, List<string>> customHeaders = null,
bool tty = false, string webSocketSubProtocol = null, Dictionary<string, List<string>> customHeaders = null,
CancellationToken cancellationToken = default)
{
if (name == null)
Expand Down Expand Up @@ -208,7 +208,7 @@ public Task<WebSocket> WebSocketNamespacedPodAttachAsync(string name, string @na
uriBuilder.Query =
query.ToString(1, query.Length - 1); // UriBuilder.Query doesn't like leading '?' chars, so trim it

return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtol, customHeaders,
return StreamConnectAsync(uriBuilder.Uri, webSocketSubProtocol, customHeaders,
cancellationToken);
}

Expand Down
4 changes: 2 additions & 2 deletions src/KubernetesClient/Kubernetes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private void Initialize()
BaseUri = new Uri("http://localhost");
}

protected override async Task<HttpOperationResponse<T>> CreateResultAsync<T>(HttpRequestMessage httpRequest, HttpResponseMessage httpResponse, bool? watch, CancellationToken cancellationToken)
internal override async Task<HttpOperationResponse<T>> CreateResultAsync<T>(HttpRequestMessage httpRequest, HttpResponseMessage httpResponse, bool? watch, CancellationToken cancellationToken)
{
if (httpRequest == null)
{
Expand Down Expand Up @@ -96,7 +96,7 @@ protected override async Task<HttpOperationResponse<T>> CreateResultAsync<T>(Htt
return result;
}

protected override Task<HttpResponseMessage> SendRequest<T>(string relativeUri, HttpMethod method, IReadOnlyDictionary<string, IReadOnlyList<string>> customHeaders, T body, CancellationToken cancellationToken)
internal override Task<HttpResponseMessage> SendRequest<T>(string relativeUri, HttpMethod method, IReadOnlyDictionary<string, IReadOnlyList<string>> customHeaders, T body, CancellationToken cancellationToken)
{
var httpRequest = new HttpRequestMessage
{
Expand Down
104 changes: 104 additions & 0 deletions src/LibKubernetesGenerator/ClientSetGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
using CaseExtensions;
using Microsoft.CodeAnalysis;
using NSwag;
using System.Collections.Generic;
using System.Linq;

namespace LibKubernetesGenerator
{
internal class ClientSetGenerator
{
private readonly ScriptObjectFactory _scriptObjectFactory;

public ClientSetGenerator(ScriptObjectFactory scriptObjectFactory)
{
_scriptObjectFactory = scriptObjectFactory;
}

public void Generate(OpenApiDocument swagger, IncrementalGeneratorPostInitializationContext context)
{
var data = swagger.Operations
.Where(o => o.Method != OpenApiOperationMethod.Options)
.Select(o =>
{
var ps = o.Operation.ActualParameters.OrderBy(p => !p.IsRequired).ToArray();

o.Operation.Parameters.Clear();

var name = new HashSet<string>();

var i = 1;
foreach (var p in ps)
{
if (name.Contains(p.Name))
{
p.Name += i++;
}

o.Operation.Parameters.Add(p);
name.Add(p.Name);
}

return o;
})
.Select(o =>
{
o.Path = o.Path.TrimStart('/');
o.Method = char.ToUpper(o.Method[0]) + o.Method.Substring(1);
return o;
})
.ToArray();

var sc = _scriptObjectFactory.CreateScriptObject();

var groups = new List<string>();
var apiGroups = new Dictionary<string, OpenApiOperationDescription[]>();

foreach (var grouped in data.Where(d => HasKubernetesAction(d.Operation?.ExtensionData))
.GroupBy(d => d.Operation.Tags.First()))
{
var clients = new List<string>();
var name = grouped.Key.ToPascalCase();
groups.Add(name);
var apis = grouped.Select(x =>
{
var groupVersionKindElements = x.Operation?.ExtensionData?["x-kubernetes-group-version-kind"];
var groupVersionKind = (Dictionary<string, object>)groupVersionKindElements;

return new { Kind = groupVersionKind?["kind"], Api = x };

});

Check warning on line 70 in src/LibKubernetesGenerator/ClientSetGenerator.cs

View workflow job for this annotation

GitHub Actions / Analyze (csharp)

Check warning on line 70 in src/LibKubernetesGenerator/ClientSetGenerator.cs

View workflow job for this annotation

GitHub Actions / e2e

Check warning on line 70 in src/LibKubernetesGenerator/ClientSetGenerator.cs

View workflow job for this annotation

GitHub Actions / MSBuild build


foreach (var item in apis.GroupBy(x => x.Kind))
{
var kind = item.Key as string;
apiGroups[kind] = item.Select(x => x.Api).ToArray();
clients.Add(kind);
}

sc.SetValue("clients", clients, true);
sc.SetValue("name", name, true);
context.RenderToContext("GroupClient.cs.template", sc, $"{name}GroupClient.g.cs");
}

foreach (var apiGroup in apiGroups)
{
var name = apiGroup.Key;
var apis = apiGroup.Value.ToArray();

sc.SetValue("apis", apis, true);
sc.SetValue("name", name, true);
context.RenderToContext("Client.cs.template", sc, $"{name}Client.g.cs");
context.RenderToContext("ClientExtensions.cs.template", sc, $"{name}ClientExtensions.g.cs");
}

sc = _scriptObjectFactory.CreateScriptObject();
sc.SetValue("groups", groups, true);

context.RenderToContext("ClientSet.cs.template", sc, $"ClientSet.g.cs");
}

private bool HasKubernetesAction(IDictionary<string, object> extensionData) =>
extensionData?.ContainsKey("x-kubernetes-action") ?? false;
}
}
29 changes: 11 additions & 18 deletions src/LibKubernetesGenerator/KubernetesClientSourceGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,46 +21,38 @@ private static IContainer BuildContainer(OpenApiDocument swagger)
builder.RegisterType<ClassNameHelper>()
.WithParameter(new NamedParameter(nameof(swagger), swagger))
.AsSelf()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<StringHelpers>()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<MetaHelper>()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<PluralHelper>()
.WithParameter(new TypedParameter(typeof(OpenApiDocument), swagger))
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<GeneralNameHelper>()
.AsSelf()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<TypeHelper>()
.AsSelf()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<ParamHelper>()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<UtilHelper>()
.AsImplementedInterfaces()
;
.AsImplementedInterfaces();

builder.RegisterType<ScriptObjectFactory>()
;
builder.RegisterType<ScriptObjectFactory>();

builder.RegisterType<ModelExtGenerator>();
builder.RegisterType<ModelGenerator>();
builder.RegisterType<ApiGenerator>();
builder.RegisterType<ClientSetGenerator>();
builder.RegisterType<VersionConverterStubGenerator>();
builder.RegisterType<VersionGenerator>();

Expand All @@ -80,6 +72,7 @@ public void Initialize(IncrementalGeneratorInitializationContext generatorContex
container.Resolve<ModelExtGenerator>().Generate(swagger, ctx);
container.Resolve<VersionConverterStubGenerator>().Generate(swagger, ctx);
container.Resolve<ApiGenerator>().Generate(swagger, ctx);
container.Resolve<ClientSetGenerator>().Generate(swagger, ctx);
});
#endif

Expand Down
Loading
Loading