fix(api): make monitor watch versions usable as delete preconditions

A watch event triggered by a WorkloadMonitor carries the monitor's
resourceVersion, so a monitor-only status change reaches informer
handlers: client-go treats an update with an unchanged resourceVersion
as a resync and hides it from them. That version never equals the
HelmRelease's, though, so a delete with it as a precondition always
failed, and its spec came from the informer cache, which can lag behind
the monitor revision.

The event now builds the Application from a release no older than the
monitor revision and carries the newer of the two versions. HelmReleases
and WorkloadMonitors are stored in the same etcd, so their versions are
revisions of one sequence, and a value this API hands out that is newer
than the live release names the current spec. A resourceVersion
precondition on delete is therefore checked against the live release and
only an older one is a conflict; the delete itself then carries the live
version.

The two backing watches are not ordered, so a monitor event can be
processed after a release event that is newer than the monitor, and a
resumed watch can replay a monitor before the release the client already
holds. When the event would carry the version the client may hold, which
without anything sent for the object yet means any release version, it
falls back to the monitor's own version and the object's version steps
back. A delete with that version from the client's cache gets a conflict
until the object's next release event or monitor change; no write is
lost.

The release is read live when the cache does not have it or has one
older than the monitor revision; otherwise the cached release already
pairs its spec with its own version. A watch start replays every
existing monitor as ADDED, so a watch that starts or reconnects reads
live once for each monitor written after its release last changed, and
each later monitor status change costs at most one read per open watch.

Fixes: 1bae0775be ("feat(application): add WorkloadsReady condition and Events tab")
Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
Aleksei Sviridkin committed 2026-11-13 20:11:48 +03:00
1 parent f61cfdf0b8
commit f13362b0ee
3 files changed
+552 -13

No files matched your search

