Skip to content

Commit daf7790

Browse files
committed
refactor: simplify Kubernetes pod watch implementation and enhance error handling
1 parent 38c7ae7 commit daf7790

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

examples/watch/Program.cs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using k8s;
2-
using k8s.Models;
32
using System;
43
using System.Threading;
54
using System.Threading.Tasks;
@@ -8,9 +7,10 @@
87

98
IKubernetes client = new Kubernetes(config);
109

11-
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
10+
var podlistResp = client.CoreV1.WatchListNamespacedPodAsync("default");
11+
1212
// C# 8 required https://docs.microsoft.com/en-us/archive/msdn-magazine/2019/november/csharp-iterating-with-async-enumerables-in-csharp-8
13-
await foreach (var (type, item) in podlistResp.WatchAsync<V1Pod, V1PodList>().ConfigureAwait(false))
13+
await foreach (var (type, item) in podlistResp.ConfigureAwait(false))
1414
{
1515
Console.WriteLine("==on watch event==");
1616
Console.WriteLine(type);
@@ -22,14 +22,24 @@
2222
void WatchUsingCallback(IKubernetes client)
2323
#pragma warning restore CS8321 // Remove unused private members
2424
{
25-
var podlistResp = client.CoreV1.ListNamespacedPodWithHttpMessagesAsync("default", watch: true);
26-
using (podlistResp.Watch<V1Pod, V1PodList>((type, item) =>
25+
using var podlistResp = client.CoreV1.WatchListNamespacedPod("default");
26+
podlistResp.OnEvent += (type, item) =>
2727
{
2828
Console.WriteLine("==on watch event==");
2929
Console.WriteLine(type);
3030
Console.WriteLine(item.Metadata.Name);
3131
Console.WriteLine("==on watch event==");
32-
}))
32+
};
33+
podlistResp.OnError += (error) =>
34+
{
35+
Console.WriteLine("==on watch error==");
36+
Console.WriteLine(error.Message);
37+
Console.WriteLine("==on watch error==");
38+
};
39+
podlistResp.OnClosed += () =>
40+
{
41+
Console.WriteLine("==on watch closed==");
42+
};
3343
{
3444
Console.WriteLine("press ctrl + c to stop watching");
3545

src/LibKubernetesGenerator/TypeHelper.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,14 @@ string toType()
245245
}
246246

247247
break;
248+
case "T":
249+
// Return single item type from list type (e.g., V1Pod from V1PodList)
250+
return !string.IsNullOrEmpty(t) && t.EndsWith("List", StringComparison.Ordinal)
251+
? t.Substring(0, t.Length - 4)
252+
: t;
253+
case "TList":
254+
// Return list type as-is
255+
return t;
248256
}
249257

250258
return t;

0 commit comments

Comments
 (0)