github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/engine/uisession/subscriber.go (about)

     1  package uisession
     2  
     3  import (
     4  	"context"
     5  
     6  	apierrors "k8s.io/apimachinery/pkg/api/errors"
     7  	"k8s.io/apimachinery/pkg/types"
     8  	"sigs.k8s.io/controller-runtime/pkg/cache"
     9  	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
    10  
    11  	"github.com/tilt-dev/tilt/internal/controllers/apicmp"
    12  	"github.com/tilt-dev/tilt/internal/hud/webview"
    13  	"github.com/tilt-dev/tilt/internal/store"
    14  	"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
    15  )
    16  
    17  type Subscriber struct {
    18  	client ctrlclient.Client
    19  }
    20  
    21  func NewSubscriber(client ctrlclient.Client) *Subscriber {
    22  	return &Subscriber{client: client}
    23  }
    24  
    25  func (s *Subscriber) OnChange(ctx context.Context, st store.RStore, summary store.ChangeSummary) error {
    26  	if summary.IsLogOnly() {
    27  		return nil
    28  	}
    29  
    30  	state := st.RLockState()
    31  	session := webview.ToUISession(state)
    32  	st.RUnlockState()
    33  
    34  	stored := &v1alpha1.UISession{}
    35  	err := s.client.Get(ctx, types.NamespacedName{Name: session.Name}, stored)
    36  	if apierrors.IsNotFound(err) {
    37  		// If nothing is stored, create it.
    38  		err := s.client.Create(ctx, session)
    39  		if err != nil {
    40  			return err
    41  		}
    42  		return nil
    43  	} else if err != nil {
    44  		// If the cache hasn't started yet, that's OK.
    45  		// We'll get it on the next OnChange()
    46  		if _, ok := err.(*cache.ErrCacheNotStarted); ok {
    47  			return nil
    48  		}
    49  
    50  		return err
    51  	}
    52  
    53  	if !apicmp.DeepEqual(session.Status, stored.Status) {
    54  		// If the current version is different than what's stored, update it.
    55  		update := &v1alpha1.UISession{
    56  			ObjectMeta: *stored.ObjectMeta.DeepCopy(),
    57  			Spec:       *stored.Spec.DeepCopy(),
    58  			Status:     *session.Status.DeepCopy(),
    59  		}
    60  		err = s.client.Status().Update(ctx, update)
    61  		if err != nil {
    62  			return err
    63  		}
    64  	}
    65  
    66  	return nil
    67  }
    68  
    69  var _ store.Subscriber = &Subscriber{}