package views import ( "cmp" "context" "encoding/json" "fmt" "maps" "slices" "strings" "sync" "time" "github.com/nats-io/nats.go/jetstream" "git.novox.be/novox/mesh-sdk/go/buscalls" "git.novox.be/novox/mesh-sdk/go/busretry" ) // Follower is a reader's picture of one state of an owner (ADR 0615 §4 to §6): it asks the owner's first-view tool at // its start, then keeps the picture from the owner's events alone, asking the tool once more only on a gap in revisions // (said in its log), never on a timer. Started while the owner is down, it keeps asking, never reading the owner's state // instead, and past Bound raises its condition naming the owner and the tool; the answer clears it. type Follower struct { Owner string // Tool is the owner's tool it asks, as the reader's invokes names it (.). Tool string State string // Ask calls the tool for the page after after. Ask func(ctx context.Context, after string) (Answer, error) // Raise and Clear are the reader's condition of this first view (past Bound; cleared by the answer). Nil says // nothing. Raise func(Status) Clear func(Status) // RaiseWaits and ClearWaits are the part's view-waits finding: written past WaitsBound of a WaitFor, cleared when it // Holds the view. Nil says nothing. RaiseWaits func(Status) ClearWaits func(Status) // Changed is told of each key the picture changes (deleted: the key is gone), after the change is held, with when the // owner's bus wrote it: the event's time, or for a key a first view brought the time its answer says (Answer.Written; // zero when the owner does not say it, and for a key the first view no longer holds). Changed func(key string, value json.RawMessage, deleted bool, at time.Time) // Said is told of the status each time an ask starts, is answered or fails, and of a raise and a clear: where a // reader keeps it on the bus for its read tool (StatusTools). Said func(Status) Logf func(string, ...any) Now func() time.Time // Bound is how long it asks before it raises; zero is views.Bound. Wait is the first wait between two asks that // failed, doubling to a minute; zero is five seconds. Bound time.Duration Wait time.Duration mu sync.Mutex values map[string]json.RawMessage st Status asking bool // during are the events heard while an ask runs: taken again after its answer, so none is lost to a picture read // before it was written. during []Event // heardRev is the highest revision of the owner's state (made at heardCreated) any event handed to Apply carried, // whether it was taken into the picture, passed over or heard while an ask ran: what the picture must reach, so a // reader that heard it knows it is behind without a further event. heardRev uint64 heardCreated time.Time // consumerMade is when the bus made the reader's consumer of the owner's events (EventHub.OnBound): an event said // before it is not delivered to it, so a picture asked before it is behind. consumerMade time.Time // catching is set while catchUp runs: one catch-up at a time. catching bool ready chan struct{} born time.Time // when the follower began (Unread) } // Status is what a reader's read tool says of one first view (design 25 § 12.2): the owner, the tool and the revision // its picture holds, when it asked and when it was answered, how many asks, the hand acts among them, and whether its // condition is raised. type Status struct { Owner string `json:"owner"` Tool string `json:"tool"` State string `json:"state"` Revision uint64 `json:"revision"` Created time.Time `json:"created,omitzero"` Keys int `json:"keys"` Asked time.Time `json:"asked,omitzero"` Answered time.Time `json:"answered,omitzero"` Asks int `json:"asks"` ByHand int `json:"by-hand"` Raised bool `json:"raised"` // Heard is the highest revision of the owner's state any event heard carried (made at HeardCreated), taken into the // picture or not; Behind says why the picture is short of it, or of its consumer's making, and an ask for it runs. Heard uint64 `json:"heard,omitempty"` HeardCreated time.Time `json:"heard-created,omitzero"` Behind string `json:"behind,omitempty"` // Why is the last reason it asked (start, a gap and which, a hand act) or why the last ask failed. Why string `json:"why,omitempty"` Error string `json:"error,omitempty"` // View is the revision of the revision view the part holds from this first view, as its seat's client names it // (design 47 *A part with no view says it waits*); WaitsFor the one it waits for and acts on nothing new until it // holds, since WaitingSince; WaitsRaised says its view-waits finding is written (past WaitsBound). View string `json:"view,omitempty"` WaitsFor string `json:"waits-for,omitempty"` WaitingSince time.Time `json:"waiting-since,omitzero"` WaitsRaised bool `json:"waits-raised,omitempty"` } // WaitsBound is how long a part waits for a view before it writes its finding view-waits (design 47): the bound the seat // list's readers keep, so an owner down for a restart raises nothing. const WaitsBound = 5 * time.Minute // waitBound waits d within ctx: true when d passed, false when ctx ended first. A variable so a test ends it at once. var waitBound = swappable(func(ctx context.Context, d time.Duration) bool { b, cancel := context.WithTimeout(ctx, d) defer cancel() <-b.Done() return ctx.Err() == nil }) // NoneYet is what a seat's revision verb answers for a branch with no revision yet (design 47 G §479, §495): that view // is ready and empty, and nothing waits for it. const NoneYet = "none yet" // WaitFor says the part waits for view, a revision of the revision view its seat's client names, and acts on nothing // new until it holds it (Holds): the status says what and since when, and if it still waits for it past WaitsBound, // RaiseWaits is told (the part writes view-waits, ViewWaitsFinding). Waiting for the view it waits for already changes // nothing, not even since when. func (f *Follower) WaitFor(ctx context.Context, view string) { f.mu.Lock() f.init() if f.st.WaitsFor == view || view == "" || view == NoneYet { f.mu.Unlock() return } f.st.WaitsFor, f.st.WaitingSince, f.st.WaitsRaised = view, f.now(), false s := f.st f.mu.Unlock() f.logf("views: %s waits for %s's view %s, from %s", f.Tool, f.Owner, view, s.WaitingSince.Format(time.RFC3339)) f.say(s) go func() { if !waitBound.get()(ctx, WaitsBound) { return } f.mu.Lock() raise := f.st.WaitsFor == view && !f.st.WaitsRaised if raise { f.st.WaitsRaised = true } s := f.st f.mu.Unlock() if raise { f.logf("views: %s has waited for %s's view %s since %s", f.Tool, f.Owner, view, s.WaitingSince.Format(time.RFC3339)) if f.RaiseWaits != nil { f.RaiseWaits(s) } f.say(s) } }() } // Holds says the part holds view now: it waits no more, and a raised view-waits is cleared (ClearWaits). func (f *Follower) Holds(view string) { f.mu.Lock() f.init() raised := f.st.WaitsRaised f.st.View, f.st.WaitsFor, f.st.WaitingSince, f.st.WaitsRaised = view, "", time.Time{}, false s := f.st f.mu.Unlock() if raised && f.ClearWaits != nil { f.ClearWaits(s) } f.say(s) } func (f *Follower) now() time.Time { if f.Now != nil { return f.Now().UTC() } return time.Now().UTC() } func (f *Follower) logf(format string, args ...any) { if f.Logf != nil { f.Logf(format, args...) } } func (f *Follower) init() { if f.values == nil { f.values = map[string]json.RawMessage{} f.ready = make(chan struct{}) f.st = Status{Owner: f.Owner, Tool: f.Tool, State: f.State} f.born = f.now() } } func (f *Follower) say(s Status) { if f.Said != nil { f.mu.Lock() s = f.statusLocked(s) f.mu.Unlock() f.Said(s) } } // statusLocked is s with what the follower holds beside it: its keys, the highest revision heard and why it is behind. // The caller holds mu. func (f *Follower) statusLocked(s Status) Status { s.Keys = len(f.values) s.Heard, s.HeardCreated, s.Behind = f.heardRev, f.heardCreated, f.behindLocked() return s } // Status is the follower's status now. func (f *Follower) Status() Status { f.mu.Lock() defer f.mu.Unlock() f.init() return f.statusLocked(f.st) } // Ready is closed once a first view was answered. func (f *Follower) Ready() <-chan struct{} { f.mu.Lock() defer f.mu.Unlock() f.init() return f.ready } // Unread says whether the first view was not answered yet: the fault `away` (busretry.Away, design 47 H2 §776) naming the // view's owner verb (its Tool) and saying "not read yet since