package main // The manager's conditions (design 39 bus-and-switch §9, §11, §29 to §31, §33, B17, B37 to B39): each said on the // operator channel as any module says one (novox/hq ADR 0437 §9), the router alone deciding whether and where the // operator is told, and each it said raised kept in its state `conditions`, written before it is said and deleted when // it is said cleared. A raise or a clear is said again only when what it says changes (ADR 0289 §1); at its start the // manager judges every kind anew, says raised again each it still holds and cleared each key it no longer holds. import ( "context" "encoding/json" "fmt" "sort" "strings" "time" occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient" oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel" stdio "git.novox.be/novox/mesh-sdk/go" . "claude-licence-manager/internal/licences" ) // HeadlineLength is the operator channel's limit on a headline; a longer one is cut, ending in "…" (B39). const HeadlineLength = 60 // SayCondition publishes a condition on the operator channel's condition accept, under the manager's name, in the form // its client encodes (ADR 0437 §9). func SayCondition(c oc.Condition) error { subject, err := occ.ConditionSubject(Publisher) if err != nil { return err } raw, err := occ.EncodeCondition(c) if err != nil { return err } return stdio.SeatPublish(subject, json.RawMessage(raw), "") } // condition is a raised condition of the manager: its key, severity, words and the line said when it is over. An // empty needs is "Nothing for you to do."; the explanation is opened by its verdict here. func condition(key, severity, headline, summary, needs, explanation, resolved string) oc.Condition { verdict := occ.NothingToDo if needs != "" { verdict = occ.NeedsYou + needs + "." } if explanation != "" { verdict += " " + explanation } return oc.Condition{Key: key, Severity: severity, State: occ.StateRaised, Subject: oc.ConditionSubject{Scope: "module", ID: Publisher}, Headline: cut(headline), Summary: summary, Needs: needs, Explanation: verdict, Resolved: resolved} } // cut keeps a headline within the operator channel's limit, ending a longer one in "…" (B39). func cut(headline string) string { r := []rune(headline) if len(r) <= HeadlineLength { return headline } return string(r[:HeadlineLength-1]) + "…" } // short is a licence's short name for a headline: its address before the "@", or its name (B39). func short(name string) string { if at := strings.Index(name, "@"); at > 0 { return name[:at] } return name } // machines is a count of consumers in a headline (B39). func machines(n int) string { if n == 1 { return "1 machine" } return fmt.Sprintf("%d machines", n) } // Judge is every condition the manager holds now, judged anew from its own state and readings, by key. func (m *Manager) Judge(ctx context.Context) (map[string]oc.Condition, error) { held := map[string]oc.Condition{} s := m.settings() reasons := s.Reasons() for _, o := range s.OutOfBound { bound := fmt.Sprintf("at least %g", o.Min) if o.HasMax { bound = fmt.Sprintf("between %g and %g", o.Min, o.Max) } key := "settings." + o.Setting + ".invalid" held[key] = condition(key, occ.SeverityWarning, o.Setting+" is outside its bound", reasons[o.Setting], fmt.Sprintf("set %s %s", o.Setting, bound), fmt.Sprintf("%s is set to %g; the licence manager uses its default %g until it is fixed.", o.Setting, o.Value, o.Default), o.Setting+" is within its bound again") } for _, p := range s.Invalid() { key := "settings." + p.Setting + ".invalid" if _, ok := held[key]; ok { continue } held[key] = condition(key, occ.SeverityWarning, p.Setting+" is above switch_at_pct", reasons[p.Setting], fmt.Sprintf("set %s at or below switch_at_pct (%g)", p.Setting, p.SwitchAt), fmt.Sprintf("%s is %g, above switch_at_pct %g; the licence manager moves no consumer until it is fixed.", p.Setting, p.Value, p.SwitchAt), p.Setting+" is at or below switch_at_pct again") } licences, err := m.Store.Licences(ctx) if err != nil { return nil, err } bindings, err := m.Store.Bindings(ctx) if err != nil { return nil, err } for _, l := range licences { for key, c := range m.judgeLicence(l, licences, bindings, s) { held[key] = c } } return held, nil } // judgeLicence is what licence l holds of no-room (§29), near-limit (§30) and usage-unread (§31). func (m *Manager) judgeLicence(l Licence, licences []Licence, bindings []Binding, s Settings) map[string]oc.Condition { held := map[string]oc.Condition{} key := "licence." + KeyFor(l.Name) + "." consumers := consumersOf(l.Name, bindings) list := strings.Join(consumers, ", ") if r := m.RuleFor(l, licences, bindings, s); r.NoTarget { o := r.Over var rooms []string for _, other := range licences { if other.Name != l.Name { rooms = append(rooms, other.Name+" "+m.roomWords(other, s)) } } sort.Strings(rooms) others := "no other licence is held" if len(rooms) > 0 { others = strings.Join(rooms, "; ") } held[key+"no-room"] = condition(key+"no-room", occ.SeverityUrgent, "No licence has room for "+machines(len(consumers)), fmt.Sprintf("no licence has room for %s, bound to %s at %g %% of its %s window", list, l.Name, o.Pct, o.Window), fmt.Sprintf("add a licence, or wait for %s's %s window to reset at %s", l.Name, o.Window, o.ResetsAt), fmt.Sprintf("%s is at %g %% of its %s window, with %s bound to it; %s.", l.Name, o.Pct, o.Window, list, others), list+" have a licence with room again") } if window, pct, resetsAt, ok := windowAt(l.Usage, s.WarnAt); ok && len(consumers) > 0 { needs, plan := "", "" if to, _ := m.targetFor(l, licences, s); to != "" { plan = fmt.Sprintf("%s move to %s at %g %%. ", list, to, s.SwitchAt) } else { needs = "no other licence has room" } held[key+"near-limit"] = condition(key+"near-limit", occ.SeverityWarning, fmt.Sprintf("%s at %g%% %s", short(l.Name), pct, window), fmt.Sprintf("%s at %g %% of its %s window", l.Name, pct, window), needs, fmt.Sprintf("%s%s is at %g %% of its %s window, which resets at %s; %s bound to it.", plan, l.Name, pct, window, resetsAt, list), fmt.Sprintf("%s is below %g %% again", l.Name, s.WarnAt)) } if since, stale := m.unread(l, s); stale { needs := "" if len(consumers) > 0 { needs = list + " are not moved off it while its usage is unknown" } why := l.Usage.ReadErrorWords() held[key+"usage-unread"] = condition(key+"usage-unread", occ.SeverityWarning, short(l.Name)+"'s usage cannot be read", fmt.Sprintf("the usage of %s cannot be read: %s", l.Name, why), needs, fmt.Sprintf("%s, older than %g minutes; the vendor answers: %s.", since, s.UsageStale.Minutes(), why), l.Name+"'s usage is read again") } return held } // unread is whether subscription l's latest successful reading is older than usage_stale_minutes (§31), or, never // read successfully, its adoption is (B38); and the words naming since when. func (m *Manager) unread(l Licence, s Settings) (string, bool) { if l.Kind != "subscription" { return "", false } if l.Usage != nil && l.Usage.ReadAt != "" { read, err := time.Parse(time.RFC3339Nano, l.Usage.ReadAt) if err != nil { return "its latest successful reading has no time", true } return "its latest successful reading was at " + l.Usage.ReadAt, m.Now().Sub(read) > s.UsageStale } if l.AdoptedAt == 0 { return "", false } adopted := time.UnixMilli(l.AdoptedAt) return "no reading has succeeded since its adoption at " + adopted.UTC().Format(time.RFC3339), m.Now().Sub(adopted) > s.UsageStale } // roomWords is another licence's room for the condition no-room, or why it is not known or not enough (§29). func (m *Manager) roomWords(o Licence, s Settings) string { room, known := Room(o, m.Now(), s) switch { case known && *o.Usage.WeeklyPct >= s.RoomBelow: return fmt.Sprintf("has %g %% room, its weekly window not below %g %%", room, s.RoomBelow) case known: return fmt.Sprintf("has %g %% room", room) case o.Kind != "subscription": return "is an API key, whose room is never known" case o.Usage == nil || o.Usage.ReadAt == "": return "has no reading" case o.Usage.WeeklyPct == nil: return "has no weekly window in its reading" case o.Failures >= s.FailuresToNotify || (o.RefreshExpiresAt != 0 && o.RefreshExpiresAt <= m.Now().UnixMilli()): return "does not refresh" } return fmt.Sprintf("was not read within %g minutes", s.UsageStale.Minutes()) } // SayConditions judges every kind anew and says what changed: each condition held whose words differ from those kept // is written in `conditions`, then said raised; each kept key no longer held is said cleared, then deleted. With // again (at the start, and by licences_resync), each held is said raised again whether or not it changed. func (m *Manager) SayConditions(ctx context.Context, again bool) error { if m.Conditions == nil || m.Say == nil { return nil } m.conditionsMu.Lock() defer m.conditionsMu.Unlock() held, err := m.Judge(ctx) if err != nil { return err } keys, err := m.Conditions.Keys() if err != nil { return err } var errs []error for _, key := range keys { if _, ok := held[key]; ok { continue } var kept KeptCondition e, err := m.Conditions.Get(key) if err != nil { errs = append(errs, err) continue } if e != nil && len(e.Value) > 0 { _ = json.Unmarshal(e.Value, &kept) } cleared := kept.Body cleared.Key, cleared.State = key, occ.StateCleared cleared.Subject = oc.ConditionSubject{Scope: "module", ID: Publisher} if err := m.Say(cleared); err != nil { errs = append(errs, fmt.Errorf("the clearing of %s could not be said: %w", key, err)) continue } if err := m.Conditions.Delete(key); err != nil { errs = append(errs, err) } } var order []string for key := range held { order = append(order, key) } sort.Strings(order) for _, key := range order { c := held[key] kept := KeptCondition{Body: c, Since: m.Now().UTC().Format(time.RFC3339)} if e, err := m.Conditions.Get(key); err == nil && e != nil && len(e.Value) > 0 { var was KeptCondition if json.Unmarshal(e.Value, &was) == nil { if !again && sameCondition(was.Body, c) { continue } if was.Since != "" { kept.Since = was.Since } } } if _, err := m.Conditions.Put(key, kept); err != nil { errs = append(errs, err) continue } if err := m.Say(c); err != nil { // Not said: the key goes again, so the next judgement says it. _ = m.Conditions.Delete(key) errs = append(errs, fmt.Errorf("%s could not be said: %w", key, err)) } } if len(errs) > 0 { return fmt.Errorf("conditions: %v", errs) } return nil } // sameCondition is whether two raised conditions say the same. func sameCondition(a, b oc.Condition) bool { ra, _ := json.Marshal(a) rb, _ := json.Marshal(b) return string(ra) == string(rb) }