+107 -11
View File
@@ -19,6 +19,7 @@ package application
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"maps" "maps"
"net/http" "net/http"
@@ -673,9 +674,20 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
// Construct HelmRelease name with the configured prefix // Construct HelmRelease name with the configured prefix
helmReleaseName := r.releaseConfig.Prefix + name helmReleaseName := r.releaseConfig.Prefix + name
// A resourceVersion precondition is judged against the live release, so
// read it uncached.
var callerRV *string
if options != nil && options.Preconditions != nil {
callerRV = options.Preconditions.ResourceVersion
}
reader := client.Reader(r.c)
if callerRV != nil {
reader = r.w
}
// Retrieve the HelmRelease before attempting to delete // Retrieve the HelmRelease before attempting to delete
helmRelease := &helmv2.HelmRelease{} helmRelease := &helmv2.HelmRelease{}
err = r.c.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}}) err = reader.Get(ctx, client.ObjectKey{Namespace: namespace, Name: helmReleaseName}, helmRelease, &client.GetOptions{Raw: &metav1.GetOptions{}})
if err != nil { if err != nil {
if apierrors.IsNotFound(err) { if apierrors.IsNotFound(err) {
// If HelmRelease does not exist, return NotFound error for Application // If HelmRelease does not exist, return NotFound error for Application
@@ -694,6 +706,15 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name) return nil, false, apierrors.NewNotFound(r.gvr.GroupResource(), name)
} }
if callerRV != nil {
if err := r.checkResourceVersion(name, *callerRV, helmRelease.ResourceVersion); err != nil {
return nil, false, err
}
options = options.DeepCopy()
liveRV := helmRelease.ResourceVersion
options.Preconditions.ResourceVersion = &liveRV
}
// Run the genericapiserver-supplied admission chain (validating webhooks // Run the genericapiserver-supplied admission chain (validating webhooks
// and ValidatingAdmissionPolicies) on the resolved Application before // and ValidatingAdmissionPolicies) on the resolved Application before
// removing the underlying HelmRelease. Custom REST handlers must invoke // removing the underlying HelmRelease. Custom REST handlers must invoke
@@ -723,6 +744,39 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
return nil, true, nil return nil, true, nil
} }
// checkResourceVersion applies a caller's resourceVersion precondition to the
// live HelmRelease. Every resourceVersion is a revision of the same etcd. An
// Application carries the version of the release its spec came from or, on a
// WorkloadMonitor-triggered watch event, a monitor revision, which is newer
// than that release only when the release was read at or after it. A value
// newer than the live release therefore names the current spec, and only an
// older one is a conflict.
func (r *REST) checkResourceVersion(name, callerRV, liveRV string) error {
caller, err := strconv.ParseUint(callerRV, 10, 64)
if err != nil {
return apierrors.NewBadRequest(fmt.Sprintf("invalid resourceVersion %q: %v", callerRV, err))
}
live, err := strconv.ParseUint(liveRV, 10, 64)
if err != nil {
return fmt.Errorf("HelmRelease for %s has an invalid resourceVersion %q: %w", name, liveRV, err)
}
if caller < live {
return apierrors.NewConflict(r.gvr.GroupResource(), name, errors.New("the object has been modified; please apply your changes to the latest version and try again"))
}
return nil
}
// newerResourceVersion returns whichever of two numeric resourceVersions is
// higher, preferring b when either does not parse.
func newerResourceVersion(a, b string) string {
av, aErr := strconv.ParseUint(a, 10, 64)
bv, bErr := strconv.ParseUint(b, 10, 64)
if aErr != nil || bErr != nil || bv >= av {
return b
}
return a
}
// Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications // Watch sets up a watch on HelmReleases, filters them based on application labels, and converts events to Applications
func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) { func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {
namespace, err := r.getNamespace(ctx) namespace, err := r.getNamespace(ctx)
@@ -871,7 +925,12 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
// workload whose status flips during the snapshot window (after the // workload whose status flips during the snapshot window (after the
// Application ADDED but before the bookmark) and then stops changing // Application ADDED but before the bookmark) and then stops changing
// would leave the client with a stale WorkloadsReady forever. // would leave the client with a stale WorkloadsReady forever.
var pendingWMEvents []watch.Event type monitorEvent struct {
event watch.Event
monitorRV string
releaseRV string
}
var pendingWMEvents []monitorEvent
// Get the starting resourceVersion from options // Get the starting resourceVersion from options
// If client provides resourceVersion (e.g., from a previous List), we should skip // If client provides resourceVersion (e.g., from a previous List), we should skip
@@ -895,9 +954,38 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
} }
} }
// lastSent holds, per Application, the resourceVersion of the last
// event this watch sent.
lastSent := map[client.ObjectKey]string{}
remember := func(app *appsv1alpha1.Application, eventType watch.EventType) {
key := client.ObjectKey{Namespace: app.Namespace, Name: app.Name}
if eventType == watch.Deleted {
delete(lastSent, key)
return
}
lastSent[key] = app.ResourceVersion
}
// sendMonitorEvent falls back to the monitor's own resourceVersion
// when the event might repeat the one the client already holds, which
// a shared informer hides from its handlers. Without an entry for the
// object, a client resuming this watch may hold any release version,
// so the release's own version counts as held. The object the client
// caches from a fallback event gets a conflict on a precondition-checked
// delete until its next event.
sendMonitorEvent := func(me monitorEvent) bool {
app := me.event.Object.(*appsv1alpha1.Application)
last, known := lastSent[client.ObjectKey{Namespace: app.Namespace, Name: app.Name}]
if (known && app.ResourceVersion == last) || (!known && app.ResourceVersion == me.releaseRV) {
app.SetResourceVersion(me.monitorRV)
}
remember(app, me.event.Type)
return send(me.event)
}
drainPendingWMEvents := func() bool { drainPendingWMEvents := func() bool {
for _, ev := range pendingWMEvents { for _, ev := range pendingWMEvents {
if !send(ev) { if !sendMonitorEvent(ev) {
return false return false
} }
} }
@@ -1012,6 +1100,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
// When startingRV == 0, always send ADDED events (client wants full state) // When startingRV == 0, always send ADDED events (client wants full state)
// Send event to custom watcher // Send event to custom watcher
remember(&app, event.Type)
if !send(watch.Event{Type: event.Type, Object: &app}) { if !send(watch.Event{Type: event.Type, Object: &app}) {
return return
} }
@@ -1070,10 +1159,19 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
} else if !fieldFilter.MatchesNamespace(hrNS) { } else if !fieldFilter.MatchesNamespace(hrNS) {
continue continue
} }
// The event's resourceVersion may be the monitor's, which a
// Delete precondition accepts as current while the release has
// not moved past it. A cached release older than the monitor
// revision could pair a stale spec with that version, so only
// then is the release read live.
hrKey := client.ObjectKey{Namespace: hrNS, Name: hrName}
hr := &helmv2.HelmRelease{} hr := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, client.ObjectKey{Namespace: hrNS, Name: hrName}, hr); err != nil { if err := r.c.Get(ctx, hrKey, hr); err != nil || newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()) != hr.GetResourceVersion() {
klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err) hr = &helmv2.HelmRelease{}
continue if err := r.w.Get(ctx, hrKey, hr); err != nil {
klog.V(4).Infof("Cannot find HelmRelease %s/%s for WorkloadMonitor event: %v", hrNS, hrName, err)
continue
}
} }
// Pass the fresh WorkloadMonitor so conversion uses the latest // Pass the fresh WorkloadMonitor so conversion uses the latest
// operational status even if the cache (r.c) has not yet // operational status even if the cache (r.c) has not yet
@@ -1094,10 +1192,8 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
continue continue
} }
} }
// Use the WorkloadMonitor's ResourceVersion for the emitted event app.SetResourceVersion(newerResourceVersion(wm.GetResourceVersion(), hr.GetResourceVersion()))
// so clients see a monotonically increasing RV and don't skip this update. outEvent := monitorEvent{event: watch.Event{Type: watch.Modified, Object: &app}, monitorRV: wm.GetResourceVersion(), releaseRV: hr.GetResourceVersion()}
app.SetResourceVersion(wm.GetResourceVersion())
outEvent := watch.Event{Type: watch.Modified, Object: &app}
// Buffer WM-triggered events that arrive before the // Buffer WM-triggered events that arrive before the
// initial-events-end bookmark. They will be replayed in order // initial-events-end bookmark. They will be replayed in order
// immediately after the bookmark is emitted. // immediately after the bookmark is emitted.
@@ -1106,7 +1202,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
continue continue
} }
bookmarker.Observe(wm.GetResourceVersion()) bookmarker.Observe(wm.GetResourceVersion())
if !send(outEvent) { if !sendMonitorEvent(outEvent) {
return return
} }
@@ -0,0 +1,441 @@
package application
import (
"context"
"encoding/json"
"strconv"
"testing"
"time"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/endpoints/request"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)
// rvWatchFixture models the two clients REST uses: c reads from an informer
// cache and writes to the API server, w talks to the API server directly.
// The cache can be left behind the live release, and the HelmRelease and
// WorkloadMonitor watches are fake watchers the test drives.
type rvWatchFixture struct {
rest *REST
cache client.Client
live client.WithWatch
hrW *watch.FakeWatcher
wmW *watch.FakeWatcher
// liveReleaseGets counts HelmRelease reads that bypass the cache. The
// watch goroutine and the test both update it; receiving an event from
// the watch orders the watch's updates before the test's next access.
liveReleaseGets int
}
var rvReleaseKey = client.ObjectKey{Namespace: "default", Name: "postgresql-mydb"}
func newRVWatchFixture(t *testing.T) *rvWatchFixture {
t.Helper()
scheme := runtime.NewScheme()
if err := cozyv1alpha1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
if err := helmv2.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
release := func() *helmv2.HelmRelease {
return &helmv2.HelmRelease{
ObjectMeta: metav1.ObjectMeta{
Name: rvReleaseKey.Name,
Namespace: rvReleaseKey.Namespace,
Labels: map[string]string{
ApplicationKindLabel: "PostgreSQL",
ApplicationGroupLabel: appsv1alpha1.GroupName,
ApplicationNameLabel: "mydb",
},
},
Spec: helmv2.HelmReleaseSpec{Values: &apiextensionsv1.JSON{Raw: []byte(`{"marker":"cached"}`)}},
}
}
f := &rvWatchFixture{hrW: watch.NewFake(), wmW: watch.NewFake()}
liveStore := fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build()
f.live = interceptor.NewClient(liveStore, interceptor.Funcs{
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
if _, ok := obj.(*helmv2.HelmRelease); ok {
f.liveReleaseGets++
}
return c.Get(ctx, key, obj, opts...)
},
Watch: func(_ context.Context, _ client.WithWatch, list client.ObjectList, _ ...client.ListOption) (watch.Interface, error) {
if _, ok := list.(*cozyv1alpha1.WorkloadMonitorList); ok {
return f.wmW, nil
}
return f.hrW, nil
},
})
f.cache = interceptor.NewClient(fake.NewClientBuilder().WithScheme(scheme).WithObjects(release()).Build(), interceptor.Funcs{
Delete: func(ctx context.Context, _ client.WithWatch, obj client.Object, opts ...client.DeleteOption) error {
return liveStore.Delete(ctx, obj, opts...)
},
})
f.rest = NewREST(f.cache, f.live, &config.Resource{
Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"},
Release: config.ReleaseConfig{Prefix: "postgresql-"},
})
return f
}
func (f *rvWatchFixture) liveRelease(t *testing.T) *helmv2.HelmRelease {
t.Helper()
hr := &helmv2.HelmRelease{}
if err := f.live.Get(context.Background(), rvReleaseKey, hr); err != nil {
t.Fatal(err)
}
return hr
}
// advanceLive writes a new spec to the live release only, leaving the cache
// one version behind, and returns the new live release.
func (f *rvWatchFixture) advanceLive(t *testing.T, marker string) *helmv2.HelmRelease {
t.Helper()
hr := f.liveRelease(t)
before := hr.ResourceVersion
hr.Spec.Values = &apiextensionsv1.JSON{Raw: []byte(`{"marker":"` + marker + `"}`)}
if err := f.live.Update(context.Background(), hr); err != nil {
t.Fatal(err)
}
if hr.ResourceVersion == before {
t.Fatal("fake client did not advance the release version")
}
return hr
}
func (f *rvWatchFixture) monitorEvent(rv string) {
f.wmW.Modify(&cozyv1alpha1.WorkloadMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: "mon-1",
Namespace: "default",
ResourceVersion: rv,
Labels: map[string]string{
appsv1alpha1.ApplicationKindLabel: "PostgreSQL",
appsv1alpha1.ApplicationGroupLabel: appsv1alpha1.GroupName,
appsv1alpha1.ApplicationNameLabel: "mydb",
},
},
Status: cozyv1alpha1.WorkloadMonitorStatus{Operational: new(true)},
})
}
func startRVWatch(t *testing.T, f *rvWatchFixture) (context.Context, watch.Interface) {
t.Helper()
ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default"))
t.Cleanup(cancel)
w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(w.Stop)
return ctx, w
}
func nextApplication(t *testing.T, w watch.Interface) *appsv1alpha1.Application {
t.Helper()
select {
case ev, ok := <-w.ResultChan():
if !ok {
t.Fatal("watch closed")
}
app, ok := ev.Object.(*appsv1alpha1.Application)
if !ok {
t.Fatalf("got %s %T, want an Application", ev.Type, ev.Object)
}
return app
case <-time.After(5 * time.Second):
t.Fatal("no event")
}
return nil
}
func specMarker(t *testing.T, app *appsv1alpha1.Application) string {
t.Helper()
var v struct {
Marker string `json:"marker"`
}
if app.Spec == nil {
t.Fatal("application has no spec")
}
if err := json.Unmarshal(app.Spec.Raw, &v); err != nil {
t.Fatal(err)
}
return v.Marker
}
func rvNumber(t *testing.T, rv string) uint64 {
t.Helper()
n, err := strconv.ParseUint(rv, 10, 64)
if err != nil {
t.Fatalf("resourceVersion %q: %v", rv, err)
}
return n
}
// The spec in a monitor-triggered event must come from a release read no
// earlier than the monitor revision the event carries, or a precondition on
// that version would accept a write built on a stale spec.
func TestWatchMonitorEventReadsReleaseLive(t *testing.T) {
f := newRVWatchFixture(t)
_, w := startRVWatch(t, f)
f.advanceLive(t, "live")
f.monitorEvent("5000")
app := nextApplication(t, w)
if got := specMarker(t, app); got != "live" {
t.Fatalf("spec marker %q, want the live release's", got)
}
if app.ResourceVersion != "5000" {
t.Fatalf("resourceVersion %q, want the monitor's 5000", app.ResourceVersion)
}
if f.liveReleaseGets != 2 {
t.Fatalf("%d live release reads, want the test's own plus one for the event", f.liveReleaseGets)
}
}
// A release cached at or past the monitor revision already pairs its spec
// with its own version, so the event uses it without a live read: a watch
// replays every existing monitor as ADDED when it starts. With nothing sent
// for the object yet, the client may hold that release version, so the event
// carries the monitor's.
func TestWatchMonitorEventUsesCacheNotOlderThanMonitor(t *testing.T) {
f := newRVWatchFixture(t)
_, w := startRVWatch(t, f)
cached := &helmv2.HelmRelease{}
if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil {
t.Fatal(err)
}
f.advanceLive(t, "live")
gets := f.liveReleaseGets
f.monitorEvent("1")
app := nextApplication(t, w)
if got := specMarker(t, app); got != "cached" {
t.Fatalf("spec marker %q, want the cached release's", got)
}
if app.ResourceVersion != "1" {
t.Fatalf("resourceVersion %q, want the monitor's 1 rather than the cached release's %q", app.ResourceVersion, cached.ResourceVersion)
}
if f.liveReleaseGets != gets {
t.Fatalf("%d live release reads for a monitor older than the cached release, want none", f.liveReleaseGets-gets)
}
}
// Shared informers deliver an update whose resourceVersion equals the stored
// one only to handlers due for a resync, so each monitor-only change must
// arrive with a resourceVersion different from the previous event's.
func TestWatchMonitorOnlyChangeAdvancesVersion(t *testing.T) {
f := newRVWatchFixture(t)
_, w := startRVWatch(t, f)
live := f.advanceLive(t, "live")
f.hrW.Modify(live.DeepCopy())
prev := rvNumber(t, nextApplication(t, w).ResourceVersion)
for _, rv := range []string{"5000", "5001"} {
f.monitorEvent(rv)
got := rvNumber(t, nextApplication(t, w).ResourceVersion)
if got <= prev {
t.Fatalf("monitor event resourceVersion %d, want above the previous event's %d", got, prev)
}
prev = got
}
}
// A monitor event processed after the release event it predates must not
// repeat the resourceVersion the client already holds, or a shared informer
// hides it from its handlers. It falls back to the monitor's older version,
// and a delete with that version gets a conflict instead of acting on a spec
// the client may not have.
func TestWatchLateMonitorEventDoesNotRepeatVersion(t *testing.T) {
f := newRVWatchFixture(t)
ctx, w := startRVWatch(t, f)
live := f.liveRelease(t)
f.hrW.Modify(live.DeepCopy())
if got := nextApplication(t, w).ResourceVersion; got != live.ResourceVersion {
t.Fatalf("release event resourceVersion %q, want %q", got, live.ResourceVersion)
}
f.monitorEvent("1")
rv := nextApplication(t, w).ResourceVersion
if rv != "1" {
t.Fatalf("late monitor event resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion)
}
_, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}})
if !apierrors.IsConflict(err) {
t.Fatalf("delete with the monitor's older version: got %v, want Conflict", err)
}
}
// A release the client already holds is skipped on a resumed watch, so the
// next monitor event must not repeat its version either.
func TestWatchLateMonitorEventAfterSkippedReplay(t *testing.T) {
f := newRVWatchFixture(t)
live := f.liveRelease(t)
w := startRVWatchFrom(t, f, live.ResourceVersion)
f.hrW.Add(live.DeepCopy())
f.monitorEvent("1")
if rv := nextApplication(t, w).ResourceVersion; rv != "1" {
t.Fatalf("monitor event after the skipped replay has resourceVersion %q, want the monitor's 1 rather than the held %q", rv, live.ResourceVersion)
}
}
// Once this watch has sent the object a monitor version, the release version
// is no longer what the client holds, and the event can carry it.
func TestWatchMonitorEventCarriesReleaseAfterFallback(t *testing.T) {
f := newRVWatchFixture(t)
_, w := startRVWatch(t, f)
live := f.liveRelease(t)
f.monitorEvent("1")
if rv := nextApplication(t, w).ResourceVersion; rv != "1" {
t.Fatalf("first monitor event resourceVersion %q, want the monitor's 1", rv)
}
f.monitorEvent("2")
if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion {
t.Fatalf("second monitor event resourceVersion %q, want the release's %q", rv, live.ResourceVersion)
}
}
// A release event in between makes the release version the held one again.
func TestWatchReleaseEventResetsHeldVersion(t *testing.T) {
f := newRVWatchFixture(t)
_, w := startRVWatch(t, f)
live := f.liveRelease(t)
f.monitorEvent("1")
nextApplication(t, w)
f.hrW.Modify(live.DeepCopy())
if rv := nextApplication(t, w).ResourceVersion; rv != live.ResourceVersion {
t.Fatalf("release event resourceVersion %q, want %q", rv, live.ResourceVersion)
}
f.monitorEvent("2")
if rv := nextApplication(t, w).ResourceVersion; rv != "2" {
t.Fatalf("monitor event after the release event has resourceVersion %q, want the monitor's 2 rather than the held %q", rv, live.ResourceVersion)
}
}
func startRVWatchFrom(t *testing.T, f *rvWatchFixture, resourceVersion string) watch.Interface {
t.Helper()
ctx, cancel := context.WithCancel(request.WithNamespace(context.Background(), "default"))
t.Cleanup(cancel)
w, err := f.rest.Watch(ctx, &metainternalversion.ListOptions{ResourceVersion: resourceVersion})
if err != nil {
t.Fatal(err)
}
t.Cleanup(w.Stop)
return w
}
// On a resumed watch the replayed monitor can arrive before the replayed
// release, so nothing is known yet about the version the client holds.
func TestWatchResumedMonitorReplayBeforeRelease(t *testing.T) {
f := newRVWatchFixture(t)
live := f.liveRelease(t)
w := startRVWatchFrom(t, f, live.ResourceVersion)
f.monitorEvent("1")
if rv := nextApplication(t, w).ResourceVersion; rv != "1" {
t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion)
}
}
// A fallback event steps the client's resume point below versions it holds,
// so a resumed client can hold a release version above the one it resumes
// from.
func TestWatchResumedBelowHeldReleaseVersion(t *testing.T) {
f := newRVWatchFixture(t)
live := f.liveRelease(t)
if rvNumber(t, live.ResourceVersion) <= 500 {
t.Fatalf("fixture release version %q must be above the resume point", live.ResourceVersion)
}
w := startRVWatchFrom(t, f, "500")
f.monitorEvent("1")
if rv := nextApplication(t, w).ResourceVersion; rv != "1" {
t.Fatalf("replayed monitor event has resourceVersion %q, want the monitor's 1 rather than the possibly held %q", rv, live.ResourceVersion)
}
}
func TestDeleteWithVersionFromMonitorEvent(t *testing.T) {
f := newRVWatchFixture(t)
ctx, w := startRVWatch(t, f)
f.advanceLive(t, "live")
f.monitorEvent("5000")
rv := nextApplication(t, w).ResourceVersion
_, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}})
if err != nil {
t.Fatalf("delete with resourceVersion %q from the watch event: %v", rv, err)
}
if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) {
t.Fatalf("release still present after delete: %v", err)
}
}
func TestDeleteRejectsVersionOlderThanLive(t *testing.T) {
f := newRVWatchFixture(t)
cached := &helmv2.HelmRelease{}
if err := f.cache.Get(context.Background(), rvReleaseKey, cached); err != nil {
t.Fatal(err)
}
f.advanceLive(t, "live")
ctx := request.WithNamespace(context.Background(), "default")
rv := cached.ResourceVersion
_, _, err := f.rest.Delete(ctx, "mydb", nil, &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{ResourceVersion: &rv}})
if !apierrors.IsConflict(err) {
t.Fatalf("delete with stale resourceVersion %q: got %v, want Conflict", rv, err)
}
if err := f.live.Get(context.Background(), rvReleaseKey, &helmv2.HelmRelease{}); err != nil {
t.Fatalf("release gone after a rejected delete: %v", err)
}
}
func TestCheckResourceVersion(t *testing.T) {
r := newTestRESTWithSchemesFromClient(nil)
for _, tc := range []struct {
caller string
check func(error) bool
}{
{"100", func(err error) bool { return err == nil }},
{"101", func(err error) bool { return err == nil }},
{"99", apierrors.IsConflict},
{"0", apierrors.IsConflict},
{"", apierrors.IsBadRequest},
{"abc", apierrors.IsBadRequest},
} {
if err := r.checkResourceVersion("mydb", tc.caller, "100"); !tc.check(err) {
t.Errorf("caller resourceVersion %q against live 100: unexpected result %v", tc.caller, err)
}
}
}
func TestNewerResourceVersion(t *testing.T) {
for _, tc := range []struct{ a, b, want string }{
{"7", "5", "7"},
{"5", "7", "7"},
{"7", "7", "7"},
{"x", "5", "5"},
{"7", "y", "y"},
} {
if got := newerResourceVersion(tc.a, tc.b); got != tc.want {
t.Errorf("newerResourceVersion(%q, %q) = %q, want %q", tc.a, tc.b, got, tc.want)
}
}
}
@@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client
WithObjects(objects...). WithObjects(objects...).
WithInterceptorFuncs(funcs). WithInterceptorFuncs(funcs).
Build() Build()
return NewREST(c, nil, &config.Resource{ return NewREST(c, c, &config.Resource{
Application: config.ApplicationConfig{ Application: config.ApplicationConfig{
Kind: "PostgreSQL", Kind: "PostgreSQL",
Plural: "postgresqls", Plural: "postgresqls",
@@ -185,7 +185,9 @@ func TestDeletePropagatesWriteOptions(t *testing.T) {
grace := int64(3) grace := int64(3)
propagation := metav1.DeletePropagationForeground propagation := metav1.DeletePropagationForeground
uid := types.UID("expected-uid") uid := types.UID("expected-uid")
rv := "17" // The version the fake client stamps on seeded objects: a resourceVersion
// precondition is checked against the live release.
rv := "999"
want := &metav1.DeleteOptions{ want := &metav1.DeleteOptions{
GracePeriodSeconds: &grace, GracePeriodSeconds: &grace,
Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv}, Preconditions: &metav1.Preconditions{UID: &uid, ResourceVersion: &rv},