Skip to content
quarry Artifact [6e3e67755e]
Login

Artifact [6e3e67755e]

Artifact 6e3e67755e5e4cc42a76a2ccdd13ec96b83f9d109de6de7428e690e9e004079d:


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.WithValue(context.WithoutCancel(ctx), ctxShared{}, true), 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()
	}
}

// ctxShared marks a run that other callers may join. Its first caller's
// obs reason (a warm, say) stays for attribution, but must not decide
// admission: a visitor joining a warm's flight would be refused as
// background while interactive slots are free.
type ctxShared struct{}

func isShared(ctx context.Context) bool { v, _ := ctx.Value(ctxShared{}).(bool); return v }