package zitcli
import (
"context"
"sync"
"time"
)
// 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
}
// 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 = &flightCall{done: make(chan struct{})}
if g.calls == nil {
g.calls = map[string]*flightCall{}
}
g.calls[key] = call
go func() {
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 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()
}
}