carlos / platform Public

console: remember when each person was last seen, at most once an hour

A person is seen when a gate passes for them: a browser session resolves,
a person's CLI token resolves (cliRoute for PrincipalUser, cliUser), or
they sign in. Service credentials are not people and write nothing.

reserveSeen checks and reserves the hour under one mutex; noteSeen then
makes one indexed UPDATE (TouchLastSeen) outside the lock. A failed write
is logged and keeps the reservation, so a failing database is retried an
hour later, never on every request, and never fails the request. The
write touches no bucket object, so the app-tab frame cache is untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a5c0097b80da85fa8020fdd31d5260e67e924053 parent 32b9ced
5 files changed, +328 −3
  • internal/console/authcli.go +8 −2
  • internal/console/emailsignin.go +1 −0
  • internal/console/lastseen.go +60 −0
  • internal/console/lastseen_test.go +248 −0
  • internal/console/server.go +11 −1

CI failed — run details

diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index da8dde151..f5af6e4d1 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -444,7 +444,8 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc)
}
s.cliRoles[pattern] = allow
s.registerRoute(pattern, func(w http.ResponseWriter, r *http.Request) {
- p, ok := s.store.CLIPrincipal(bearer(r), time.Now())
+ now := time.Now()
+ p, ok := s.store.CLIPrincipal(bearer(r), now)
if !ok {
// The same 401, with the same body, cliUser has always given:
// an expired token, a revoked one and a fabricated one are not
@@ -452,6 +453,9 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc)
s.cliNotSignedIn(w)
return
}
+ if p.Kind == PrincipalUser {
+ s.noteSeen(p.Address, now)
+ }
if p.Kind == PrincipalService && !allow.Permits(p.Role) {
if allow.Empty() {
// A closed door has no role that would work, so naming the
@@ -1253,11 +1257,13 @@ func (s *Server) cliNotSignedIn(w http.ResponseWriter) {
// 401 with the same body: an expired token, a revoked one, a fabricated one
// and a service credential are not distinguishable from outside.
func (s *Server) cliUser(w http.ResponseWriter, r *http.Request) (string, bool) {
- addr, ok := s.store.CLITokenAddress(bearer(r), time.Now())
+ now := time.Now()
+ addr, ok := s.store.CLITokenAddress(bearer(r), now)
if !ok {
s.cliNotSignedIn(w)
return "", false
}
+ s.noteSeen(addr, now)
return addr, true
}
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 3c42c4286..dfd863831 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -273,6 +273,7 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, addr, keym
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.")
return
}
+ s.noteSeen(addr, now)
s.clearCookie(w, authCookie)
s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
if created {
diff --git a/internal/console/lastseen.go b/internal/console/lastseen.go
new file mode 100644
index 000000000..6dd3fc1a3
--- /dev/null
+++ b/internal/console/lastseen.go
@@ -0,0 +1,60 @@
+package console
+
+import (
+ "log"
+ "time"
+)
+
+// Last seen: when each person was last active in the console, for the
+// operator people pages. A person is seen when a gate has passed for them: a
+// browser session resolves (session), a person's CLI token resolves
+// (cliRoute for PrincipalUser, cliUser), or they sign in (finishSignin).
+// Service credentials are not people and are never seen.
+//
+// AT MOST ONCE AN HOUR PER PERSON. The first request in a person's hour
+// reserves it in memory and makes one indexed UPDATE; every other request in
+// that hour costs a map lookup under seenMu and nothing else. The reservation
+// is taken and checked under one lock, so a burst of requests after the hour
+// writes once, and the write runs after the lock is released, so a slow
+// database never holds up anyone else's reservation check.
+//
+// A FAILED WRITE NEVER FAILS THE REQUEST. It is logged and the reservation
+// stays, so a failing database is retried an hour later, not on every
+// request. A person with no users row gets no row: TouchLastSeen never
+// creates one.
+//
+// The map holds one entry per address that has passed a gate since the
+// process started, so it is bounded by the people who use this console, not
+// by anything an unauthenticated caller can send.
+//
+// A last_seen write is not an app write: it touches no bucket object, so the
+// app-tab frame cache (appframe.go) is not cleared by it.
+
+// lastSeenEvery is how long a reservation stands: at most one last_seen write
+// per person per lastSeenEvery.
+const lastSeenEvery = time.Hour
+
+// reserveSeen reports whether addr's last_seen should be written at now: true
+// at most once per lastSeenEvery per address, and the hour is reserved in the
+// same critical section that checks it.
+func (s *Server) reserveSeen(addr string, now time.Time) bool {
+ s.seenMu.Lock()
+ defer s.seenMu.Unlock()
+ if at, ok := s.seen[addr]; ok && now.Sub(at) < lastSeenEvery {
+ return false
+ }
+ s.seen[addr] = now
+ return true
+}
+
+// noteSeen records that addr was seen at now, when its hour is not already
+// reserved. Called only after a gate has passed for addr as a person.
+func (s *Server) noteSeen(addr string, now time.Time) {
+ if !s.reserveSeen(addr, now) {
+ return
+ }
+ s.lastSeenWrites.Add(1)
+ if err := s.store.TouchLastSeen(addr, now); err != nil {
+ log.Printf("console: last seen %s: %v", addr, err)
+ }
+}
diff --git a/internal/console/lastseen_test.go b/internal/console/lastseen_test.go
new file mode 100644
index 000000000..0313e0606
--- /dev/null
+++ b/internal/console/lastseen_test.go
@@ -0,0 +1,248 @@
+package console
+
+import (
+ "net/http"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// lastSeenPaul is the fixture person's address: the one signInPaul signs in.
+const lastSeenPaul = "paul@keymail.dev"
+
+// lastSeenOf reads address's stored last_seen (Unix seconds); ok is false
+// when there is no users row.
+func lastSeenOf(t *testing.T, fx *consoleFixture, address string) (seen int64, ok bool) {
+ t.Helper()
+ err := fx.st.db.QueryRow(`SELECT last_seen FROM users WHERE address = ?`, address).Scan(&seen)
+ if err != nil {
+ return 0, false
+ }
+ return seen, true
+}
+
+// expireSeen makes address's reserved hour an hour and a minute old, as if
+// that much time had passed since the last write. moveBack also moves the
+// stored last_seen back an hour, so the next write can be seen moving it
+// (last_seen is whole seconds and the test runs inside one).
+func expireSeen(t *testing.T, fx *consoleFixture, address string, moveBack bool) {
+ t.Helper()
+ fx.srv.seenMu.Lock()
+ fx.srv.seen[address] = time.Now().Add(-61 * time.Minute)
+ fx.srv.seenMu.Unlock()
+ if moveBack {
+ if _, err := fx.st.db.Exec(`UPDATE users SET last_seen = last_seen - 3600 WHERE address = ?`, address); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func getKass(t *testing.T, fx *consoleFixture, c *http.Client) int {
+ t.Helper()
+ status, _, _ := get(t, c, fx.u("/apps/kass"))
+ return status
+}
+
+// TestLastSeenIsWrittenOncePerHour: signing in writes last_seen, browsing
+// within the hour writes nothing more, and the first request after the hour
+// writes again and moves it.
+func TestLastSeenIsWrittenOncePerHour(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ if n := fx.srv.lastSeenWrites.Load(); n != 1 {
+ t.Fatalf("lastSeenWrites after sign-in = %d, want 1", n)
+ }
+ first, ok := lastSeenOf(t, fx, lastSeenPaul)
+ if !ok || first == 0 {
+ t.Fatalf("last_seen after sign-in = %d (row %v), want set", first, ok)
+ }
+ for i := 0; i < 10; i++ {
+ if s := getKass(t, fx, c); s != http.StatusOK {
+ t.Fatalf("GET /apps/kass = %d", s)
+ }
+ }
+ if n := fx.srv.lastSeenWrites.Load(); n != 1 {
+ t.Fatalf("lastSeenWrites after ten GETs = %d, want 1", n)
+ }
+ expireSeen(t, fx, lastSeenPaul, true)
+ before, _ := lastSeenOf(t, fx, lastSeenPaul)
+ if s := getKass(t, fx, c); s != http.StatusOK {
+ t.Fatalf("GET /apps/kass = %d", s)
+ }
+ if n := fx.srv.lastSeenWrites.Load(); n != 2 {
+ t.Fatalf("lastSeenWrites after the hour = %d, want 2", n)
+ }
+ if after, _ := lastSeenOf(t, fx, lastSeenPaul); after <= before {
+ t.Fatalf("last_seen after the hour = %d, want past %d", after, before)
+ }
+}
+
+// TestLastSeenReservationIsAtomic: once the hour has passed, a burst of
+// requests (and a burst of direct calls) writes exactly once. Run with -race.
+func TestLastSeenReservationIsAtomic(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ const n = 64
+
+ expireSeen(t, fx, lastSeenPaul, false)
+ base := fx.srv.lastSeenWrites.Load()
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ statuses := make([]int, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ res, err := c.Get(fx.u("/apps/kass"))
+ if err != nil {
+ return
+ }
+ res.Body.Close()
+ statuses[i] = res.StatusCode
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ for i, s := range statuses {
+ if s != http.StatusOK {
+ t.Fatalf("GET %d = %d", i, s)
+ }
+ }
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 1 {
+ t.Fatalf("%d concurrent GETs after the hour wrote %d times, want 1", n, got)
+ }
+
+ expireSeen(t, fx, lastSeenPaul, false)
+ base = fx.srv.lastSeenWrites.Load()
+ now := time.Now()
+ start = make(chan struct{})
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ fx.srv.noteSeen(lastSeenPaul, now)
+ }()
+ }
+ close(start)
+ wg.Wait()
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 1 {
+ t.Fatalf("%d concurrent noteSeen calls after the hour wrote %d times, want 1", n, got)
+ }
+}
+
+// TestLastSeenFromTheCLI: a person's CLI token counts as being seen, through
+// both a cliRoute door and a cliUser door; a service credential is not a
+// person and writes nothing.
+func TestLastSeenFromTheCLI(t *testing.T) {
+ fx := newConsoleFixture(t)
+ tok := cliToken(t, fx, lastSeenPaul, "code-"+t.Name())
+
+ for _, door := range []string{"/api/cli/apps", "/auth/cli/whoami"} {
+ expireSeen(t, fx, lastSeenPaul, true)
+ before, _ := lastSeenOf(t, fx, lastSeenPaul)
+ base := fx.srv.lastSeenWrites.Load()
+ if status, _ := getJSON(t, fx.ts.URL+door, tok); status != http.StatusOK {
+ t.Fatalf("GET %s with Paul's CLI token = %d", door, status)
+ }
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 1 {
+ t.Fatalf("GET %s with Paul's CLI token wrote %d times, want 1", door, got)
+ }
+ if after, _ := lastSeenOf(t, fx, lastSeenPaul); after <= before {
+ t.Fatalf("GET %s: last_seen = %d, want past %d", door, after, before)
+ }
+ }
+
+ // A service credential: its request reaches the door (or is refused at
+ // the person-only one) and writes nothing for anyone.
+ svc := serviceToken(t, fx.st, OpsAccountID, "hub", "", svcrole.Publish)
+ expireSeen(t, fx, lastSeenPaul, false)
+ snapshot := func() map[string]int64 {
+ rows, err := fx.st.db.Query(`SELECT address, last_seen FROM users`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ out := map[string]int64{}
+ for rows.Next() {
+ var a string
+ var s int64
+ if err := rows.Scan(&a, &s); err != nil {
+ t.Fatal(err)
+ }
+ out[a] = s
+ }
+ return out
+ }
+ before := snapshot()
+ base := fx.srv.lastSeenWrites.Load()
+ if status, _ := getJSON(t, fx.ts.URL+"/api/cli/apps", svc); status != http.StatusOK {
+ t.Fatalf("GET /api/cli/apps with a publish credential = %d", status)
+ }
+ if status, _ := getJSON(t, fx.ts.URL+"/auth/cli/whoami", svc); status != http.StatusUnauthorized {
+ t.Fatalf("GET /auth/cli/whoami with a service credential = %d, want 401", status)
+ }
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 0 {
+ t.Fatalf("service credential requests wrote %d times, want 0", got)
+ }
+ after := snapshot()
+ if len(after) != len(before) {
+ t.Fatalf("users rows %v after a service credential's requests, was %v", after, before)
+ }
+ for a, s := range before {
+ if after[a] != s {
+ t.Fatalf("%s last_seen moved %d -> %d on a service credential's request", a, s, after[a])
+ }
+ }
+}
+
+// TestLastSeenWithNoUserRowIsHarmless: a session whose person has no users
+// row still answers as it does today; the write creates no row, and the
+// hour stays reserved so the next request does not try again.
+func TestLastSeenWithNoUserRowIsHarmless(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ want := getKass(t, fx, c)
+ if _, err := fx.st.db.Exec(`DELETE FROM users WHERE address = ?`, lastSeenPaul); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.seenMu.Lock()
+ clear(fx.srv.seen)
+ fx.srv.seenMu.Unlock()
+ base := fx.srv.lastSeenWrites.Load()
+ if got := getKass(t, fx, c); got != want {
+ t.Fatalf("GET /apps/kass with no users row = %d, want %d as before", got, want)
+ }
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 1 {
+ t.Fatalf("lastSeenWrites = +%d, want +1", got)
+ }
+ // The page's own landing-spot upsert (SetLastAccount) has always made a
+ // users row for a session without one, and it runs after the gate. The
+ // touch ran first, against no row, so a row the page made carries no
+ // last_seen.
+ if seen, ok := lastSeenOf(t, fx, lastSeenPaul); ok && seen != 0 {
+ t.Fatalf("last_seen = %d on a row the touch found missing, want 0", seen)
+ }
+ if got := getKass(t, fx, c); got != want {
+ t.Fatalf("second GET /apps/kass = %d, want %d", got, want)
+ }
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 1 {
+ t.Fatalf("lastSeenWrites after a second GET within the hour = +%d, want +1", got)
+ }
+
+ // The touch on its own, with no page after it, creates no users row.
+ if _, err := fx.st.db.Exec(`DELETE FROM users WHERE address = ?`, lastSeenPaul); err != nil {
+ t.Fatal(err)
+ }
+ expireSeen(t, fx, lastSeenPaul, false)
+ fx.srv.noteSeen(lastSeenPaul, time.Now())
+ if got := fx.srv.lastSeenWrites.Load() - base; got != 2 {
+ t.Fatalf("lastSeenWrites after a direct noteSeen past the hour = +%d, want +2", got)
+ }
+ if _, ok := lastSeenOf(t, fx, lastSeenPaul); ok {
+ t.Fatal("touching last_seen created a users row")
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index add201c7c..b61db99f8 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1350,6 +1350,13 @@ type Server struct {
// every app with records (runsweep.go); zero until the first, which is
// therefore full. Only the run sweep's one goroutine touches it.
lastOrphanFull time.Time
+ // seen is when each person's current last-seen hour was reserved
+ // (lastseen.go), keyed by address and only for addresses that passed a
+ // gate; seenMu guards it. lastSeenWrites counts last_seen write
+ // attempts, for tests only.
+ seenMu sync.Mutex
+ seen map[string]time.Time
+ lastSeenWrites atomic.Int64
}
// edgeFoldTTL is how long one fold of the deployment's edges files stands
@@ -1595,6 +1602,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
scanQueue: objstore.NewQueueIndex(),
perf: cfg.Perf,
billing: newBillingRuntime(cfg.Billing),
+ seen: map[string]time.Time{},
}
if s.perf == nil {
s.perf = &perf.Recorder{}
@@ -2543,11 +2551,13 @@ func (s *Server) session(r *http.Request) (address, rawToken string, ok bool) {
return "", "", false
}
end := perf.Span(r, "db")
- addr, ok := s.store.SessionAddress(c.Value, time.Now())
+ now := time.Now()
+ addr, ok := s.store.SessionAddress(c.Value, now)
end()
if !ok {
return "", "", false
}
+ s.noteSeen(addr, now)
return addr, c.Value, true
}