package web import ( "context" "net/http" "slices" "strings" "sync" "time" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/store" ) // clientCapsHeader is what Base's native app says it can draw, on its // /ask/* reads (docs/api/base-native-v1.md); clientCapsParam is the same // list as a query parameter, for an app whose HTTP kit sets no header of // its own (rastrillo/native's NativeHTTP). const ( clientCapsHeader = "Base-Client-Capabilities" clientCapsParam = "client_caps" ) // clientWindow is how long a native client's last word counts: one not // seen for longer no longer holds a capability back. const clientWindow = 30 * 24 * time.Hour // clientCaps reads a request's Base-Client-Capabilities: native is true // for the native app's session, caps are the known values it named, in // KnownCapabilities' order. A web session is never native. func clientCaps(r *http.Request) (native bool, caps []string) { s, ok := sessions.Current(r) if !ok || s.Method != connect.NativeMethod { return false, nil } said := map[string]bool{} for _, v := range append(r.Header.Values(clientCapsHeader), r.URL.Query()[clientCapsParam]...) { for _, c := range strings.Split(v, ",") { said[strings.TrimSpace(c)] = true } } for _, c := range equipo.KnownCapabilities { if said[c] { caps = append(caps, c) } } return true, caps } // askCaps are the capabilities Base tells Equipo for the member numbered // member: every known one, but those a native client of theirs seen in // the last 30 days last called without. A read error withholds them all, // and so does a client of theirs Base couldn't record (clientsDown). func (a *app) askCaps(ctx context.Context, member int64) []string { // Worked out under the member's lock, so no record of theirs is // half made meanwhile. m := a.memberLock(member) m.Lock() defer m.Unlock() if a.clientsDown(member) { return nil } // An app Base has never heard from draws nothing. now := time.Now() if unseen, err := store.UnseenNativeClients(ctx, a.db, member, connect.NativeMethod, now.Add(-connect.NativeLifetime), now); err != nil || unseen > 0 { if err != nil { a.logger.Error("ask: native sessions", "err", err) } return nil } clients, err := store.AskClients(ctx, a.db, member, time.Now().Add(-clientWindow)) if err != nil { a.logger.Error("ask: clients", "err", err) return nil } var out []string for _, c := range equipo.KnownCapabilities { ok := true for _, cl := range clients { ok = ok && slices.Contains(strings.Split(cl.Caps, ","), c) } if ok { out = append(out, c) } } return out } // clientsUnrecorded holds, per member number, the native clients whose // last request Base couldn't record: while any is held, the member is // told to draw nothing. It lives in memory: a restart forgets it, and // the client's next request records it. type clientsUnrecorded struct { mu sync.Mutex held map[int64]map[string]time.Time // locks holds a *sync.Mutex per member number (recordClient). locks sync.Map } // recordClient records a native request of the member numbered member's // (its session's token hash is the client): on one of the two reads, // what it says it draws, else only that it was seen (a first write draws // nothing). Base's knowledge only ever narrows on a failure: a read Base // couldn't record removes what the client said before, so it counts as // unseen (UnseenNativeClients), and holds the member back in memory as // well, until a read of that client's is recorded. A write never lifts // that. One member's requests are recorded one at a time. func (a *app) recordClient(ctx context.Context, r *http.Request, member int64, said []string) { c, err := r.Cookie(a.sess.CookieName()) if err != nil { a.logger.Error("ask: see client", "err", err) a.clientRecorded(member, "", false) return } client := sessions.HashToken(c.Value) m := a.memberLock(member) m.Lock() defer m.Unlock() // A client going away mid-request doesn't stop its record (nor its // undoing on a failure), which stays bounded. ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recordWait) defer cancel() if !recordsClient(r) { if err := store.TouchAskClient(ctx, a.db, member, client); err != nil { a.logger.Error("ask: see client", "err", err) a.clientRecorded(member, client, false) } return } if err := store.SeeAskClient(ctx, a.db, member, client, strings.Join(said, ",")); err != nil { a.logger.Error("ask: see client", "err", err) if err := store.ForgetAskClient(ctx, a.db, member, client); err != nil { a.logger.Error("ask: forget client", "err", err) } a.clientRecorded(member, client, false) return } a.clientRecorded(member, client, true) } // recordWait bounds recording one client's request. const recordWait = 5 * time.Second // memberLock is the member numbered member's lock: their clients are // recorded, and their capabilities worked out, one at a time. func (a *app) memberLock(member int64) *sync.Mutex { m, _ := a.unrecorded.locks.LoadOrStore(member, &sync.Mutex{}) return m.(*sync.Mutex) } // clientRecorded notes whether client's request was recorded for the // member numbered member. func (a *app) clientRecorded(member int64, client string, ok bool) { u := &a.unrecorded u.mu.Lock() defer u.mu.Unlock() if ok { delete(u.held[member], client) if len(u.held[member]) == 0 { delete(u.held, member) } return } if u.held == nil { u.held = map[int64]map[string]time.Time{} } if u.held[member] == nil { u.held[member] = map[string]time.Time{} } u.held[member][client] = time.Now() } // clientsDown reports whether a native client of the member numbered // member went unrecorded. func (a *app) clientsDown(member int64) bool { a.unrecorded.mu.Lock() defer a.unrecorded.mu.Unlock() for client, at := range a.unrecorded.held[member] { // A hold lasts as long as a client's word does. if time.Since(at) < clientWindow { return true } delete(a.unrecorded.held[member], client) } return false } // recordsClient reports whether r is one of the two reads on which an // app says what it can draw: every app reads /ask/state and opens // /ask/events, and only these answers carry lookups. func recordsClient(r *http.Request) bool { return r.Method == http.MethodGet && (r.URL.Path == "/ask/state" || r.URL.Path == "/ask/events") } // withAskCaps records what a native app's /ask/state or /ask/events read // says it can draw, and every other native /ask/* request as a sign of // life (a client first seen writing draws nothing; web sessions are not // recorded), then puts the member's capabilities // (askCaps) on the request's context, so every Equipo call made for it // carries Base-Capabilities. It runs behind the member gate. func (a *app) withAskCaps(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { me, ok := CurrentMember(r) if !ok { next.ServeHTTP(w, r) return } ctx := r.Context() n, err := store.MemberNumber(ctx, a.db, me.ID) if err != nil { a.logger.Error("ask: member number", "err", err) next.ServeHTTP(w, r) return } if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") { a.recordClient(ctx, r, n, said) } // Worked out as each call to Equipo is sent, not now. next.ServeHTTP(w, r.WithContext(equipo.WithCapabilitiesFunc(ctx, func(ctx context.Context) []string { return a.askCaps(ctx, n) }))) }) } // plainLookups reports whether r is the native app's and didn't say it // draws lookups: its /ask/* answers then carry each message's lookups // folded into its text (equipo.Message.PlainLookups), whatever Equipo // sent. func plainLookups(r *http.Request) bool { native, caps := clientCaps(r) return native && !slices.Contains(caps, equipo.CapLookupAnswers) } // asDrawn is m as client r draws it (plainLookups). func asDrawn(r *http.Request, m equipo.Message) equipo.Message { if plainLookups(r) { return m.PlainLookups() } return m }