diff --git a/README.md b/README.md index 348ae61..4018027 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,78 @@ 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 `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 +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; a larger value is treated as 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` (`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) 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. + +`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..294d5e4 --- /dev/null +++ b/internal/handlers/search.go @@ -0,0 +1,52 @@ +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"` +} + +// 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) == "" { + 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,