a73x

internal/server/syncsvc/tracker.go

Ref:   Size: 1.4 KiB   History

package syncsvc

import "sync"

type vmStatus struct {
	status  string
	lastErr string
	ip      string
}

type statusTracker struct {
	mu   sync.Mutex
	last map[string]vmStatus
}

func newStatusTracker() *statusTracker {
	return &statusTracker{last: map[string]vmStatus{}}
}

func (t *statusTracker) writeThrough(vmID, status, lastErr, ip string, write func() (string, error)) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	prior, ok := t.last[vmID]
	if ok && prior.status == status && prior.lastErr == lastErr &&
		(ip == "" || ip == prior.ip) {
		return nil // unchanged — skip the write
	}
	written, err := write()
	if err != nil {
		return err // rejected — do not cache; let the next report retry
	}
	if written == "" {
		written = prior.ip
	}
	t.last[vmID] = vmStatus{status: status, lastErr: lastErr, ip: written}
	return nil
}

func (t *statusTracker) forget(vmID string) {
	t.mu.Lock()
	defer t.mu.Unlock()
	delete(t.last, vmID)
}

type netTracker struct {
	mu   sync.Mutex
	last map[string]string
}

func newNetTracker() *netTracker { return &netTracker{last: map[string]string{}} }

func (t *netTracker) writeThrough(hostID, value string, write func() error) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.last[hostID] == value {
		return nil
	}
	if err := write(); err != nil {
		return err
	}
	t.last[hostID] = value
	return nil
}

func (t *netTracker) forget(hostID string) {
	t.mu.Lock()
	defer t.mu.Unlock()
	delete(t.last, hostID)
}