From 52d2c06d8a0044207a1bc05aae4bc09fc3e9c647 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Sun, 22 Nov 2026 09:03:30 +0800 Subject: [PATCH 1/2] GET /fmsg/search: define the optional search contract; answer 501 Adds the route, its delegated OAuth scope (fmsg:read) and the response shapes for an optional thread search, documented in the README, so clients can rely on one contract. This server does not implement it and answers 501 Not Implemented to an authenticated caller. Before, the path fell through to GET /fmsg/:id and answered 400 "invalid message id". A q with no words (only punctuation) is specified to answer 200 with no threads, which gives clients a cheap way to tell whether a server implements search. Co-Authored-By: Claude Opus 5.5 --- README.md | 68 ++++++++++++++++++++++++++++ cmd/fmsg-webapi/main.go | 1 + cmd/fmsg-webapi/search_route_test.go | 50 ++++++++++++++++++++ internal/handlers/search.go | 49 ++++++++++++++++++++ internal/middleware/oauth.go | 1 + 5 files changed, 169 insertions(+) create mode 100644 cmd/fmsg-webapi/search_route_test.go create mode 100644 internal/handlers/search.go diff --git a/README.md b/README.md index 348ae61..cc5ea6b 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,7 @@ the application. | `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/search` | Find the identity's threads by words (optional; `501` here) | | `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 | @@ -646,6 +647,73 @@ from listed messages. Drafts don't count. **Response:** `200 OK` with `{"threads": }`. +### GET `/fmsg/search` + +**Optional; this server answers `501 Not Implemented`.** The route, the +OAuth scope (`fmsg:read`) and the shapes below are defined so that clients can +rely on one contract, and a deployment that indexes message text can implement +it. Clients should treat `501` (or `404` from older servers) as "search is not +available" and offer no search. + +Finds the authenticated identity's threads by the words in their messages and +returns each matching thread whole, so a client can list them without first +paging in every message. + +A thread is grouped as for `GET /fmsg/count`: a message belongs with its +parent when the identity can see the parent, so the first message the identity +can see is the thread's root. A thread matches when one of its messages has +every word of `q`. Each word matches the start of a word in the message's +topic, sender and recipient addresses, attachment names or text body; case and +accents don't matter. An +[FMSG-008](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md) +edited message is found by its edited words as well as its original ones, and +its match shows the edited text; edit messages themselves, like reactions, are +never results. A draft is found by its author only. The other filters apply to +the thread as a whole. + +**Query parameters:** + +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `q` | — | Words to find. Empty lists every thread the filters allow. A `q` with no words in it (only punctuation) matches nothing and answers `200` with no threads | +| `sort` | `newest` | `newest` or `oldest`, by each thread's newest message | +| `files` | `false` | `true`: only threads with an attachment | +| `unread` | `false` | `true`: only threads with a message the identity hasn't read | +| `scope` | `all` | `drafts`: only threads with a draft of the identity's | +| `trash` | `exclude` | `exclude`: threads with something outside the trash, matched on those messages. `only`: threads with something in the trash | +| `limit` | `25` | Threads per page, at most 50 | +| `offset` | `0` | Threads to skip | + +**Response:** `200 OK` + +```json +{ + "total": 42, + "next_offset": 25, + "terms": ["sign", "frag"], + "threads": [ + { "root": 812, "time": 1794300120.5, + "match": { "id": 845, "field": "body", "text": "…the sign-in fragment is used…" } } + ], + "messages": [ { "id": 812, "…": "…" } ] +} +``` + +- `threads` are in order. `time` is the newest message's time (null for a + thread of drafts). `match` is the newest message with the words: `field` is + `body`, `topic`, `file`, `from` or `to`, and `text` the text to show for it. + It is null when `q` is empty. +- `messages` holds every message of those threads, shaped as in `GET /fmsg`, + including ones in the trash (`trash` set) so the thread can be grouped. + Reactions are left out. +- `next_offset` is the `offset` of the next page, null on the last. A page + may end early when its threads hold many messages. +- `terms` are the words of `q` as matched (folded), for highlighting. + +`400` for an invalid parameter. A search that runs too long answers `503`. +Search words are message content, so an implementation should keep `q` out of +its logs. + ### 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 c15e113..e498d5f 100644 --- a/cmd/fmsg-webapi/main.go +++ b/cmd/fmsg-webapi/main.go @@ -288,6 +288,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.GET("/search", msgHandler.Search) fmsg.POST("", msgHandler.Atomic((*handlers.MessageHandler).Create)) fmsg.GET("/:id", msgHandler.Get) fmsg.PUT("/:id", msgHandler.Atomic((*handlers.MessageHandler).Update)) diff --git a/cmd/fmsg-webapi/search_route_test.go b/cmd/fmsg-webapi/search_route_test.go new file mode 100644 index 0000000..a71f39f --- /dev/null +++ b/cmd/fmsg-webapi/search_route_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/markmnl/fmsg-webapi/internal/handlers" + "github.com/markmnl/fmsg-webapi/internal/middleware" +) + +// TestSearchNotImplemented: GET /fmsg/search is routed to the search handler, +// not taken as GET /fmsg/:id, and answers 501 to an authenticated caller and +// 401 otherwise. +func TestSearchNotImplemented(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + msgs := handlers.NewMessageHandler(nil, "", 0, 0, 0, nil, "", "") + identity := func(c *gin.Context) { + if id := c.GetHeader("X-Test-Identity"); id != "" { + c.Set(middleware.IdentityKey, id) + } + } + registerRoutes(router, identity, msgs, + handlers.NewAttachmentHandler(nil, "", 0, 0), + handlers.NewTokenHandler(nil, nil, ""), + handlers.NewSubAccountHandler(nil, ""), + handlers.NewPushHandler(nil, msgs, "", "", "", ""), + handlers.NewWSHandler(nil, handlers.NewHub(msgs), nil)) + + for _, tc := range []struct { + identity string + want int + }{ + {"@alice@example.com", http.StatusNotImplemented}, + {"", http.StatusUnauthorized}, + } { + req := httptest.NewRequest(http.MethodGet, "/fmsg/search?q=hello&limit=1", nil) + if tc.identity != "" { + req.Header.Set("X-Test-Identity", tc.identity) + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != tc.want { + t.Errorf("identity %q: status %d, want %d (body %s)", tc.identity, rec.Code, tc.want, rec.Body.String()) + } + } +} diff --git a/internal/handlers/search.go b/internal/handlers/search.go new file mode 100644 index 0000000..3f2c9c4 --- /dev/null +++ b/internal/handlers/search.go @@ -0,0 +1,49 @@ +package handlers + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/markmnl/fmsg-webapi/internal/middleware" +) + +// Search. GET /fmsg/search is an optional endpoint: it finds the caller's +// threads by the words in their messages and returns them whole. This server +// defines the route and the shapes below so clients can rely on one contract +// (see the README), but does not implement it: it answers 501 Not +// Implemented. A deployment that indexes message text can implement it. + +type searchMatch struct { + ID int64 `json:"id"` + // Field is where the words were found: body, topic, file, from or to. + Field string `json:"field"` + Text string `json:"text"` +} + +type searchThread struct { + Root int64 `json:"root"` + // Time is when the thread was last active: its newest message's time. + Time *float64 `json:"time"` + // Match is the newest message of the thread that has the words; null + // when there were no words to find. + Match *searchMatch `json:"match"` +} + +type searchResponse struct { + // Total is how many threads match, over all pages. + Total int64 `json:"total"` + // NextOffset is the offset of the next page, null when this is the last. + NextOffset *int `json:"next_offset"` + Terms []string `json:"terms"` + Threads []searchThread `json:"threads"` + Messages []messageListItem `json:"messages"` +} + +// Search handles GET /fmsg/search. Not implemented by this server. +func (h *MessageHandler) Search(c *gin.Context) { + if middleware.GetIdentity(c) == "" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + c.JSON(http.StatusNotImplemented, gin.H{"error": "search is not implemented by this host"}) +} diff --git a/internal/middleware/oauth.go b/internal/middleware/oauth.go index 18b37bc..d95c972 100644 --- a/internal/middleware/oauth.go +++ b/internal/middleware/oauth.go @@ -31,6 +31,7 @@ var oauthRouteScopes = map[string]string{ "GET /fmsg": ScopeRead, "GET /fmsg/sent": ScopeRead, "GET /fmsg/count": ScopeRead, + "GET /fmsg/search": ScopeRead, "GET /fmsg/:id": ScopeRead, "GET /fmsg/:id/data": ScopeRead, "GET /fmsg/:id/thread": ScopeRead, From 7bcd3616718530677dd8d0de39ab22015505db1c Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Sun, 22 Nov 2026 10:58:39 +0800 Subject: [PATCH 2/2] search: README clarifications from review - Clients treat 501, or 400/404 from servers predating the endpoint, as no search; document the q=- probe. - limit above 50 is treated as 50; match field to includes added recipients. - messages include edit and trashed messages for grouping; clients leave them out of counts unless trash=only. - Keep the contract types referenced so unused-code checks stay quiet. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++++++++++++------- internal/handlers/search.go | 3 +++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cc5ea6b..4018027 100644 --- a/README.md +++ b/README.md @@ -652,8 +652,11 @@ from listed messages. Drafts don't count. **Optional; this server answers `501 Not Implemented`.** The route, the OAuth scope (`fmsg:read`) and the shapes below are defined so that clients can rely on one contract, and a deployment that indexes message text can implement -it. Clients should treat `501` (or `404` from older servers) as "search is not -available" and offer no search. +it. Clients should treat `501`, or `400`/`404` from servers that predate this +endpoint (they take `search` for a message id), as search not being available, +and offer no search. To check whether a server implements search, request +`GET /fmsg/search?q=-&limit=1`: `q` has no words, so a server that implements +search answers `200` without searching. Finds the authenticated identity's threads by the words in their messages and returns each matching thread whole, so a client can list them without first @@ -681,7 +684,7 @@ the thread as a whole. | `unread` | `false` | `true`: only threads with a message the identity hasn't read | | `scope` | `all` | `drafts`: only threads with a draft of the identity's | | `trash` | `exclude` | `exclude`: threads with something outside the trash, matched on those messages. `only`: threads with something in the trash | -| `limit` | `25` | Threads per page, at most 50 | +| `limit` | `25` | Threads per page; a larger value is treated as 50 | | `offset` | `0` | Threads to skip | **Response:** `200 OK` @@ -701,11 +704,13 @@ the thread as a whole. - `threads` are in order. `time` is the newest message's time (null for a thread of drafts). `match` is the newest message with the words: `field` is - `body`, `topic`, `file`, `from` or `to`, and `text` the text to show for it. - It is null when `q` is empty. + `body`, `topic`, `file`, `from` or `to` (`to` includes recipients added + later), and `text` the text to show for it. It is null when `q` is empty. - `messages` holds every message of those threads, shaped as in `GET /fmsg`, - including ones in the trash (`trash` set) so the thread can be grouped. - Reactions are left out. + including ones in the trash (`trash` set) and edit messages (`edit` set), so + the thread can be grouped. Reactions are left out. Clients should leave edit + messages out of counts and previews, and trashed messages too unless + `trash=only`. - `next_offset` is the `offset` of the next page, null on the last. A page may end early when its threads hold many messages. - `terms` are the words of `q` as matched (folded), for highlighting. diff --git a/internal/handlers/search.go b/internal/handlers/search.go index 3f2c9c4..294d5e4 100644 --- a/internal/handlers/search.go +++ b/internal/handlers/search.go @@ -39,6 +39,9 @@ type searchResponse struct { Messages []messageListItem `json:"messages"` } +// The types above are the contract; nothing here builds them yet. +var _ = searchResponse{Threads: []searchThread{{Match: &searchMatch{}}}} + // Search handles GET /fmsg/search. Not implemented by this server. func (h *MessageHandler) Search(c *gin.Context) { if middleware.GetIdentity(c) == "" {