package main import ( "fmt" "sync" "time" "distribution/internal/holder" ) // askTakenBound is the setting the taken key of a publish ask lives (design 47 H2 §775, H-A-381 (2)): the holder never // receives the caller's bound, so it keeps an ask's id this long, the largest caller's bound by default. const askTakenBound = "ask-taken-bound" // askTakenDefault is ask-taken-bound's default, the runner's ask-unanswered-bound (H-A-381 (2)). const askTakenDefault = 10 * time.Minute // asks takes each publish ask once by its id (design 47 H2 §775; ADR 0668 §2; H-A-381): the first call with an id is // kept in the state taken and acts; a repeat while that act runs joins it and gets its answer; a repeat after it ended // answers the act's state read afresh (holder.Repeat), never acting twice. No answer is kept in taken. A call that // carries no ask id is no kept call, and acts as it did before. type asks struct { take func(seat, ask string, bound time.Duration) (bool, error) bound time.Duration mu sync.Mutex running map[string]*flight // joined, when set, is told each repeat that joins a running act (a test's hook). joined func() } // flight is one act of a taken ask while it runs, which a repeat joins. type flight struct { done chan struct{} a holder.PublishAnswer err error } func (k *asks) once(seat, ask string, act, repeat func() (holder.PublishAnswer, error)) (holder.PublishAnswer, error) { if ask == "" || k == nil || k.take == nil { return act() } key := seat + "." + ask k.mu.Lock() if f, ok := k.running[key]; ok { k.mu.Unlock() if k.joined != nil { k.joined() } <-f.done return f.a, f.err } if k.running == nil { k.running = map[string]*flight{} } f := &flight{done: make(chan struct{})} k.running[key] = f k.mu.Unlock() defer func() { k.mu.Lock() delete(k.running, key) k.mu.Unlock() close(f.done) }() took, err := k.take(seat, ask, k.bound) switch { case err != nil: f.err = fmt.Errorf("publish: the ask %s of %s cannot be taken: %w", ask, seat, err) case took: f.a, f.err = act() default: logf("%s.publish: the ask %s was taken before; it answers the act's state, acting not again", seat, ask) f.a, f.err = repeat() } return f.a, f.err }