package views // A view found by its seat (design 47 G §717): a part follows a state of the module holding a seat, the holder read from // the seat-holders view through the holder function the part is given (A-295, A-298), so no code names the holder and a // moved holder is followed as it moves. Nothing is asked on a timer: the holder is read again at each change of a view the // reader follows, the seat-holders view among them. import ( "context" "encoding/json" "errors" "fmt" "maps" "sync" "time" ) // HolderWait is what a seat's view waits for while it follows no holder (design 47 G §717): its status's WaitsFor, and // past WaitsBound the reader's view-waits finding names the seat and the state. const HolderWait = "a holder of the seat" // seatFollow is one seat's view: the picture the part reads (its follower names the seat, never asks) and the holder's // view it hands on. type seatFollow struct { seat, state string holders func(seat string) []string pic *Picture kick chan struct{} running bool mu sync.Mutex holder string // the holder followed now, "" for none inner *Picture // its view cancel context.CancelFunc // ends the wait for its first view handed *Picture // the view whose state the picture holds } // FollowSeat follows state of the module holding seat (design 47 G §717): it returns at once a picture that reads as empty, // its follower not ready, and never fails for want of a holder. At each change of a view the reader follows (the // seat-holders view the holder function answers from among them) it reads the seat's first holder: on a first holder it // follows as Follow does after Start, the first view asked of `.`, then its views family; on another holder // it drops the old one's view and follows the new one, the picture handing on the new holder's state whole once its first // view arrives; with no holder it keeps the picture it has and follows nothing. While no holder's first view is held the // follower's status names the seat, waiting for HolderWait since the start or since its holder left, and past WaitsBound // the reader writes view-waits naming the seat and the state, cleared when a holder's first view arrives. The picture's // bus name is `_` (KeyValue opens it). A seat's state followed already is its picture. func (r *ProcessReader) FollowSeat(seat, state string, holders func(seat string) []string) (*Picture, error) { if seat == "" || state == "" || holders == nil { return nil, errors.New("views: a seat's view names its seat and state, and the holder function that answers its holder") } bucket := seat + "_" + state r.mu.Lock() if sw := r.seats[bucket]; sw != nil { r.mu.Unlock() return sw.pic, nil } sw := &seatFollow{seat: seat, state: state, holders: holders, kick: make(chan struct{}, 1)} p := &Picture{bucket: bucket, ctx: context.Background()} sf := &Follower{Owner: seat, Tool: "seat:" + seat + "." + state, State: state, Logf: r.Logf, Now: r.Now, Changed: p.changed} sf.RaiseWaits = func(s Status) { if r.holdsSeat(sw) { r.waits(s, true) } } sf.ClearWaits = func(s Status) { r.waits(s, false) } p.f, sw.pic = sf, p if r.seats == nil { r.seats = map[string]*seatFollow{} } r.seats[bucket] = sw asked := r.asked r.mu.Unlock() if asked { r.runSeat(sw) } return p, nil } // holdsSeat says whether sw is still a seat's view of the reader. func (r *ProcessReader) holdsSeat(sw *seatFollow) bool { r.mu.Lock() defer r.mu.Unlock() return r.seats[sw.pic.bucket] == sw } // runSeat starts sw's reading of its holder once the reader asks (Ask): its wait from the start, then a read at once and at // each change told (seatsChanged). func (r *ProcessReader) runSeat(sw *seatFollow) { r.mu.Lock() if sw.running || !r.asked { r.mu.Unlock() return } sw.running = true ctx, said := r.ctx, r.said r.mu.Unlock() sw.pic.f.Said = func(s Status) { if said != nil && sw.waiting() { said(s) } } sw.pic.f.WaitFor(ctx, HolderWait) go func() { for { r.reread(ctx, sw) select { case <-ctx.Done(): return case <-sw.kick: } } }() } // seatsChanged tells every seat's view to read its holder again, without blocking (a view's change is told outside its // follower's lock, but may be told often: one read stands for many). func (r *ProcessReader) seatsChanged() { r.mu.Lock() defer r.mu.Unlock() for _, sw := range r.seats { select { case sw.kick <- struct{}{}: default: } } } // waiting says whether no holder's first view is held: the seat's own status is said only then. func (sw *seatFollow) waiting() bool { sw.mu.Lock() defer sw.mu.Unlock() return sw.handed == nil } // reread reads the seat's first holder and follows it when it is another than the one followed. func (r *ProcessReader) reread(ctx context.Context, sw *seatFollow) { holder := "" if hs := sw.holders(sw.seat); len(hs) > 0 { holder = hs[0] } sw.mu.Lock() old, cancel := sw.holder, sw.cancel if holder == old { sw.mu.Unlock() return } sw.holder, sw.inner, sw.cancel, sw.handed = "", nil, nil, nil sw.mu.Unlock() if old != "" { cancel() if err := r.Drop(old, sw.state); err != nil { r.logf("views: %s's view of %s's %s is not dropped: %v", r.Module, old, sw.state, err) } r.logf("views: %s no longer follows %s's %s: the seat %s holder is now %q", r.Module, old, sw.state, sw.seat, holder) } if holder == "" { // the picture is kept; the wait is since the holder left sw.pic.f.WaitFor(ctx, HolderWait) return } inner, fresh, err := r.follow(holder, sw.state, holder+"."+sw.state) if err != nil || !fresh { r.logf("views: %s does not follow %s's %s for the seat %s: %v", r.Module, holder, sw.state, sw.seat, cmpErr(err, "followed already apart from the seat")) return } own := inner.f.Changed inner.f.Changed = func(key string, value json.RawMessage, deleted bool, at time.Time) { own(key, value, deleted, at) r.apply(sw, inner, key, value, deleted, at) } ictx, icancel := context.WithCancel(ctx) sw.mu.Lock() sw.holder, sw.inner, sw.cancel = holder, inner, icancel sw.mu.Unlock() r.logf("views: %s follows %s's %s, the holder of the seat %s", r.Module, holder, sw.state, sw.seat) r.begin(inner.bucket) go func() { select { case <-ictx.Done(): case <-inner.f.Ready(): r.hand(sw, inner) } }() } func cmpErr(err error, words string) error { if err != nil { return err } return errors.New(words) } // apply takes one change of the holder's view into the seat's picture, once its state was handed on whole. func (r *ProcessReader) apply(sw *seatFollow, inner *Picture, key string, value json.RawMessage, deleted bool, at time.Time) { sw.mu.Lock() if sw.inner != inner { sw.mu.Unlock() return } if sw.handed != inner { sw.mu.Unlock() r.hand(sw, inner) // its first view: the state whole, this change in it return } defer sw.mu.Unlock() sf := sw.pic.f sf.mu.Lock() if deleted { delete(sf.values, key) } else { sf.values[key] = value } changed := sf.Changed sf.mu.Unlock() if changed != nil { changed(key, value, deleted, at) } } // hand takes the holder's state whole into the seat's picture at its first view: each key it changes is told, each key the // old holder had that the new lacks is told deleted, the picture is ready, and the wait for a holder is cleared. func (r *ProcessReader) hand(sw *seatFollow, inner *Picture) { sw.mu.Lock() if sw.inner != inner || sw.handed == inner { sw.mu.Unlock() return } select { case <-inner.f.Ready(): default: sw.mu.Unlock() return } sw.handed = inner holder := sw.holder values := inner.f.Values() sf := sw.pic.f sf.mu.Lock() sf.init() old := sf.values sf.values = maps.Clone(values) select { case <-sf.ready: default: close(sf.ready) } changed := sf.Changed sf.mu.Unlock() if changed != nil { for k, v := range values { if ov, ok := old[k]; !ok || string(ov) != string(v) { changed(k, v, false, time.Time{}) } } for k := range old { if _, ok := values[k]; !ok { changed(k, nil, true, time.Time{}) } } } sw.mu.Unlock() sf.Holds(holder) r.logf("views: %s holds %s's %s, the holder of the seat %s", r.Module, holder, sw.state, sw.seat) r.mu.Lock() status := r.status r.mu.Unlock() if key := StatusKey(sw.seat, sw.state); status != nil && key != StatusKey(holder, sw.state) { if kv := status.KV(); kv != nil { if err := kv.Delete(context.Background(), key); err != nil { r.logf("views: the waiting status %s is not removed from %s: %v", key, StatusState, err) } } } } // HolderBucket is the bus name `_` of the holder whose state FollowSeat follows now for seat, "" while it // follows none (design 47 G A-303): the name a part uses where another part names the holder's real bucket (a key the // watchman writes, a name kept in an entry), read at each use, so a moved holder is named as it moves. func (r *ProcessReader) HolderBucket(seat, state string) string { r.mu.Lock() sw := r.seats[seat+"_"+state] r.mu.Unlock() if sw == nil { return "" } sw.mu.Lock() defer sw.mu.Unlock() if sw.holder == "" { return "" } return sw.holder + "_" + state } // seatPicture is the picture of a seat's view by its bus name, nil when none. func (r *ProcessReader) seatPicture(bucket string) *Picture { r.mu.Lock() defer r.mu.Unlock() if sw := r.seats[bucket]; sw != nil { return sw.pic } return nil } // seatWaitsSummary is the view-waits words of a seat's view that follows no holder yet. func seatWaitsSummary(part string, s Status) string { return fmt.Sprintf("%s waits for a module holding the seat %s, to follow its view %s, since %s", part, s.Owner, s.State, s.WaitingSince.UTC().Format(time.RFC3339)) }