From 3cda5cfdb3d3a9c7d2d7faf311520c3fd0211b70 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Sun, 1 Nov 2026 17:46:45 +0800 Subject: [PATCH] GET /fmsg/count: how many threads the identity has Lets a client show "93 of 8,324 threads" while it pages through the lists. Each sent message the identity can see (sender, recipient or added recipient) whose parent it can't also see starts a thread, which is how clients group threads from listed messages; drafts don't count. ?trash= as for GET /fmsg. Read scope for delegated OAuth tokens. Co-Authored-By: Claude Opus 5.5 --- README.md | 17 ++++++ cmd/fmsg-webapi/main.go | 1 + internal/handlers/count.go | 56 +++++++++++++++++++ internal/handlers/count_integration_test.go | 43 ++++++++++++++ .../handlers/finalization_integration_test.go | 1 + internal/middleware/oauth.go | 1 + 6 files changed, 119 insertions(+) create mode 100644 internal/handlers/count.go create mode 100644 internal/handlers/count_integration_test.go diff --git a/README.md b/README.md index c96dbe7..81d093c 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,7 @@ the application. | `GET` | `/healthz` | Health check (no auth): `200 ok`, or `503` when the database is unreachable | | `GET` | `/fmsg` | List messages for the authenticated identity | | `GET` | `/fmsg/sent` | List authored messages (sent + drafts) | +| `GET` | `/fmsg/count` | Count the identity's threads | | `GET` | `/fmsg/ws` | WebSocket for pushed event notifications | | `POST` | `/fmsg/token` | Exchange an API key for a JWT | | `GET` | `/fmsg/sub-accounts` | List owned API-access grants | @@ -627,6 +628,22 @@ This includes both sent messages and drafts (`time_sent` may be `NULL`). **Response:** JSON array of message objects with the same shape as `GET /fmsg`. +### GET `/fmsg/count` + +How many threads the authenticated identity has, for a client to show "93 of +8,324 threads" while it pages through the lists. Every sent message the +identity can see (as its sender, a recipient or an added recipient) whose +parent it can't also see starts one thread, which is how a thread is grouped +from listed messages. Drafts don't count. + +**Query parameters:** + +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `trash` | `exclude` | As for `GET /fmsg`: `exclude`, `include` or `only` | + +**Response:** `200 OK` with `{"threads": }`. + ### POST `/fmsg` Creates a draft message. The `from` address must match the authenticated user. The message is stored with `time_sent = NULL` (draft status) until explicitly sent. diff --git a/cmd/fmsg-webapi/main.go b/cmd/fmsg-webapi/main.go index 6566f49..b63d5d9 100644 --- a/cmd/fmsg-webapi/main.go +++ b/cmd/fmsg-webapi/main.go @@ -287,6 +287,7 @@ func registerRoutes(router *gin.Engine, jwtMiddleware gin.HandlerFunc, msgHandle fmsg.GET("", msgHandler.List) fmsg.GET("/sent", msgHandler.Sent) + fmsg.GET("/count", msgHandler.Count) fmsg.POST("", msgHandler.Atomic((*handlers.MessageHandler).Create)) fmsg.GET("/:id", msgHandler.Get) fmsg.PUT("/:id", msgHandler.Atomic((*handlers.MessageHandler).Update)) diff --git a/internal/handlers/count.go b/internal/handlers/count.go new file mode 100644 index 0000000..50b698d --- /dev/null +++ b/internal/handlers/count.go @@ -0,0 +1,56 @@ +package handlers + +import ( + "log" + "net/http" + + "github.com/gin-gonic/gin" +) + +// Count handles GET /fmsg/count: how many threads the authenticated identity +// has, for showing "93 of 8,324 threads" while the list is paged in. A thread +// is counted once for each sent message the identity can see (as its sender, +// a recipient or an added recipient) whose parent it can't also see, which is +// how clients group a thread from listed messages. trash is as for GET /fmsg: +// exclude (default), include or only. +func (h *MessageHandler) Count(c *gin.Context) { + addrs, err := h.visibleAddrs(c) + if err != nil { + log.Printf("count threads: resolve visible addrs: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count threads"}) + return + } + trashFilter, ok := trashListFilter(c) + if !ok { + return + } + ctx := c.Request.Context() + hasTrash, err := h.hasTrash(ctx, addrs[0]) + if err != nil { + log.Printf("count threads: trash: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count threads"}) + return + } + var threads int64 + err = h.q().QueryRow(ctx, + `WITH vis AS ( + SELECT m.id, m.pid + FROM msg m + CROSS JOIN LATERAL (SELECT CASE WHEN $2 THEN fmsg_api_trash_state($3, m.id) END AS state) t + WHERE m.time_sent IS NOT NULL + AND (lower(m.from_addr) = ANY($1) + OR EXISTS (SELECT 1 FROM msg_to mt WHERE mt.msg_id = m.id AND lower(mt.addr) = ANY($1)) + OR EXISTS (SELECT 1 FROM msg_add_to mat WHERE mat.msg_id = m.id AND lower(mat.addr) = ANY($1))) + AND `+trashFilter+` + ) + SELECT count(*) FROM vis v + WHERE v.pid IS NULL OR NOT EXISTS (SELECT 1 FROM vis p WHERE p.id = v.pid)`, + addrs, hasTrash, addrs[0], + ).Scan(&threads) + if err != nil { + log.Printf("count threads: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count threads"}) + return + } + c.JSON(http.StatusOK, gin.H{"threads": threads}) +} diff --git a/internal/handlers/count_integration_test.go b/internal/handlers/count_integration_test.go new file mode 100644 index 0000000..1483705 --- /dev/null +++ b/internal/handlers/count_integration_test.go @@ -0,0 +1,43 @@ +package handlers + +import ( + "net/http" + "testing" +) + +func TestCountThreads(t *testing.T) { + a := newFinalizationAPI(t) + count := func(who, query string) float64 { + t.Helper() + return jsonResponse(t, a.request(who, "GET", "/fmsg/count"+query, nil), http.StatusOK)["threads"].(float64) + } + + first := a.sendAs(t, alice, []string{bob}, "first thread", nil) + a.sendAs(t, bob, []string{alice}, "a reply is the same thread", mustID(t, first)) + a.sendAs(t, alice, []string{bob, carol}, "second thread", nil) + a.draft(t, bob, "a draft is not a thread", nil) + + for who, want := range map[string]float64{alice: 2, bob: 2, carol: 1} { + if got := count(who, ""); got != want { + t.Errorf("%s: %v threads, want %v", who, got, want) + } + } + if got := count("@dave@example.com", ""); got != 0 { + t.Errorf("an outsider: %v threads, want 0", got) + } + + // A thread in the trash leaves the default count, and is counted by trash=only. + jsonResponse(t, a.request(bob, "DELETE", "/fmsg/"+first+"?thread=true", nil), http.StatusOK) + if got := count(bob, ""); got != 1 { + t.Errorf("bob after trashing a thread: %v, want 1", got) + } + if got := count(bob, "?trash=only"); got != 1 { + t.Errorf("bob's trash: %v, want 1", got) + } + if got := count(bob, "?trash=include"); got != 2 { + t.Errorf("bob including trash: %v, want 2", got) + } + if w := a.request(bob, "GET", "/fmsg/count?trash=nope", nil); w.Code != http.StatusBadRequest { + t.Errorf("bad trash value: HTTP %d", w.Code) + } +} diff --git a/internal/handlers/finalization_integration_test.go b/internal/handlers/finalization_integration_test.go index b352f51..2e64e44 100644 --- a/internal/handlers/finalization_integration_test.go +++ b/internal/handlers/finalization_integration_test.go @@ -95,6 +95,7 @@ func newFinalizationAPIWithID(t *testing.T, fmsgID http.Handler) *finalizationAP r.DELETE("/fmsg/:id", h.Atomic((*MessageHandler).Delete)) r.GET("/fmsg", h.List) r.GET("/fmsg/sent", h.Sent) + r.GET("/fmsg/count", h.Count) r.GET("/fmsg/:id", h.Get) r.GET("/fmsg/:id/data", h.DownloadData) r.POST("/fmsg/:id/send", h.Atomic((*MessageHandler).Send)) diff --git a/internal/middleware/oauth.go b/internal/middleware/oauth.go index c006245..f714fc2 100644 --- a/internal/middleware/oauth.go +++ b/internal/middleware/oauth.go @@ -30,6 +30,7 @@ const IdentitiesClaim = "fmsg_identities" var oauthRouteScopes = map[string]string{ "GET /fmsg": ScopeRead, "GET /fmsg/sent": ScopeRead, + "GET /fmsg/count": ScopeRead, "GET /fmsg/:id": ScopeRead, "GET /fmsg/:id/data": ScopeRead, "GET /fmsg/:id/thread": ScopeRead,