From c1bfb8fabc5abd1dbe38414736071af53aaac4d2 Mon Sep 17 00:00:00 2001 From: Marcus Kimpenhaus <575109+kimpenhaus@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:20:52 +0100 Subject: [PATCH] feat(client): patch the status instead of replacing it PatchStatusAsync(entity, change) applies the change and patches only the status fields it touched, PatchStatusAsync(from, to) the differences between two entities. Both send a JSON merge patch to the /status subresource without a resourceVersion, so they do not fail with 409 Conflict when the entity changed in the meantime. PatchStatusAsync(patch, name, namespace, ...) sends an own patch, e.g. server-side apply. UpdateStatusAsync is unchanged. All new members have default implementations, so IKubernetesClient stays non-breaking. --- .../operator/building-blocks/controllers.mdx | 20 +++- docs/docs/operator/migration.mdx | 6 + docs/docs/operator/troubleshooting.mdx | 3 + .../IKubernetesClient.cs | 107 ++++++++++++++++- .../KubernetesClient.cs | 25 ++++ src/KubeOps.KubernetesClient/README.md | 8 +- src/KubeOps.KubernetesClient/StatusPatch.cs | 109 ++++++++++++++++++ .../KubernetesClient.FieldManager.Test.cs | 51 +++----- .../KubernetesClient.PatchStatus.Test.cs | 94 +++++++++++++++ .../StatusPatch.Test.cs | 101 ++++++++++++++++ .../StubApiServer.cs | 46 ++++++++ .../V1StatusTestEntity.cs | 50 ++++++++ ...etesClient.PatchStatus.Integration.Test.cs | 69 +++++++++++ 13 files changed, 645 insertions(+), 44 deletions(-) create mode 100644 src/KubeOps.KubernetesClient/StatusPatch.cs create mode 100644 test/KubeOps.KubernetesClient.Test/KubernetesClient.PatchStatus.Test.cs create mode 100644 test/KubeOps.KubernetesClient.Test/StatusPatch.Test.cs create mode 100644 test/KubeOps.KubernetesClient.Test/StubApiServer.cs create mode 100644 test/KubeOps.KubernetesClient.Test/V1StatusTestEntity.cs create mode 100644 test/KubeOps.Operator.Test/KubernetesClient.PatchStatus.Integration.Test.cs diff --git a/docs/docs/operator/building-blocks/controllers.mdx b/docs/docs/operator/building-blocks/controllers.mdx index ff762ad9..38252c78 100644 --- a/docs/docs/operator/building-blocks/controllers.mdx +++ b/docs/docs/operator/building-blocks/controllers.mdx @@ -126,13 +126,29 @@ public async Task> ReconcileAsync( } // Update status to reflect current state - entity.Status.LastReconciled = DateTime.UtcNow; - await client.UpdateStatusAsync(entity, cancellationToken); + entity = await client.PatchStatusAsync( + entity, + e => e.Status.LastReconciled = DateTime.UtcNow, + cancellationToken); return ReconciliationResult.Success(entity); } ``` +### Writing the Status + +`PatchStatusAsync(entity, change)` applies `change` to the entity and writes only the status fields it changed, +as a JSON merge patch to the `/status` subresource. The patch carries no `resourceVersion`, so it does not fail +with `409 Conflict` when the entity changed in the meantime, and status fields you did not change stay as +others wrote them. `PatchStatusAsync(from, to)` does the same for the changes between two entities. + +Removed fields are sent as `null`. A changed array, e.g. a list of conditions, is sent as a whole and replaces +the conditions that others added in the meantime; use a server-side apply patch with +`PatchStatusAsync(patch, name, namespace, fieldManager, force)` when several writers share a list. + +`UpdateStatusAsync(entity)` replaces the whole status. Use it when the write must fail with `409 Conflict` if +the entity changed since you read it. + ### DeletedAsync :::warning[Important] diff --git a/docs/docs/operator/migration.mdx b/docs/docs/operator/migration.mdx index 0e4ca372..a2570b97 100644 --- a/docs/docs/operator/migration.mdx +++ b/docs/docs/operator/migration.mdx @@ -405,3 +405,9 @@ builder.AddKubeOps("operator", "../MyOperator") .RunWithKubernetes(k8s) .PublishAsKubernetesOperator(k8s); ``` + +### New in v15 (non-breaking) + +- **Status patch**: `PatchStatusAsync(entity, change)` and `PatchStatusAsync(from, to)` write only the changed + status fields as a JSON merge patch, without a `409 Conflict` on an outdated `resourceVersion`. See + [Writing the Status](./building-blocks/controllers#writing-the-status). diff --git a/docs/docs/operator/troubleshooting.mdx b/docs/docs/operator/troubleshooting.mdx index 74d53ed6..1ec564a1 100644 --- a/docs/docs/operator/troubleshooting.mdx +++ b/docs/docs/operator/troubleshooting.mdx @@ -82,6 +82,9 @@ entity = await client.UpdateStatusAsync(entity, cancellationToken); // use the r [leader election](./configuration/leader-election)) writing the same object concurrently. Treat them as retryable: re-fetch, re-apply, or simply let the failed reconciliation retry. +For the status, `PatchStatusAsync` avoids the conflict: it patches only the changed status fields and +carries no `resourceVersion`. See [Writing the Status](./building-blocks/controllers#writing-the-status). + ## Entity is stuck in "Terminating" **Symptom:** A resource has a `DeletionTimestamp` but is never deleted. diff --git a/src/KubeOps.KubernetesClient/IKubernetesClient.cs b/src/KubeOps.KubernetesClient/IKubernetesClient.cs index a350f044..e29c3be1 100644 --- a/src/KubeOps.KubernetesClient/IKubernetesClient.cs +++ b/src/KubeOps.KubernetesClient/IKubernetesClient.cs @@ -7,6 +7,7 @@ using KubeOps.Abstractions.Entities; using KubeOps.KubernetesClient.Selectors; +using KubeOps.Transpiler; namespace KubeOps.KubernetesClient; @@ -249,8 +250,13 @@ Task> UpdateAsync(params TEntity[] entities) } /// - /// Update the status object of a given entity on the Kubernetes API. + /// Update (replace) the status object of a given entity on the Kubernetes API. /// + /// + /// The replace carries the resourceVersion of and fails with + /// 409 Conflict if the entity changed in the meantime. To write only the changed status fields + /// without that check, use . + /// /// The type of the Kubernetes entity. /// The entity that contains a status object. /// The token to monitor for cancellation requests. @@ -258,6 +264,92 @@ Task> UpdateAsync(params TEntity[] entities) Task UpdateStatusAsync(TEntity entity, CancellationToken cancellationToken = default) where TEntity : IKubernetesObject; + /// + /// Apply to and patch the status fields it changed on the + /// Kubernetes API. + /// + /// + /// The changes are sent as a JSON merge patch to the /status subresource. It carries only the changed + /// fields (removed fields as null, changed arrays as a whole) and no resourceVersion, so it does + /// not fail with 409 Conflict if the entity changed in the meantime. A changed array replaces the + /// array on the API, including entries that others added. + /// + /// The type of the Kubernetes entity. + /// The entity, e.g. as it was passed to the reconciler. It is changed in place. + /// The change of the status, e.g. e => e.Status.Phase = "Ready". + /// The token to monitor for cancellation requests. + /// The patched entity, or if the status did not change. + Task PatchStatusAsync( + TEntity entity, + Action change, + CancellationToken cancellationToken = default) + where TEntity : IKubernetesObject + { + var original = entity.ToNode(); + change(entity); + var patch = StatusPatch.CreateMergePatch(original, entity.ToNode()); + return PatchStatusIfChangedAsync(patch, entity, cancellationToken); + } + + /// + /// Patch the status of a given entity on the Kubernetes API with the changes between the status of + /// and the status of . + /// + /// + /// Sent like . + /// + /// The type of the Kubernetes entity. + /// The entity with the original status. + /// The entity with the desired status. + /// The token to monitor for cancellation requests. + /// The patched entity, or if the status did not change. + Task PatchStatusAsync( + TEntity from, + TEntity to, + CancellationToken cancellationToken = default) + where TEntity : IKubernetesObject => + PatchStatusIfChangedAsync(StatusPatch.CreateMergePatch(from.ToNode(), to.ToNode()), from, cancellationToken); + + /// + /// Patch the status of a given entity on the Kubernetes API by name and namespace using a + /// object, sent to the /status subresource. + /// + /// The type of the Kubernetes entity. + /// + /// The representing the changes to apply, e.g. a JSON merge patch or a server-side apply + /// patch. Only changes to the status are applied. + /// + /// The name of the entity to patch. + /// The namespace of the entity to patch (if applicable). + /// + /// The field manager to write with. Required for a server-side apply patch outside an operator. + /// + /// + /// Force a server-side apply patch, taking ownership of conflicting fields. Only valid for server-side apply. + /// + /// When set (e.g., "All"), the patch is validated but not persisted to storage. + /// The token to monitor for cancellation requests. + /// The patched entity. + Task PatchStatusAsync( + V1Patch patch, + string name, + string? @namespace = null, + string? fieldManager = null, + bool? force = null, + string? dryRun = null, + CancellationToken cancellationToken = default) + where TEntity : IKubernetesObject => + StatusPatch.SendAsync( + ApiClient, + Entities.ToEntityMetadata().Metadata, + patch, + name, + @namespace, + fieldManager, + force, + dryRun, + cancellationToken); + /// /// Patch a given entity on the Kubernetes API by calculating the diff between the current entity and the provided entity. /// This method fetches the current entity from the API, computes the patch, and applies it. @@ -559,4 +651,17 @@ Watcher Watch( bool? allowWatchBookmarks = null, CancellationToken cancellationToken = default) where TEntity : IKubernetesObject; + + private Task PatchStatusIfChangedAsync( + V1Patch? patch, + TEntity unchanged, + CancellationToken cancellationToken) + where TEntity : IKubernetesObject => + patch is null + ? Task.FromResult(unchanged) + : PatchStatusAsync( + patch, + unchanged.Name(), + unchanged.Namespace(), + cancellationToken: cancellationToken); } diff --git a/src/KubeOps.KubernetesClient/KubernetesClient.cs b/src/KubeOps.KubernetesClient/KubernetesClient.cs index 01e8c991..bec8cfc0 100644 --- a/src/KubeOps.KubernetesClient/KubernetesClient.cs +++ b/src/KubeOps.KubernetesClient/KubernetesClient.cs @@ -248,6 +248,31 @@ public Task UpdateStatusAsync(TEntity entity, CancellationToke }; } + /// + public async Task PatchStatusAsync( + V1Patch patch, + string name, + string? @namespace = null, + string? fieldManager = null, + bool? force = null, + string? dryRun = null, + CancellationToken cancellationToken = default) + where TEntity : IKubernetesObject + { + ThrowIfDisposed(); + + return await StatusPatch.SendAsync( + ApiClient, + GetMetadata(), + patch, + name, + @namespace, + fieldManager, + force, + dryRun, + cancellationToken); + } + /// public async Task PatchAsync( V1Patch patch, diff --git a/src/KubeOps.KubernetesClient/README.md b/src/KubeOps.KubernetesClient/README.md index f2a6c630..c0bc9bc7 100644 --- a/src/KubeOps.KubernetesClient/README.md +++ b/src/KubeOps.KubernetesClient/README.md @@ -152,15 +152,17 @@ if (existingPod != null) ### Update Resource Status ```csharp -// Update the status of a custom resource +// Patch only the changed status fields, without a 409 Conflict on an outdated resourceVersion var existingCrd = await client.GetAsync("my-instance", "default"); if (existingCrd != null) { - existingCrd.Status.Message = "Processing completed"; - var updatedCrd = await client.UpdateStatusAsync(existingCrd); + var patchedCrd = await client.PatchStatusAsync(existingCrd, crd => crd.Status.Message = "Processing completed"); } ``` +`UpdateStatusAsync` replaces the whole status instead and fails with `409 Conflict` on an outdated +`resourceVersion`. See [Writing the Status](https://dotnet.github.io/dotnet-operator-sdk/docs/operator/building-blocks/controllers#writing-the-status). + ### Watch Resources ```csharp diff --git a/src/KubeOps.KubernetesClient/StatusPatch.cs b/src/KubeOps.KubernetesClient/StatusPatch.cs new file mode 100644 index 00000000..f0374efa --- /dev/null +++ b/src/KubeOps.KubernetesClient/StatusPatch.cs @@ -0,0 +1,109 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System.Text.Json.Nodes; + +using k8s; +using k8s.Models; + +using KubeOps.Abstractions.Entities; + +namespace KubeOps.KubernetesClient; + +/// +/// Builds and sends patches of the /status subresource of an entity. +/// +internal static class StatusPatch +{ + private const string Status = "status"; + + /// + /// Creates a merge patch that turns the status of into the status of + /// . It carries only the changed fields: removed fields are set to null, + /// and changed arrays are sent as a whole. + /// + /// The JSON of the entity with the original status. + /// The JSON of the entity with the desired status. + /// The merge patch, or if the status did not change. + public static V1Patch? CreateMergePatch(JsonNode? from, JsonNode? to) => + TryCreateDiff(from?[Status], to?[Status], out var status) + ? new V1Patch(new JsonObject { [Status] = status }.ToJsonString(), V1Patch.PatchType.MergePatch) + : null; + + /// + /// Sends to the /status subresource of the entity. + /// + /// The type of the entity. + /// The client to send the patch with. + /// The metadata of . + /// The patch. + /// The name of the entity. + /// The namespace of the entity, or if cluster scoped. + /// The field manager to write with. + /// Whether to force a server-side apply patch. + /// The dry run mode. + /// The token to monitor for cancellation requests. + /// The patched entity. + public static Task SendAsync( + IKubernetes apiClient, + EntityMetadata metadata, + V1Patch patch, + string name, + string? @namespace, + string? fieldManager, + bool? force, + string? dryRun, + CancellationToken cancellationToken) => + @namespace switch + { + not null => apiClient.CustomObjects.PatchNamespacedCustomObjectStatusAsync( + patch, + metadata.Group ?? string.Empty, + metadata.Version, + @namespace, + metadata.PluralName, + name, + dryRun: dryRun, + fieldManager: fieldManager, + force: force, + cancellationToken: cancellationToken), + _ => apiClient.CustomObjects.PatchClusterCustomObjectStatusAsync( + patch, + metadata.Group ?? string.Empty, + metadata.Version, + metadata.PluralName, + name, + dryRun: dryRun, + fieldManager: fieldManager, + force: force, + cancellationToken: cancellationToken), + }; + + private static bool TryCreateDiff(JsonNode? from, JsonNode? to, out JsonNode? diff) + { + if (from is not JsonObject fromObject || to is not JsonObject toObject) + { + var changed = !JsonNode.DeepEquals(from, to); + diff = changed ? to?.DeepClone() : null; + return changed; + } + + var diffObject = new JsonObject(); + foreach (var (key, _) in fromObject.Where(property => !toObject.ContainsKey(property.Key))) + { + diffObject[key] = null; + } + + foreach (var (key, toValue) in toObject) + { + if (TryCreateDiff(fromObject[key], toValue, out var valueDiff)) + { + diffObject[key] = valueDiff; + } + } + + diff = diffObject; + return diffObject.Count > 0; + } +} diff --git a/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs b/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs index abc4a677..f1255b97 100644 --- a/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs +++ b/test/KubeOps.KubernetesClient.Test/KubernetesClient.FieldManager.Test.cs @@ -2,10 +2,6 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System.Net; -using System.Text; -using System.Web; - using FluentAssertions; using k8s; @@ -21,7 +17,7 @@ public sealed class KubernetesClientFieldManagerTest : IDisposable { private static readonly KubernetesClientConfiguration Config = new() { Host = "https://kubernetes.test" }; - private readonly StubApiServer _apiServer = new(); + private readonly StubApiServer _apiServer = new() { Response = ConfigMap() }; private readonly IKubernetesClient _client; public KubernetesClientFieldManagerTest() @@ -32,22 +28,26 @@ public KubernetesClientFieldManagerTest() } [Fact] - public async Task Create_Update_UpdateStatus_And_Patch_Send_The_Field_Manager() + public async Task Create_Update_UpdateStatus_Patch_And_PatchStatus_Send_The_Field_Manager() { var cancellationToken = TestContext.Current.CancellationToken; + var patch = new V1Patch("""{"data":{"key":"value"}}""", V1Patch.PatchType.MergePatch); await _client.CreateAsync(ConfigMap(), cancellationToken); await _client.UpdateAsync(ConfigMap(), cancellationToken); await _client.UpdateStatusAsync(ConfigMap(), cancellationToken); - await _client.PatchAsync( - ConfigMap(), - new V1Patch("""{"data":{"key":"value"}}""", V1Patch.PatchType.MergePatch), + await _client.PatchAsync(ConfigMap(), patch, cancellationToken: cancellationToken); + await _client.PatchStatusAsync( + patch, + "my-config", + "default", cancellationToken: cancellationToken); - _apiServer.Requests.Should().Equal( + _apiServer.Requests.Select(r => (r.Method, r.FieldManager)).Should().Equal( ("POST", "my-operator"), ("PUT", "my-operator"), ("PUT", "my-operator"), + ("PATCH", "my-operator"), ("PATCH", "my-operator")); } @@ -61,7 +61,7 @@ await _client.PatchAsync( force: true, cancellationToken: TestContext.Current.CancellationToken); - _apiServer.Requests.Should().ContainSingle() + _apiServer.Requests.Select(r => (r.Method, r.FieldManager)).Should().ContainSingle() .Which.Should().Be(("PATCH", "server-side-apply")); } @@ -71,7 +71,8 @@ public async Task Reads_And_Deletes_Do_Not_Send_A_Field_Manager() await _client.GetAsync("my-config", "default", TestContext.Current.CancellationToken); await _client.DeleteAsync(ConfigMap(), TestContext.Current.CancellationToken); - _apiServer.Requests.Should().Equal(("GET", null), ("DELETE", null)); + _apiServer.Requests.Select(r => (r.Method, r.FieldManager)) + .Should().Equal(("GET", null), ("DELETE", null)); } [Fact] @@ -99,30 +100,4 @@ public void Constructor_With_Field_Manager_Rejects_An_Invalid_Field_Manager() ApiVersion = V1ConfigMap.KubeApiVersion, Metadata = new() { Name = "my-config", NamespaceProperty = "default" }, }; - - /// - /// Answers every request with a config map and records the method and the fieldManager it carried. - /// - private sealed class StubApiServer : DelegatingHandler - { - public List<(string Method, string? FieldManager)> Requests { get; } = []; - - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - Requests.Add(( - request.Method.Method, - HttpUtility.ParseQueryString(request.RequestUri!.Query)["fieldManager"])); - - return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - RequestMessage = request, - Content = new StringContent( - KubernetesJson.Serialize(ConfigMap()), - Encoding.UTF8, - "application/json"), - }); - } - } } diff --git a/test/KubeOps.KubernetesClient.Test/KubernetesClient.PatchStatus.Test.cs b/test/KubeOps.KubernetesClient.Test/KubernetesClient.PatchStatus.Test.cs new file mode 100644 index 00000000..55c6dab1 --- /dev/null +++ b/test/KubeOps.KubernetesClient.Test/KubernetesClient.PatchStatus.Test.cs @@ -0,0 +1,94 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using FluentAssertions; + +using k8s; +using k8s.Models; + +using KubeOps.TestHelpers; + +namespace KubeOps.KubernetesClient.Test; + +[Trait(TestTrait.Category, TestCategory.UnitTest)] +[Trait(TestTrait.Area, TestArea.KubernetesClient)] +public sealed class KubernetesClientPatchStatusTest : IDisposable +{ + private const string StatusPath = "/apis/client.test/v1/namespaces/default/statustests/my-entity/status"; + + private static readonly KubernetesClientConfiguration Config = new() { Host = "https://kubernetes.test" }; + + private readonly StubApiServer _apiServer = new() { Response = Entity() }; + private readonly IKubernetesClient _client; + + public KubernetesClientPatchStatusTest() + { + _client = new KubernetesClient(Config, new Kubernetes(Config, _apiServer)); + } + + [Fact] + public async Task PatchStatus_With_A_Change_Sends_A_Merge_Patch_Of_The_Changed_Fields_To_The_Status() + { + var entity = Entity(); + + await _client.PatchStatusAsync( + entity, + e => e.Status.Phase = "Ready", + TestContext.Current.CancellationToken); + + entity.Status.Phase.Should().Be("Ready"); + _apiServer.Requests.Should().ContainSingle().Which.Should().Match(r => + r.Method == "PATCH" + && r.Uri.PathAndQuery == StatusPath + && r.ContentType == "application/merge-patch+json" + && r.Body == """{"status":{"phase":"Ready"}}"""); + } + + [Fact] + public async Task PatchStatus_From_To_Sends_A_Merge_Patch_Of_The_Changed_Fields_To_The_Status() + { + var to = Entity(); + to.Status.Phase = "Ready"; + + await _client.PatchStatusAsync(Entity(), to, TestContext.Current.CancellationToken); + + _apiServer.Requests.Should().ContainSingle().Which.Body.Should().Be("""{"status":{"phase":"Ready"}}"""); + } + + [Fact] + public async Task PatchStatus_Without_Changes_Returns_The_Entity_Without_A_Request() + { + var entity = Entity(); + + var changed = await _client.PatchStatusAsync(entity, _ => { }, TestContext.Current.CancellationToken); + var fromTo = await _client.PatchStatusAsync(entity, Entity(), TestContext.Current.CancellationToken); + + changed.Should().BeSameAs(entity); + fromTo.Should().BeSameAs(entity); + _apiServer.Requests.Should().BeEmpty(); + } + + [Fact] + public async Task PatchStatus_With_A_Patch_Of_A_Cluster_Scoped_Entity_Uses_The_Cluster_Path() + { + await _client.PatchStatusAsync( + new V1Patch("""{"status":{"phase":"Ready"}}""", V1Patch.PatchType.ApplyPatch), + "my-entity", + fieldManager: "my-operator", + force: true, + cancellationToken: TestContext.Current.CancellationToken); + + _apiServer.Requests.Should().ContainSingle().Which.Should().Match(r => + r.Uri.PathAndQuery == "/apis/client.test/v1/statustests/my-entity/status?fieldManager=my-operator&force=true" + && r.ContentType == "application/apply-patch+yaml"); + } + + public void Dispose() => _client.Dispose(); + + private static V1StatusTestEntity Entity() => new() + { + Metadata = new() { Name = "my-entity", NamespaceProperty = "default", ResourceVersion = "1" }, + Status = new() { Phase = "Pending" }, + }; +} diff --git a/test/KubeOps.KubernetesClient.Test/StatusPatch.Test.cs b/test/KubeOps.KubernetesClient.Test/StatusPatch.Test.cs new file mode 100644 index 00000000..5f0ffd47 --- /dev/null +++ b/test/KubeOps.KubernetesClient.Test/StatusPatch.Test.cs @@ -0,0 +1,101 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using FluentAssertions; + +using k8s.Models; + +using KubeOps.Abstractions.Entities; +using KubeOps.TestHelpers; + +namespace KubeOps.KubernetesClient.Test; + +[Trait(TestTrait.Category, TestCategory.UnitTest)] +[Trait(TestTrait.Area, TestArea.KubernetesClient)] +public sealed class StatusPatchTest +{ + [Fact] + public void CreateMergePatch_Returns_Null_If_The_Status_Did_Not_Change() + { + MergePatch(Entity(), Entity()).Should().BeNull(); + } + + [Fact] + public void CreateMergePatch_Ignores_Changes_Outside_The_Status() + { + var to = Entity(); + to.Spec.Replicas = 3; + to.Metadata.Labels = new Dictionary { ["app"] = "demo" }; + to.Metadata.ResourceVersion = "42"; + + MergePatch(Entity(), to).Should().BeNull(); + } + + [Fact] + public void CreateMergePatch_Carries_Only_The_Changed_Fields() + { + var to = Entity(); + to.Status.Phase = "Ready"; + + var patch = StatusPatch.CreateMergePatch(Entity().ToNode(), to.ToNode()); + + patch.Should().NotBeNull(); + patch!.Type.Should().Be(V1Patch.PatchType.MergePatch); + patch.Content.Should().Be("""{"status":{"phase":"Ready"}}"""); + } + + [Fact] + public void CreateMergePatch_Sets_Removed_Fields_To_Null() + { + var to = Entity(); + to.Status.Message = null; + + MergePatch(Entity(), to).Should().Be("""{"status":{"message":null}}"""); + } + + [Fact] + public void CreateMergePatch_Sends_A_Changed_Array_As_A_Whole() + { + var to = Entity(); + to.Status.Conditions.Add(new() { Type = "Available", Status = "True" }); + + MergePatch(Entity(), to).Should().Be( + """{"status":{"conditions":[{"type":"Ready","status":"True"},{"type":"Available","status":"True"}]}}"""); + } + + [Fact] + public void CreateMergePatch_Recurses_Into_Nested_Objects() + { + var to = Entity(); + to.Status.Endpoint.Port = 8443; + + MergePatch(Entity(), to).Should().Be("""{"status":{"endpoint":{"port":8443}}}"""); + } + + [Fact] + public void CreateMergePatch_Sends_The_Whole_Status_If_The_Original_Has_None() + { + var from = Entity(); + from.Status = null!; + + MergePatch(from, Entity()).Should().Be( + """{"status":{"phase":"Pending","message":"Waiting","conditions":[{"type":"Ready","status":"True"}],""" + + "\"endpoint\":{\"host\":\"demo\",\"port\":443}}}"); + } + + private static object? MergePatch(V1StatusTestEntity from, V1StatusTestEntity to) => + StatusPatch.CreateMergePatch(from.ToNode(), to.ToNode())?.Content; + + private static V1StatusTestEntity Entity() => new() + { + Metadata = new() { Name = "my-entity", NamespaceProperty = "default", ResourceVersion = "1" }, + Status = new() + { + Phase = "Pending", + Message = "Waiting", + Conditions = [new() { Type = "Ready", Status = "True" }], + Endpoint = new() { Host = "demo", Port = 443 }, + }, + }; +} diff --git a/test/KubeOps.KubernetesClient.Test/StubApiServer.cs b/test/KubeOps.KubernetesClient.Test/StubApiServer.cs new file mode 100644 index 00000000..ae153029 --- /dev/null +++ b/test/KubeOps.KubernetesClient.Test/StubApiServer.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System.Net; +using System.Text; +using System.Web; + +using k8s; + +namespace KubeOps.KubernetesClient.Test; + +/// +/// Stands in for the Kubernetes API server: records every request and answers it with , +/// or with 404 without one. +/// +internal sealed class StubApiServer : DelegatingHandler +{ + public List Requests { get; } = []; + + public object? Response { get; set; } + + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + Requests.Add(new( + request.Method.Method, + request.RequestUri!, + request.Content?.Headers.ContentType?.MediaType, + request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken))); + + return Response is null + ? new HttpResponseMessage(HttpStatusCode.NotFound) { RequestMessage = request } + : new HttpResponseMessage(HttpStatusCode.OK) + { + RequestMessage = request, + Content = new StringContent(KubernetesJson.Serialize(Response), Encoding.UTF8, "application/json"), + }; + } +} + +internal sealed record StubApiRequest(string Method, Uri Uri, string? ContentType, string? Body) +{ + public string? FieldManager => HttpUtility.ParseQueryString(Uri.Query)["fieldManager"]; +} diff --git a/test/KubeOps.KubernetesClient.Test/V1StatusTestEntity.cs b/test/KubeOps.KubernetesClient.Test/V1StatusTestEntity.cs new file mode 100644 index 00000000..fa415931 --- /dev/null +++ b/test/KubeOps.KubernetesClient.Test/V1StatusTestEntity.cs @@ -0,0 +1,50 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using k8s.Models; + +using KubeOps.Abstractions.Entities; + +namespace KubeOps.KubernetesClient.Test; + +[KubernetesEntity(Group = "client.test", ApiVersion = "v1", Kind = "StatusTest", PluralName = "statustests")] +public sealed class V1StatusTestEntity + : CustomKubernetesEntity +{ + public V1StatusTestEntity() + { + ApiVersion = "client.test/v1"; + Kind = "StatusTest"; + } + + public sealed class EntitySpec + { + public int Replicas { get; set; } + } + + public sealed class EntityStatus + { + public string? Phase { get; set; } + + public string? Message { get; set; } + + public List Conditions { get; set; } = []; + + public Address Endpoint { get; set; } = new(); + } + + public sealed class Condition + { + public string Type { get; set; } = string.Empty; + + public string Status { get; set; } = string.Empty; + } + + public sealed class Address + { + public string Host { get; set; } = string.Empty; + + public int Port { get; set; } + } +} diff --git a/test/KubeOps.Operator.Test/KubernetesClient.PatchStatus.Integration.Test.cs b/test/KubeOps.Operator.Test/KubernetesClient.PatchStatus.Integration.Test.cs new file mode 100644 index 00000000..7e699dc5 --- /dev/null +++ b/test/KubeOps.Operator.Test/KubernetesClient.PatchStatus.Integration.Test.cs @@ -0,0 +1,69 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System.Net; + +using FluentAssertions; + +using k8s.Autorest; +using k8s.Models; + +using KubeOps.KubernetesClient; +using KubeOps.Operator.Test.TestEntities; + +using Microsoft.Extensions.Hosting; + +namespace KubeOps.Operator.Test; + +[Trait(TestTrait.Area, TestArea.KubernetesClient)] +public sealed class KubernetesClientPatchStatusIntegrationTest : IntegrationTestBase +{ + private readonly IKubernetesClient _client = new KubernetesClient.KubernetesClient(); + private readonly TestNamespaceProvider _ns = new(); + + [Fact] + public async Task PatchStatus_Succeeds_With_An_Outdated_Entity_Where_UpdateStatus_Conflicts() + { + var cancellationToken = TestContext.Current.CancellationToken; + var entity = await _client.CreateAsync( + new V1OperatorIntegrationTestEntity("test-entity", "username", _ns.Namespace), + cancellationToken); + var outdated = await _client.GetAsync( + entity.Name(), + entity.Namespace(), + cancellationToken); + + entity.Spec.Username = "changed"; + await _client.UpdateAsync(entity, cancellationToken); + + var update = () => _client.UpdateStatusAsync(outdated!, cancellationToken); + await update.Should().ThrowAsync() + .Where(e => e.Response.StatusCode == HttpStatusCode.Conflict); + + var patched = await _client.PatchStatusAsync( + outdated!, + e => e.Status.Status = "patched", + cancellationToken); + + patched.Status.Status.Should().Be("patched"); + patched.Spec.Username.Should().Be("changed"); + } + + public override async ValueTask InitializeAsync() + { + await base.InitializeAsync(); + await _ns.InitializeAsync(); + } + + public override async ValueTask DisposeAsync() + { + await base.DisposeAsync(); + await _ns.DisposeAsync(); + _client.Dispose(); + } + + protected override void ConfigureHost(HostApplicationBuilder builder) + { + } +}