cmd/ez-agent-configurator/auth_dispatch.go

package main

import (
	"context"
	"errors"
	"sync"
	"sync/atomic"
	"time"

	"github.com/gdamore/tcell/v2"
)

// tview's QueueUpdateDraw waits indefinitely after its event loop stops. Auth
// workers instead use this bounded, cancellable UI queue. A private key event
// wakes the same UI loop; pointer identity prevents it reaching any widget.
type authUIUpdate struct {
	ctx    context.Context
	update func()
	done   chan bool
	state  atomic.Int32 // queued=0, executing=1, canceled=2
}

type authUIQueue struct {
	mu      sync.Mutex
	workers sync.WaitGroup
	ctx     context.Context
	cancel  context.CancelFunc
	pending []*authUIUpdate
	screen  tcell.Screen
	wake    *tcell.EventKey
}

func newAuthUIQueue() *authUIQueue {
	ctx, cancel := context.WithCancel(context.Background())
	return &authUIQueue{ctx: ctx, cancel: cancel, wake: tcell.NewEventKey(tcell.KeyF64, 0, tcell.ModNone)}
}

func (a *ConfiguratorApp) queueAuthUpdate(ctx context.Context, update func()) bool {
	queue := a.authUI
	job := &authUIUpdate{ctx: ctx, update: update, done: make(chan bool, 1)}
	queue.mu.Lock()
	if queue.ctx.Err() != nil || ctx.Err() != nil || len(queue.pending) >= 8 {
		queue.mu.Unlock()
		return false
	}
	queue.pending = append(queue.pending, job)
	screen := queue.screen
	queue.mu.Unlock()
	if screen != nil {
		// PostEvent is nonblocking. A full terminal queue already has events
		// which will drain our updates at the next key event/draw wakeup.
		_ = screen.PostEvent(queue.wake)
	}
	select {
	case applied := <-job.done:
		return applied
	case <-ctx.Done():
		if job.state.CompareAndSwap(0, 2) {
			return false
		}
		return <-job.done
	case <-queue.ctx.Done():
		if job.state.CompareAndSwap(0, 2) {
			return false
		}
		return <-job.done
	}
}

// Only the UI event loop calls this, never the draw hook under tview's lock.
func (a *ConfiguratorApp) drainAuthUpdates() {
	queue := a.authUI
	if queue == nil {
		return
	}
	queue.mu.Lock()
	pending := queue.pending
	queue.pending = nil
	queue.mu.Unlock()
	for _, job := range pending {
		if queue.ctx.Err() != nil || job.ctx.Err() != nil {
			job.state.CompareAndSwap(0, 2)
		}
		applied := job.state.CompareAndSwap(0, 1)
		if applied {
			job.update()
		}
		job.done <- applied
	}
}

func (a *ConfiguratorApp) authBeforeDraw(screen tcell.Screen) bool {
	queue := a.authUI
	queue.mu.Lock()
	queue.screen = screen
	pending := len(queue.pending) > 0 && queue.ctx.Err() == nil
	queue.mu.Unlock()
	if pending {
		_ = screen.PostEvent(queue.wake)
	}
	return false
}

func (a *ConfiguratorApp) shutdownAuth() {
	queue := a.authUI
	if queue == nil {
		return
	}
	queue.mu.Lock()
	queue.cancel()
	pending := queue.pending
	queue.pending, queue.screen = nil, nil
	queue.mu.Unlock()
	for _, job := range pending {
		job.state.CompareAndSwap(0, 2)
		job.done <- false
	}
	for _, view := range a.viewStack {
		if view.onClose != nil {
			view.onClose()
		}
	}
}

func (a *ConfiguratorApp) stop() {
	a.shutdownAuth()
	a.app.Stop()
}

// Admission and shutdown share the queue lock so Wait cannot race a new Add.
func (a *ConfiguratorApp) startAuthWorker(work func()) bool {
	queue := a.authUI
	queue.mu.Lock()
	defer queue.mu.Unlock()
	if queue.ctx.Err() != nil {
		return false
	}
	queue.workers.Add(1)
	go func() { defer queue.workers.Done(); work() }()
	return true
}

// Call only after the event loop exits and shutdownAuth has canceled delivery.
func (a *ConfiguratorApp) waitAuthWorkers() error {
	done := make(chan struct{})
	go func() { a.authUI.workers.Wait(); close(done) }()
	select {
	case <-done:
		return nil
	case <-time.After(15 * time.Second):
		return errors.New("configurator auth cleanup did not finish before shutdown")
	}
}