| 1 | package web |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/home/connect" |
| 12 | "amadan.net/rastrillo/rastrillo/sessions" |
| 13 | |
| 14 | "amadan.net/oficina/base/internal/equipo" |
| 15 | "amadan.net/oficina/base/internal/store" |
| 16 | ) |
| 17 | |
| 18 | // clientCapsHeader is what Base's native app says it can draw, on its |
| 19 | // /ask/* reads (docs/api/base-native-v1.md); clientCapsParam is the same |
| 20 | // list as a query parameter, for an app whose HTTP kit sets no header of |
| 21 | // its own (rastrillo/native's NativeHTTP). |
| 22 | const ( |
| 23 | clientCapsHeader = "Base-Client-Capabilities" |
| 24 | clientCapsParam = "client_caps" |
| 25 | ) |
| 26 | |
| 27 | // clientWindow is how long a native client's last word counts: one not |
| 28 | // seen for longer no longer holds a capability back. |
| 29 | const clientWindow = 30 * 24 * time.Hour |
| 30 | |
| 31 | // clientCaps reads a request's Base-Client-Capabilities: native is true |
| 32 | // for the native app's session, caps are the known values it named, in |
| 33 | // KnownCapabilities' order. A web session is never native. |
| 34 | func clientCaps(r *http.Request) (native bool, caps []string) { |
| 35 | s, ok := sessions.Current(r) |
| 36 | if !ok || s.Method != connect.NativeMethod { |
| 37 | return false, nil |
| 38 | } |
| 39 | said := map[string]bool{} |
| 40 | for _, v := range append(r.Header.Values(clientCapsHeader), r.URL.Query()[clientCapsParam]...) { |
| 41 | for _, c := range strings.Split(v, ",") { |
| 42 | said[strings.TrimSpace(c)] = true |
| 43 | } |
| 44 | } |
| 45 | for _, c := range equipo.KnownCapabilities { |
| 46 | if said[c] { |
| 47 | caps = append(caps, c) |
| 48 | } |
| 49 | } |
| 50 | return true, caps |
| 51 | } |
| 52 | |
| 53 | // askCaps are the capabilities Base tells Equipo for the member numbered |
| 54 | // member: every known one, but those a native client of theirs seen in |
| 55 | // the last 30 days last called without. A read error withholds them all, |
| 56 | // and so does a client of theirs Base couldn't record (clientsDown). |
| 57 | func (a *app) askCaps(ctx context.Context, member int64) []string { |
| 58 | // Worked out under the member's lock, so no record of theirs is |
| 59 | // half made meanwhile. |
| 60 | m := a.memberLock(member) |
| 61 | m.Lock() |
| 62 | defer m.Unlock() |
| 63 | if a.clientsDown(member) { |
| 64 | return nil |
| 65 | } |
| 66 | // An app Base has never heard from draws nothing. |
| 67 | now := time.Now() |
| 68 | if unseen, err := store.UnseenNativeClients(ctx, a.db, member, connect.NativeMethod, now.Add(-connect.NativeLifetime), now); err != nil || unseen > 0 { |
| 69 | if err != nil { |
| 70 | a.logger.Error("ask: native sessions", "err", err) |
| 71 | } |
| 72 | return nil |
| 73 | } |
| 74 | clients, err := store.AskClients(ctx, a.db, member, time.Now().Add(-clientWindow)) |
| 75 | if err != nil { |
| 76 | a.logger.Error("ask: clients", "err", err) |
| 77 | return nil |
| 78 | } |
| 79 | var out []string |
| 80 | for _, c := range equipo.KnownCapabilities { |
| 81 | ok := true |
| 82 | for _, cl := range clients { |
| 83 | ok = ok && slices.Contains(strings.Split(cl.Caps, ","), c) |
| 84 | } |
| 85 | if ok { |
| 86 | out = append(out, c) |
| 87 | } |
| 88 | } |
| 89 | return out |
| 90 | } |
| 91 | |
| 92 | // clientsUnrecorded holds, per member number, the native clients whose |
| 93 | // last request Base couldn't record: while any is held, the member is |
| 94 | // told to draw nothing. It lives in memory: a restart forgets it, and |
| 95 | // the client's next request records it. |
| 96 | type clientsUnrecorded struct { |
| 97 | mu sync.Mutex |
| 98 | held map[int64]map[string]time.Time |
| 99 | // locks holds a *sync.Mutex per member number (recordClient). |
| 100 | locks sync.Map |
| 101 | } |
| 102 | |
| 103 | // recordClient records a native request of the member numbered member's |
| 104 | // (its session's token hash is the client): on one of the two reads, |
| 105 | // what it says it draws, else only that it was seen (a first write draws |
| 106 | // nothing). Base's knowledge only ever narrows on a failure: a read Base |
| 107 | // couldn't record removes what the client said before, so it counts as |
| 108 | // unseen (UnseenNativeClients), and holds the member back in memory as |
| 109 | // well, until a read of that client's is recorded. A write never lifts |
| 110 | // that. One member's requests are recorded one at a time. |
| 111 | func (a *app) recordClient(ctx context.Context, r *http.Request, member int64, said []string) { |
| 112 | c, err := r.Cookie(a.sess.CookieName()) |
| 113 | if err != nil { |
| 114 | a.logger.Error("ask: see client", "err", err) |
| 115 | a.clientRecorded(member, "", false) |
| 116 | return |
| 117 | } |
| 118 | client := sessions.HashToken(c.Value) |
| 119 | m := a.memberLock(member) |
| 120 | m.Lock() |
| 121 | defer m.Unlock() |
| 122 | // A client going away mid-request doesn't stop its record (nor its |
| 123 | // undoing on a failure), which stays bounded. |
| 124 | ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recordWait) |
| 125 | defer cancel() |
| 126 | if !recordsClient(r) { |
| 127 | if err := store.TouchAskClient(ctx, a.db, member, client); err != nil { |
| 128 | a.logger.Error("ask: see client", "err", err) |
| 129 | a.clientRecorded(member, client, false) |
| 130 | } |
| 131 | return |
| 132 | } |
| 133 | if err := store.SeeAskClient(ctx, a.db, member, client, strings.Join(said, ",")); err != nil { |
| 134 | a.logger.Error("ask: see client", "err", err) |
| 135 | if err := store.ForgetAskClient(ctx, a.db, member, client); err != nil { |
| 136 | a.logger.Error("ask: forget client", "err", err) |
| 137 | } |
| 138 | a.clientRecorded(member, client, false) |
| 139 | return |
| 140 | } |
| 141 | a.clientRecorded(member, client, true) |
| 142 | } |
| 143 | |
| 144 | // recordWait bounds recording one client's request. |
| 145 | const recordWait = 5 * time.Second |
| 146 | |
| 147 | // memberLock is the member numbered member's lock: their clients are |
| 148 | // recorded, and their capabilities worked out, one at a time. |
| 149 | func (a *app) memberLock(member int64) *sync.Mutex { |
| 150 | m, _ := a.unrecorded.locks.LoadOrStore(member, &sync.Mutex{}) |
| 151 | return m.(*sync.Mutex) |
| 152 | } |
| 153 | |
| 154 | // clientRecorded notes whether client's request was recorded for the |
| 155 | // member numbered member. |
| 156 | func (a *app) clientRecorded(member int64, client string, ok bool) { |
| 157 | u := &a.unrecorded |
| 158 | u.mu.Lock() |
| 159 | defer u.mu.Unlock() |
| 160 | if ok { |
| 161 | delete(u.held[member], client) |
| 162 | if len(u.held[member]) == 0 { |
| 163 | delete(u.held, member) |
| 164 | } |
| 165 | return |
| 166 | } |
| 167 | if u.held == nil { |
| 168 | u.held = map[int64]map[string]time.Time{} |
| 169 | } |
| 170 | if u.held[member] == nil { |
| 171 | u.held[member] = map[string]time.Time{} |
| 172 | } |
| 173 | u.held[member][client] = time.Now() |
| 174 | } |
| 175 | |
| 176 | // clientsDown reports whether a native client of the member numbered |
| 177 | // member went unrecorded. |
| 178 | func (a *app) clientsDown(member int64) bool { |
| 179 | a.unrecorded.mu.Lock() |
| 180 | defer a.unrecorded.mu.Unlock() |
| 181 | for client, at := range a.unrecorded.held[member] { |
| 182 | // A hold lasts as long as a client's word does. |
| 183 | if time.Since(at) < clientWindow { |
| 184 | return true |
| 185 | } |
| 186 | delete(a.unrecorded.held[member], client) |
| 187 | } |
| 188 | return false |
| 189 | } |
| 190 | |
| 191 | // recordsClient reports whether r is one of the two reads on which an |
| 192 | // app says what it can draw: every app reads /ask/state and opens |
| 193 | // /ask/events, and only these answers carry lookups. |
| 194 | func recordsClient(r *http.Request) bool { |
| 195 | return r.Method == http.MethodGet && (r.URL.Path == "/ask/state" || r.URL.Path == "/ask/events") |
| 196 | } |
| 197 | |
| 198 | // withAskCaps records what a native app's /ask/state or /ask/events read |
| 199 | // says it can draw, and every other native /ask/* request as a sign of |
| 200 | // life (a client first seen writing draws nothing; web sessions are not |
| 201 | // recorded), then puts the member's capabilities |
| 202 | // (askCaps) on the request's context, so every Equipo call made for it |
| 203 | // carries Base-Capabilities. It runs behind the member gate. |
| 204 | func (a *app) withAskCaps(next http.Handler) http.Handler { |
| 205 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 206 | me, ok := CurrentMember(r) |
| 207 | if !ok { |
| 208 | next.ServeHTTP(w, r) |
| 209 | return |
| 210 | } |
| 211 | ctx := r.Context() |
| 212 | n, err := store.MemberNumber(ctx, a.db, me.ID) |
| 213 | if err != nil { |
| 214 | a.logger.Error("ask: member number", "err", err) |
| 215 | next.ServeHTTP(w, r) |
| 216 | return |
| 217 | } |
| 218 | if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") { |
| 219 | a.recordClient(ctx, r, n, said) |
| 220 | } |
| 221 | // Worked out as each call to Equipo is sent, not now. |
| 222 | next.ServeHTTP(w, r.WithContext(equipo.WithCapabilitiesFunc(ctx, func(ctx context.Context) []string { return a.askCaps(ctx, n) }))) |
| 223 | }) |
| 224 | } |
| 225 | |
| 226 | // plainLookups reports whether r is the native app's and didn't say it |
| 227 | // draws lookups: its /ask/* answers then carry each message's lookups |
| 228 | // folded into its text (equipo.Message.PlainLookups), whatever Equipo |
| 229 | // sent. |
| 230 | func plainLookups(r *http.Request) bool { |
| 231 | native, caps := clientCaps(r) |
| 232 | return native && !slices.Contains(caps, equipo.CapLookupAnswers) |
| 233 | } |
| 234 | |
| 235 | // asDrawn is m as client r draws it (plainLookups). |
| 236 | func asDrawn(r *http.Request, m equipo.Message) equipo.Message { |
| 237 | if plainLookups(r) { |
| 238 | return m.PlainLookups() |
| 239 | } |
| 240 | return m |
| 241 | } |
| 242 | |