|
| 1 | +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package controllers |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "strings" |
| 9 | + "sync" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/stretchr/testify/assert" |
| 13 | + "github.com/stretchr/testify/require" |
| 14 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 15 | + "k8s.io/apimachinery/pkg/types" |
| 16 | + ctrl "sigs.k8s.io/controller-runtime" |
| 17 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 18 | + "sigs.k8s.io/controller-runtime/pkg/client/fake" |
| 19 | + |
| 20 | + mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1" |
| 21 | + "github.com/stacklok/toolhive/pkg/container/kubernetes" |
| 22 | +) |
| 23 | + |
| 24 | +// patchRecordingClient wraps a client.Client and records the marshaled body |
| 25 | +// of every Patch call. Tests use it to assert the wire-level flavor of a |
| 26 | +// patch — in particular, an optimistic-lock merge patch stamps the |
| 27 | +// resourceVersion into the body, so its presence in the recorded body is a |
| 28 | +// deterministic signal that MergeFromWithOptimisticLock was in effect. |
| 29 | +// |
| 30 | +// Patches issued via .Status().Patch do not pass through this wrapper: |
| 31 | +// controller-runtime's subresource client is obtained from the embedded |
| 32 | +// client.Client and has its own Patch implementation, so the recorder only |
| 33 | +// observes spec/metadata patches on the root client. |
| 34 | +type patchRecordingClient struct { |
| 35 | + client.Client |
| 36 | + mu sync.Mutex |
| 37 | + patches []recordedPatch |
| 38 | +} |
| 39 | + |
| 40 | +type recordedPatch struct { |
| 41 | + obj client.Object |
| 42 | + body string |
| 43 | +} |
| 44 | + |
| 45 | +func (c *patchRecordingClient) Patch( |
| 46 | + ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption, |
| 47 | +) error { |
| 48 | + // err ignored: patch.Data is json.Marshal of a typed MCPServer, which |
| 49 | + // has no channels/funcs/cyclic pointers and cannot fail in practice. |
| 50 | + // A failure here would also break the production controller's own |
| 51 | + // Patch call and fire other assertions before this one. |
| 52 | + if data, err := patch.Data(obj); err == nil { |
| 53 | + c.mu.Lock() |
| 54 | + c.patches = append(c.patches, recordedPatch{ |
| 55 | + obj: obj.DeepCopyObject().(client.Object), |
| 56 | + body: string(data), |
| 57 | + }) |
| 58 | + c.mu.Unlock() |
| 59 | + } |
| 60 | + return c.Client.Patch(ctx, obj, patch, opts...) |
| 61 | +} |
| 62 | + |
| 63 | +// lastMCPServerPatchBody returns the body of the most recent recorded |
| 64 | +// Patch call whose target was an *mcpv1beta1.MCPServer. Returns empty |
| 65 | +// string if none was recorded. |
| 66 | +func (c *patchRecordingClient) lastMCPServerPatchBody() string { |
| 67 | + c.mu.Lock() |
| 68 | + defer c.mu.Unlock() |
| 69 | + for i := len(c.patches) - 1; i >= 0; i-- { |
| 70 | + if _, ok := c.patches[i].obj.(*mcpv1beta1.MCPServer); ok { |
| 71 | + return c.patches[i].body |
| 72 | + } |
| 73 | + } |
| 74 | + return "" |
| 75 | +} |
| 76 | + |
| 77 | +// TestMCPServerSpecPatchesAreOptimisticLock asserts that each of the three |
| 78 | +// MCPServer spec Patch call sites introduced in #4767 emits a merge-patch |
| 79 | +// whose body carries the resourceVersion precondition. A regression from |
| 80 | +// client.MergeFromWithOptions(orig, client.MergeFromWithOptimisticLock{}) |
| 81 | +// to plain client.MergeFrom(orig) would drop the precondition and fail |
| 82 | +// these assertions, independent of whether the higher-level field- |
| 83 | +// clobber survival test still passes. |
| 84 | +func TestMCPServerSpecPatchesAreOptimisticLock(t *testing.T) { |
| 85 | + t.Parallel() |
| 86 | + |
| 87 | + const namespace = "default" |
| 88 | + |
| 89 | + tests := []struct { |
| 90 | + name string |
| 91 | + // seed returns the MCPServer fixture placed in the fake client |
| 92 | + // before the action runs. Returning a distinct name per case |
| 93 | + // keeps parallel subtests from colliding on the shared fake. |
| 94 | + seed func() *mcpv1beta1.MCPServer |
| 95 | + // action triggers the reconcile path that should emit the |
| 96 | + // optimistic-lock Patch under test. It is invoked with a |
| 97 | + // recorder-backed reconciler. |
| 98 | + action func(t *testing.T, r *MCPServerReconciler, key types.NamespacedName) |
| 99 | + }{ |
| 100 | + { |
| 101 | + name: "AddFinalizer", |
| 102 | + seed: func() *mcpv1beta1.MCPServer { |
| 103 | + s := createTestMCPServer("optlock-add", namespace) |
| 104 | + // No finalizer yet — Reconcile should add it. |
| 105 | + return s |
| 106 | + }, |
| 107 | + action: func(t *testing.T, r *MCPServerReconciler, key types.NamespacedName) { |
| 108 | + t.Helper() |
| 109 | + _, _ = r.Reconcile(context.TODO(), ctrl.Request{NamespacedName: key}) |
| 110 | + }, |
| 111 | + }, |
| 112 | + { |
| 113 | + name: "RemoveFinalizer", |
| 114 | + seed: func() *mcpv1beta1.MCPServer { |
| 115 | + s := createTestMCPServer("optlock-remove", namespace) |
| 116 | + s.Finalizers = []string{MCPServerFinalizerName} |
| 117 | + // DeletionTimestamp forces Reconcile into the |
| 118 | + // finalize branch. The fake client accepts an |
| 119 | + // already-set timestamp on created objects. |
| 120 | + now := metav1.Now() |
| 121 | + s.DeletionTimestamp = &now |
| 122 | + return s |
| 123 | + }, |
| 124 | + action: func(t *testing.T, r *MCPServerReconciler, key types.NamespacedName) { |
| 125 | + t.Helper() |
| 126 | + _, _ = r.Reconcile(context.TODO(), ctrl.Request{NamespacedName: key}) |
| 127 | + }, |
| 128 | + }, |
| 129 | + { |
| 130 | + name: "RestartAnnotation", |
| 131 | + seed: func() *mcpv1beta1.MCPServer { |
| 132 | + s := createTestMCPServer("optlock-restart", namespace) |
| 133 | + s.Finalizers = []string{MCPServerFinalizerName} |
| 134 | + if s.Annotations == nil { |
| 135 | + s.Annotations = map[string]string{} |
| 136 | + } |
| 137 | + s.Annotations[RestartedAtAnnotationKey] = "2026-01-01T00:00:00Z" |
| 138 | + s.Annotations[RestartStrategyAnnotationKey] = "immediate" |
| 139 | + return s |
| 140 | + }, |
| 141 | + action: func(t *testing.T, r *MCPServerReconciler, key types.NamespacedName) { |
| 142 | + t.Helper() |
| 143 | + got := &mcpv1beta1.MCPServer{} |
| 144 | + require.NoError(t, r.Get(context.TODO(), key, got)) |
| 145 | + // handleRestartAnnotation is the innermost |
| 146 | + // function that issues the Patch under test; |
| 147 | + // calling it directly avoids exercising the |
| 148 | + // rest of Reconcile, which would issue many |
| 149 | + // unrelated writes. |
| 150 | + _, _ = r.handleRestartAnnotation(context.TODO(), got) |
| 151 | + }, |
| 152 | + }, |
| 153 | + } |
| 154 | + |
| 155 | + for _, tc := range tests { |
| 156 | + t.Run(tc.name, func(t *testing.T) { |
| 157 | + t.Parallel() |
| 158 | + |
| 159 | + seeded := tc.seed() |
| 160 | + testScheme := createTestScheme() |
| 161 | + fakeClient := fake.NewClientBuilder(). |
| 162 | + WithScheme(testScheme). |
| 163 | + WithObjects(seeded). |
| 164 | + WithStatusSubresource(&mcpv1beta1.MCPServer{}). |
| 165 | + Build() |
| 166 | + recorder := &patchRecordingClient{Client: fakeClient} |
| 167 | + reconciler := newTestMCPServerReconciler( |
| 168 | + recorder, testScheme, kubernetes.PlatformKubernetes) |
| 169 | + |
| 170 | + tc.action(t, reconciler, types.NamespacedName{ |
| 171 | + Name: seeded.Name, |
| 172 | + Namespace: namespace, |
| 173 | + }) |
| 174 | + |
| 175 | + body := recorder.lastMCPServerPatchBody() |
| 176 | + require.NotEmpty(t, body, |
| 177 | + "no MCPServer Patch was recorded; the reconcile path did not emit the expected write") |
| 178 | + assert.True(t, |
| 179 | + strings.Contains(body, `"resourceVersion"`), |
| 180 | + "MCPServer spec patch body did not include a resourceVersion precondition; "+ |
| 181 | + "MergeFromWithOptimisticLock regression? body=%s", body) |
| 182 | + }) |
| 183 | + } |
| 184 | +} |
0 commit comments