Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,9 @@ such a message carries (`""` for a clearing reaction) and `null` for every
other message, so clients can hide reaction messages from message lists.
`reactions` lists the effective reactions on this message: each participant's
latest reaction, grouped by emoji in order of first reaction, with the
reactors of each. It is `[]` when there are none.
reactors of each. It is `[]` when there are none. An add-to batch is a message
of its own (its own `sha256` and participants), so its reactions are listed on
it, as `add_to[].reactions` (omitted when there are none), not on the message.

`edit` and `edited` implement
[FMSG-008 Edits](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md). An edit is an ordinary message: a reply from the
Expand Down Expand Up @@ -999,13 +1001,21 @@ recipients isn't counted against the caller's send limits (see

Sets or clears the authenticated identity's reaction on a message, per
[FMSG-005 Reactions](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-005-reactions.md).
The identity must be a participant of the message — the sender or a recipient
in `to` or `add_to` — and the message must be sent and not terminal.

The reaction is sent immediately as a reaction message: a reply to `:id` with
`no_reply` and `terminal` set, type `text/plain;charset=UTF-8`, body the emoji,
addressed to every other participant of the message, or to the caller alone
for a message they sent only to themselves. Delivery then proceeds
`:id` names the message reacted to: a message id or `sha256`, or the `sha256`
of an add-to batch. An add-to batch is a message of its own — the original's
contents with a wider audience — so a reaction to it is to that batch, not to
the original. Named by id, a message the identity was only added to (in a
batch) is that batch, the only one of them they have. The identity must be a
participant of the message reacted to — its sender or a recipient in `to`, and
for a batch also its adder or a recipient it added — and the message must be
sent and not terminal.

The reaction is sent immediately as a reaction message: a reply to that
message (`psha256` its hash) with `no_reply` and `terminal` set, type
`text/plain;charset=UTF-8`, body the emoji, addressed to every other
participant of that message — for the original not those only added in
batches, for a batch also its adder and the recipients it added — or to the
caller alone for a message they sent only to themselves. Delivery then proceeds
exactly as for any sent message, and like any message it counts against the
reactor's send limits and each local recipient's receive limits (see
[Quotas](#quotas)). A reaction message cannot be replied to, reacted to, or
Expand All @@ -1017,7 +1027,8 @@ have recipients added.
| ------- | -------- | -------- | ----------- |
| `emoji` | `string` | no | A single emoji (a Unicode `RGI_Emoji` sequence, or any single well-formed emoji sequence). `""` or `null` clears the caller's reaction. |

Setting the same reaction the caller already has is idempotent: nothing is
Each message — the original and each batch — has its own reactions.
Setting the same reaction the caller already has on it is idempotent: nothing is
sent and the existing reaction message is returned with `200 OK`. Clearing when
the caller has no reaction returns `200 OK` with `null` values.

Expand Down
10 changes: 2 additions & 8 deletions internal/handlers/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -699,10 +699,7 @@ func (h *MessageHandler) Get(c *gin.Context) {
// Compute ShortText only after authorization has been confirmed.
msg.ShortText = h.extractShortText(dataPath, msg.Type)
msg.Reaction = h.reactionOf(msg.HasPid, msg.NoReply, msg.Terminal, msg.Important, msg.HasAddTo, msg.Type, msg.Size, len(msg.Attachments), dataPath)
msg.Reactions = h.loadReactions(ctx, []int64{msgID})[msgID]
if msg.Reactions == nil {
msg.Reactions = []models.Reaction{}
}
msg.Reactions = applyReactions(h.loadReactions(ctx, []int64{msgID}), msgID, msg.AddTo)
if editShape(msg.HasPid, msg.NoReply, msg.Terminal, msg.Important, msg.HasAddTo, msg.Type, len(msg.Attachments)) {
_, msg.Edit = h.editSubject(ctx, msgID)
}
Expand Down Expand Up @@ -1579,10 +1576,7 @@ func (h *MessageHandler) messageItemFor(ctx context.Context, msgID int64, recipi
dataPath: dataPath,
}
item.Reaction = h.reactionOf(item.HasPid, item.NoReply, item.Terminal, item.Important, item.HasAddTo, item.Type, item.Size, len(item.Attachments), dataPath)
item.Reactions = h.loadReactions(ctx, []int64{msgID})[msgID]
if item.Reactions == nil {
item.Reactions = []models.Reaction{}
}
item.Reactions = applyReactions(h.loadReactions(ctx, []int64{msgID}), msgID, item.AddTo)
if editShape(item.HasPid, item.NoReply, item.Terminal, item.Important, item.HasAddTo, item.Type, len(item.Attachments)) {
_, item.Edit = h.editSubject(ctx, msgID)
}
Expand Down
31 changes: 20 additions & 11 deletions internal/handlers/quota_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func TestLocalDeliveryChecksAndRecordsReceiveQuota(t *testing.T) {
// usage recorded; adding recipients sends no new message.
erin, frank := "@erin@example.com", "@frank@example.com"
id.set(frank, map[string]any{"limitRecvSizePer1d": 10})
jsonResponse(t, a.request("@alice@example.com", "POST", "/fmsg/"+msg+"/add-to", map[string]any{"add_to": []string{erin, frank}}), 200)
batch := jsonResponse(t, a.request("@alice@example.com", "POST", "/fmsg/"+msg+"/add-to", map[string]any{"add_to": []string{erin, frank}}), 200)
rows = a.recipientRows(t, "msg_add_to", msg)
wantRow(t, rows, erin, true, responseCodeAccept)
wantRow(t, rows, frank, false, responseCodeUserFull)
Expand All @@ -195,17 +195,26 @@ func TestLocalDeliveryChecksAndRecordsReceiveQuota(t *testing.T) {
if len(send) != 2 || send[1].Address != bob || send[1].Size != int64(len("👍")) {
t.Fatalf("reaction send usage: %+v", send)
}
// carol is still full, and nobody unknown; alice, dave, erin and frank
// each have room for the reaction.
recv = id.posted("recv")[2:]
gotRecv := map[string]int64{}
for _, u := range recv {
gotRecv[u.Address] = u.Size
}
want := map[string]int64{"@alice@example.com": 4, dave: 4, erin: 4, frank: 4}
if fmt.Sprint(gotRecv) != fmt.Sprint(want) || len(recv) != len(want) {
t.Fatalf("reaction recv usage: %+v, want %v", recv, want)
// The reaction goes to the message's participants: carol is still full,
// nobody unknown, and alice and dave each have room. erin and frank were
// added in a batch, a message of its own: they don't get it.
wantRecv := func(from int, want map[string]int64) {
t.Helper()
recv := id.posted("recv")[from:]
gotRecv := map[string]int64{}
for _, u := range recv {
gotRecv[u.Address] = u.Size
}
if fmt.Sprint(gotRecv) != fmt.Sprint(want) || len(recv) != len(want) {
t.Fatalf("reaction recv usage: %+v, want %v", recv, want)
}
}
wantRecv(2, map[string]int64{"@alice@example.com": 4, dave: 4})
// A reaction on the batch goes to its participants: the message's and
// those it added.
n := len(id.posted("recv"))
jsonResponse(t, a.request(bob, "POST", "/fmsg/"+batch["sha256"].(string)+"/react", map[string]any{"emoji": "👍"}), 201)
wantRecv(n, map[string]int64{"@alice@example.com": 4, dave: 4, erin: 4, frank: 4})
}

func TestSendRefusedOverSendQuota(t *testing.T) {
Expand Down
122 changes: 93 additions & 29 deletions internal/handlers/reactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,18 @@ func (h *MessageHandler) reactionSubject(ctx context.Context, msgID int64) (int6
return *pid, true
}

// reactionKey names a reaction's subject: a message, or one add-to batch of
// it (batch is that batch's hex sha256). A batch is a message of its own, so
// its reactions are its own, not the original's.
type reactionKey struct {
msgID int64
batch string
}

// reactionRow is one stored reaction message on a subject.
type reactionRow struct {
subjectID int64
batch string // hex sha256 of the add-to batch the reaction names; "" for the message itself
msgID int64
from string
time float64
Expand All @@ -141,21 +150,22 @@ func newerReaction(a, b reactionRow) bool {
// reactions: one per reactor, grouped by emoji in order of first reaction,
// reactors within a group in time order. A reactor whose effective reaction is
// empty has none and is omitted.
func effectiveReactions(rows []reactionRow) map[int64][]models.Reaction {
bySubject := make(map[int64]map[string]reactionRow)
func effectiveReactions(rows []reactionRow) map[reactionKey][]models.Reaction {
bySubject := make(map[reactionKey]map[string]reactionRow)
for _, r := range rows {
reactors := bySubject[r.subjectID]
k := reactionKey{r.subjectID, r.batch}
reactors := bySubject[k]
if reactors == nil {
reactors = make(map[string]reactionRow)
bySubject[r.subjectID] = reactors
bySubject[k] = reactors
}
key := strings.ToLower(r.from)
if cur, ok := reactors[key]; !ok || newerReaction(r, cur) {
reactors[key] = r
}
}

result := make(map[int64][]models.Reaction, len(bySubject))
result := make(map[reactionKey][]models.Reaction, len(bySubject))
for subject, reactors := range bySubject {
var eff []reactionRow
for _, r := range reactors {
Expand Down Expand Up @@ -195,8 +205,9 @@ func (h *MessageHandler) loadReactionRows(ctx context.Context, subjectIDs []int6
return nil, nil
}
rows, err := h.q().Query(ctx, `
SELECT r.pid, r.id, r.from_addr, r.time_sent, r.sha256, r.size, r.filepath
SELECT r.pid, COALESCE(encode(sb.sha256, 'hex'), ''), r.id, r.from_addr, r.time_sent, r.sha256, r.size, r.filepath
FROM msg r
LEFT JOIN msg_add_to_batch sb ON sb.msg_id = r.pid AND sb.sha256 = r.psha256
WHERE r.pid = ANY($1)
AND r.time_sent IS NOT NULL
AND r.is_terminal AND r.no_reply AND NOT r.is_important
Expand All @@ -217,7 +228,7 @@ func (h *MessageHandler) loadReactionRows(ctx context.Context, subjectIDs []int6
var r reactionRow
var size int
var dataPath string
if err := rows.Scan(&r.subjectID, &r.msgID, &r.from, &r.time, &r.hash, &size, &dataPath); err != nil {
if err := rows.Scan(&r.subjectID, &r.batch, &r.msgID, &r.from, &r.time, &r.hash, &size, &dataPath); err != nil {
return nil, err
}
e, ok := h.readReactionData(dataPath, size)
Expand All @@ -230,8 +241,9 @@ func (h *MessageHandler) loadReactionRows(ctx context.Context, subjectIDs []int6
return out, rows.Err()
}

// loadReactions returns the effective reactions on each of the given subjects.
func (h *MessageHandler) loadReactions(ctx context.Context, subjectIDs []int64) map[int64][]models.Reaction {
// loadReactions returns the effective reactions on each of the given messages
// and on each of their add-to batches.
func (h *MessageHandler) loadReactions(ctx context.Context, subjectIDs []int64) map[reactionKey][]models.Reaction {
rows, err := h.loadReactionRows(ctx, subjectIDs, "")
if err != nil {
log.Printf("load reactions: %v", err)
Expand All @@ -240,6 +252,20 @@ func (h *MessageHandler) loadReactions(ctx context.Context, subjectIDs []int64)
return effectiveReactions(rows)
}

// applyReactions sets each add-to batch's own reactions and returns the
// message's (never nil).
func applyReactions(set map[reactionKey][]models.Reaction, msgID int64, addTo []models.AddToBatch) []models.Reaction {
for i := range addTo {
if addTo[i].SHA256 != nil {
addTo[i].Reactions = set[reactionKey{msgID, strings.ToLower(*addTo[i].SHA256)}]
}
}
if r := set[reactionKey{msgID, ""}]; r != nil {
return r
}
return []models.Reaction{}
}

// populateListReactions fills Reaction and Reactions on every list item.
func (h *MessageHandler) populateListReactions(ctx context.Context, items []messageListItem) {
ids := make([]int64, len(items))
Expand All @@ -250,17 +276,17 @@ func (h *MessageHandler) populateListReactions(ctx context.Context, items []mess
}
reactions := h.loadReactions(ctx, ids)
for i := range items {
items[i].Reactions = reactions[items[i].ID]
if items[i].Reactions == nil {
items[i].Reactions = []models.Reaction{}
}
items[i].Reactions = applyReactions(reactions, items[i].ID, items[i].AddTo)
}
}

// reactionRecipients returns a subject's participants other than the reactor,
// in message order and deduplicated case-insensitively: the to list of a
// reaction (FMSG-005 Recipients).
func reactionRecipients(subject *models.Message, reactor string) []string {
// reaction (FMSG-005 Recipients). The subject is the message, or, when batch
// is set, that add-to batch of it: a message of its own, whose participants
// are also its adder and the recipients it added. Other batches' recipients
// are not participants of the subject.
func reactionRecipients(subject *models.Message, batch *models.AddToBatch, reactor string) []string {
seen := map[string]bool{strings.ToLower(reactor): true}
var out []string
add := func(addr string) {
Expand All @@ -275,15 +301,37 @@ func reactionRecipients(subject *models.Message, reactor string) []string {
for _, a := range subject.To {
add(a)
}
for _, b := range subject.AddTo {
add(b.AddToFrom)
for _, a := range b.To {
if batch != nil {
add(batch.AddToFrom)
for _, a := range batch.To {
add(a)
}
}
return out
}

// reactSubject resolves the :id of POST /fmsg/:id/react: a message id or
// sha256, or the sha256 of an add-to batch, which is a message of its own. It
// returns the message id the batch is stored with and the batch hash ("" for
// the message itself).
func reactSubject(c *gin.Context, q queries) (int64, string, bool) {
if s := strings.ToLower(c.Param("id")); len(s) == 64 {
if hash, err := decodeHash(s); err == nil {
var id int64
err := q.QueryRow(c.Request.Context(), `SELECT msg_id FROM msg_add_to_batch WHERE sha256 = $1 LIMIT 1`, hash).Scan(&id)
if err == nil {
return id, s, true
}
if !errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to resolve message"})
return 0, "", false
}
}
}
id, ok := resolveID(c, q)
return id, "", ok
}

// reactInput is the request body of POST /fmsg/:id/react.
type reactInput struct {
Emoji *string `json:"emoji"` // a single emoji; null or "" clears the caller's reaction
Expand All @@ -295,7 +343,7 @@ type reactInput struct {
// idempotent and sends nothing.
func (h *MessageHandler) React(c *gin.Context) {
identity := middleware.GetIdentity(c)
msgID, ok := resolveID(c, h.q())
msgID, batchHash, ok := reactSubject(c, h.q())
if !ok {
return
}
Expand Down Expand Up @@ -330,12 +378,31 @@ func (h *MessageHandler) React(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
// The subject: the message, or the add-to batch named by its hash.
// Named by id, a caller who was only added has just their batch, so that
// is what they react to.
onOriginal := strings.EqualFold(subject.From, identity) || isRecipient(subject.To, identity)
var batch *models.AddToBatch
for i := range subject.AddTo {
b := &subject.AddTo[i]
if b.SHA256 == nil {
continue
}
if batchHash != "" && strings.EqualFold(*b.SHA256, batchHash) || batchHash == "" && !onOriginal && isRecipient(b.To, identity) {
batch = b
break
}
}
// Only a participant of the subject may react to it (the host enforces
// the same rule on the wire).
if !strings.EqualFold(subject.From, identity) && !isRecipient(subject.To, identity) && !addToContains(subject.AddTo, identity) {
if !onOriginal && (batch == nil || !isRecipient(batch.To, identity)) {
c.JSON(http.StatusForbidden, gin.H{"error": "only participants may react to a message"})
return
}
subjectBatch := ""
if batch != nil {
subjectBatch = strings.ToLower(*batch.SHA256)
}
if subject.Time == nil {
c.JSON(http.StatusConflict, gin.H{"error": "cannot react to a draft"})
return
Expand All @@ -345,7 +412,7 @@ func (h *MessageHandler) React(c *gin.Context) {
return
}

recipients := reactionRecipients(subject, identity)
recipients := reactionRecipients(subject, batch, identity)
if len(recipients) == 0 {
// A message the caller sent only to themselves: the reaction is
// addressed to the caller (FMSG-005 v0.1.1).
Expand All @@ -361,6 +428,9 @@ func (h *MessageHandler) React(c *gin.Context) {
}
var current *reactionRow
for i := range mine {
if mine[i].batch != subjectBatch {
continue // a reaction on another message: the original or another batch
}
if current == nil || newerReaction(mine[i], *current) {
current = &mine[i]
}
Expand Down Expand Up @@ -390,14 +460,8 @@ func (h *MessageHandler) React(c *gin.Context) {
}

parentHash := subject.SHA256
if !sameAddr(subject.From, identity) && !isRecipient(subject.To, identity) {
parentHash = nil
for _, b := range subject.AddTo {
if isRecipient(b.To, identity) {
parentHash = b.SHA256
break
}
}
if batch != nil {
parentHash = batch.SHA256
}
if parentHash == nil {
c.JSON(500, gin.H{"error": "reaction parent has no finalized identity"})
Expand Down
Loading