Skip to content
quarry Artifact [1c27628fe0]
Login

Artifact [1c27628fe0]

Artifact 1c27628fe0c421ad6a51eefbdc0a6c9c3e053debc86f851dbd24f07e6fa8ab89:


package zitcli

import (
	"context"
	"sync"
	"time"

	"craftdesign.group/quarry/internal/obs"
)

// sharedRunLimit bounds one shared run. The run belongs to no caller, so
// no request deadline ends it; the slowest listing measured is under a
// minute.
const sharedRunLimit = 5 * time.Minute

// flightGroup holds the runs in progress, by key.
type flightGroup struct {
	mu    sync.Mutex
	calls map[string]*flightCall
}

type flightCall struct {
	done chan struct{}
	val  any
	err  error
	// promote is closed when an interactive caller (one with no obs
	// reason) joins a run a background caller began: the run is then
	// admitted as interactive work. Closed at most once, under the
	// group's lock.
	promote  chan struct{}
	promoted bool
}

// shared memoises an expensive read and collapses concurrent callers for
// one key onto ONE run. lookup consults the cache and store fills it;
// both run under the group's lock so a result cannot slip between a miss
// and the registration of a run.
//
// The run uses a context tied to no caller (values kept, cancellation
// dropped, bounded by sharedRunLimit): a caller that gives up returns
// its own ctx error and the run carries on for the rest. A failed run is
// not stored, so the next caller retries.
func shared[T any](g *flightGroup, ctx context.Context, key string,
	lookup func() (T, bool), store func(T), run func(context.Context) (T, error)) (T, error) {
	var zero T
	g.mu.Lock()
	if v, ok := lookup(); ok {
		g.mu.Unlock()
		return v, nil
	}
	call, ok := g.calls[key]
	if ok && !call.promoted && obs.Reason(ctx) == "" {
		call.promoted = true
		close(call.promote)
	}
	if !ok {
		call = &flightCall{done: make(chan struct{}), promote: make(chan struct{})}
		if g.calls == nil {
			g.calls = map[string]*flightCall{}
		}
		g.calls[key] = call
		go func() {
			rctx, cancel := context.WithTimeout(context.WithValue(context.WithoutCancel(ctx), ctxPromote{}, (<-chan struct{})(call.promote)), sharedRunLimit)
			defer cancel()
			v, err := run(rctx)
			g.mu.Lock()
			delete(g.calls, key)
			if err == nil {
				store(v)
			}
			g.mu.Unlock()
			call.val, call.err = v, err
			close(call.done)
		}()
	}
	g.mu.Unlock()
	select {
	case <-call.done:
		if call.err != nil {
			return zero, call.err
		}
		return call.val.(T), nil
	case <-ctx.Done():
		return zero, ctx.Err()
	}
}

// ctxPromote carries a shared run's promote channel to admission. The
// first caller's obs reason stays on the run for attribution and decides
// its class: a warm's run waits for the background share like any warm,
// unless an interactive caller joins it, which promotes it.
type ctxPromote struct{}

func promoteOf(ctx context.Context) <-chan struct{} {
	ch, _ := ctx.Value(ctxPromote{}).(<-chan struct{})
	return ch
}