Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Fix Space comment retries, push quota, and recipient visibility

Anand Baburajanc2c20dc4be16
diff --git a/server/space/controller/comments.go b/server/space/controller/comments.go
index b11441e8a8..5dccfbb81b 100644
--- a/server/space/controller/comments.go
+++ b/server/space/controller/comments.go
@@ -58,10 +58,13 @@ func (c *CommentsController) Create(ctx context.Context, space *repo.SpaceRecord
if err != nil {
return err
}
- if err := c.Repo.Create(ctx, space.SpaceID, postID, req, cipher); err != nil {
+ created, err := c.Repo.CreateWithCreated(ctx, space.SpaceID, postID, req, cipher)
+ if err != nil {
return err
}
- c.notify(ctx, space, postID, req.CommentID, false)
+ if created {
+ c.notify(ctx, space, postID, req.CommentID, false)
+ }
return nil
}
@@ -89,7 +92,5 @@ func (c *CommentsController) notify(ctx context.Context, actor *repo.SpaceRecord
if err != nil {
return
}
- for _, recipient := range recipients {
- go c.ActivityNotifier.OnSpaceComment(spaceActivityActor(actor), recipient.UserID, spaceActivityActor(&owner), postID, commentID, recipient.Kind)
- }
+ go c.ActivityNotifier.OnSpaceComment(spaceActivityActor(actor), recipients, spaceActivityActor(&owner), postID, commentID)
}
diff --git a/server/space/controller/comments_test.go b/server/space/controller/comments_test.go
index 76673ffc66..2e101f7e50 100644
--- a/server/space/controller/comments_test.go
+++ b/server/space/controller/comments_test.go
@@ -136,11 +136,12 @@ func TestDiscussionNotifiesPostOwnerParticipantsAndLikers(t *testing.T) {
_, err := repos.Spaces.DB.ExecContext(ctx, `UPDATE users SET encrypted_email = NULL WHERE user_id = $1`, spaces["bob"].OwnerID)
require.NoError(t, err)
}
- require.NoError(t, comments.Create(ctx, spaces[test.actor], test.postID, models.CreateCommentRequest{
+ request := models.CreateCommentRequest{
CommentID: test.id,
ReplyToID: test.replyTo,
Cipher: base64.StdEncoding.EncodeToString([]byte(test.id)),
- }))
+ }
+ require.NoError(t, comments.Create(ctx, spaces[test.actor], test.postID, request))
var expectedRecipients, notifiedRecipients []int64
expectedKinds := make(map[int64]string)
for name, kind := range test.recipients {
@@ -158,6 +159,7 @@ func TestDiscussionNotifiesPostOwnerParticipantsAndLikers(t *testing.T) {
notifiedRecipients = append(notifiedRecipients, activity.recipientIDs...)
}
require.ElementsMatch(t, expectedRecipients, notifiedRecipients)
+ require.NoError(t, comments.Create(ctx, spaces[test.actor], test.postID, request))
requireNoSpaceActivity(t, notifier)
for name, space := range spaces {
items, _, err := repos.Notifications.List(ctx, space.SpaceID, "", 50)
diff --git a/server/space/controller/notifications.go b/server/space/controller/notifications.go
index 1c092b4d5d..20c9d8c8fb 100644
--- a/server/space/controller/notifications.go
+++ b/server/space/controller/notifications.go
@@ -55,7 +55,7 @@ func spaceActivityActor(space *repo.SpaceRecord) SpaceActivityActor {
}
type SpaceActivityNotifier interface {
- OnSpaceComment(actor SpaceActivityActor, recipientUserID int64, postOwner SpaceActivityActor, postID int64, commentID, kind string)
+ OnSpaceComment(actor SpaceActivityActor, recipients []repo.CommentNotificationRecipient, postOwner SpaceActivityActor, postID int64, commentID string)
OnSpacePostCreated(actor SpaceActivityActor, postID int64)
OnSpacePostLiked(actor SpaceActivityActor, recipientUserID int64)
OnSpacePostReplied(actor SpaceActivityActor, recipientUserID int64)
@@ -73,6 +73,11 @@ type SpaceWebPushSender struct {
sendSlots chan struct{}
}
+type spaceWebPushDelivery struct {
+ activity string
+ subscriptions []repo.SpaceWebPushSubscriptionRecord
+}
+
type spaceWebPushPayload struct {
Title string `json:"title"`
Body string `json:"body"`
@@ -193,10 +198,20 @@ func (n *SpaceWebPushSender) send(
activity, action, event, destination string,
subscriptions []repo.SpaceWebPushSubscriptionRecord,
) {
- subscriptions = deduplicateSpaceWebPushSubscriptions(subscriptions)
if len(subscriptions) == 0 {
return
}
+ n.sendDeliveries(actor, action, event, destination, []spaceWebPushDelivery{{activity, subscriptions}})
+}
+
+func (n *SpaceWebPushSender) sendDeliveries(
+ actor SpaceActivityActor,
+ action, event, destination string,
+ deliveries []spaceWebPushDelivery,
+) {
+ if len(deliveries) == 0 {
+ return
+ }
limitContext, err := n.sendLimiter.Get(
context.Background(),
strconv.FormatInt(actor.UserID, 10),
@@ -217,31 +232,33 @@ func (n *SpaceWebPushSender) send(
}
var waitGroup sync.WaitGroup
- for _, subscription := range subscriptions {
- payload := spaceWebPushPayload{
- Title: "Ente Space",
- Body: fmt.Sprintf("%s %s", spaceActivityActorLabel(actor.Slug), activity),
- Action: action,
- }
- if subscription.Public {
- payload.TargetID = subscription.TargetID
- } else {
- payload.URL = destination
- }
- encoded, err := json.Marshal(payload)
- if err != nil {
- log.WithField("event", event).WithError(err).
- Error("Failed to encode Space web push payload")
- continue
- }
+ for _, delivery := range deliveries {
+ for _, subscription := range deduplicateSpaceWebPushSubscriptions(delivery.subscriptions) {
+ payload := spaceWebPushPayload{
+ Title: "Ente Space",
+ Body: fmt.Sprintf("%s %s", spaceActivityActorLabel(actor.Slug), delivery.activity),
+ Action: action,
+ }
+ if subscription.Public {
+ payload.TargetID = subscription.TargetID
+ } else {
+ payload.URL = destination
+ }
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ log.WithField("event", event).WithError(err).
+ Error("Failed to encode Space web push payload")
+ continue
+ }
- waitGroup.Add(1)
- n.sendSlots <- struct{}{}
- go func(subscription repo.SpaceWebPushSubscriptionRecord, payload []byte) {
- defer waitGroup.Done()
- defer func() { <-n.sendSlots }()
- n.sendSubscription(event, payload, subscription)
- }(subscription, encoded)
+ waitGroup.Add(1)
+ n.sendSlots <- struct{}{}
+ go func(subscription repo.SpaceWebPushSubscriptionRecord, payload []byte) {
+ defer waitGroup.Done()
+ defer func() { <-n.sendSlots }()
+ n.sendSubscription(event, payload, subscription)
+ }(subscription, encoded)
+ }
}
waitGroup.Wait()
}
@@ -417,19 +434,34 @@ func isPublicWebPushAddress(address net.IP) bool {
return true
}
-func (n *SpaceWebPushSender) OnSpaceComment(actor SpaceActivityActor, recipientUserID int64, postOwner SpaceActivityActor, postID int64, commentID, kind string) {
- post := "@" + postOwner.Slug + "'s post"
- if recipientUserID == postOwner.UserID {
- post = "your post"
- } else if actor.SpaceID == postOwner.SpaceID {
- post = "their post"
+func (n *SpaceWebPushSender) OnSpaceComment(actor SpaceActivityActor, recipients []repo.CommentNotificationRecipient, postOwner SpaceActivityActor, postID int64, commentID string) {
+ if !n.available() {
+ return
}
- activity := "commented on " + post
- switch kind {
- case "comment_reply":
- activity = "replied to your comment"
- case "comment_reaction":
- activity = "reacted to your comment"
+ var deliveries []spaceWebPushDelivery
+ for _, recipient := range recipients {
+ subscriptions, err := n.webPushRepo.ListActiveAccountSubscriptions(context.Background(), recipient.UserID)
+ if err != nil {
+ log.WithField("event", "comment").WithError(err).Error("Failed to list Space web push subscriptions")
+ continue
+ }
+ if len(subscriptions) == 0 {
+ continue
+ }
+ post := "@" + postOwner.Slug + "'s post"
+ if recipient.UserID == postOwner.UserID {
+ post = "your post"
+ } else if actor.SpaceID == postOwner.SpaceID {
+ post = "their post"
+ }
+ activity := "commented on " + post
+ switch recipient.Kind {
+ case "comment_reply":
+ activity = "replied to your comment"
+ case "comment_reaction":
+ activity = "reacted to your comment"
+ }
+ deliveries = append(deliveries, spaceWebPushDelivery{activity, subscriptions})
}
- n.sendAccountActivity(actor, activity, "View comments", "comment", fmt.Sprintf("/app/posts/%s/%d?comments=1&comment=%s", url.PathEscape(postOwner.SpaceID), postID, url.QueryEscape(commentID)), recipientUserID)
+ n.sendDeliveries(actor, "View comments", "comment", fmt.Sprintf("/app/posts/%s/%d?comments=1&comment=%s", url.PathEscape(postOwner.SpaceID), postID, url.QueryEscape(commentID)), deliveries)
}
diff --git a/server/space/controller/notifications_test.go b/server/space/controller/notifications_test.go
index 02035cc9b2..68ab109315 100644
--- a/server/space/controller/notifications_test.go
+++ b/server/space/controller/notifications_test.go
@@ -459,7 +459,7 @@ func TestFriendAndDiscussionPushNotificationDestinations(t *testing.T) {
} {
t.Run(test.name, func(t *testing.T) {
payload = spaceWebPushPayload{}
- sender.OnSpaceComment(actor, recipientID, test.postOwner, 42, "comment/with space", test.kind)
+ sender.OnSpaceComment(actor, []repo.CommentNotificationRecipient{{UserID: recipientID, Kind: test.kind}}, test.postOwner, 42, "comment/with space")
require.Equal(t, spaceWebPushPayload{
Title: "Ente Space",
Body: test.body,
@@ -500,15 +500,67 @@ func TestSpaceWebPushSendRateAppliesOncePerActivity(t *testing.T) {
require.Equal(t, len(subscriptions), len(sent))
}
-func (n *recordingSpaceActivityNotifier) OnSpaceComment(actor SpaceActivityActor, recipientUserID int64, postOwner SpaceActivityActor, postID int64, commentID, kind string) {
- n.events <- recordedSpaceActivity{
- event: kind,
- actorUserID: actor.UserID,
- actorSpaceID: actor.SpaceID,
- actorSlug: actor.Slug,
- postID: postID,
- postOwner: postOwner,
- commentID: commentID,
- recipientIDs: []int64{recipientUserID},
+func TestCommentPushQuotaAppliesOnceAcrossRecipients(t *testing.T) {
+ _, repos, ctx := setupPostsControllerTest(t)
+ var recipients []repo.CommentNotificationRecipient
+ var endpoints []string
+ for i := range 10 {
+ userID := insertSpaceControllerUser(t, repos, fmt.Sprintf("comment-push-%[email protected]", i), "public")
+ sessionHash := []byte(fmt.Sprintf("comment-push-session-%d", i))
+ require.NoError(t, repos.Sessions.CreateBrowserSession(ctx, sessionHash, userID, "wrap-key", timeutil.NDaysFromNow(1)))
+ endpoint := fmt.Sprintf("https://fcm.googleapis.com/wp/comment-%d", i)
+ _, err := repos.WebPush.UpsertAccountSubscription(ctx, sessionHash, endpoint, "p256dh", "auth")
+ require.NoError(t, err)
+ recipients = append(recipients, repo.CommentNotificationRecipient{UserID: userID, Kind: "comment"})
+ endpoints = append(endpoints, endpoint)
+ }
+ recipients[0].Kind = "comment_reply"
+ originalSend := sendSpaceWebPush
+ t.Cleanup(func() { sendSpaceWebPush = originalSend })
+ sent := make(chan string, len(recipients))
+ sendSpaceWebPush = func(_ context.Context, _ []byte, subscription *webpush.Subscription, _ *webpush.Options) (*http.Response, error) {
+ sent <- subscription.Endpoint
+ return &http.Response{StatusCode: http.StatusCreated, Body: io.NopCloser(strings.NewReader(""))}, nil
+ }
+ actor := SpaceActivityActor{UserID: 100, SpaceID: "actor", Slug: "alice"}
+ owner := SpaceActivityActor{UserID: recipients[1].UserID, SpaceID: "owner", Slug: "bob"}
+ for _, priorActivities := range []int{0, 49} {
+ t.Run(fmt.Sprintf("after-%d-activities", priorActivities), func(t *testing.T) {
+ sender := NewSpaceWebPushSender(repos.WebPush, newSpaceWebPushTestConfig(t))
+ sender.OnSpaceComment(actor, []repo.CommentNotificationRecipient{{UserID: actor.UserID, Kind: "comment"}}, owner, 42, "no-subscribers")
+ for range priorActivities {
+ sender.OnSpaceFriendAdded(actor, recipients[0].UserID)
+ require.Len(t, sent, 1)
+ <-sent
+ }
+ for i := range 50 - priorActivities {
+ sender.OnSpaceComment(actor, recipients, owner, 42, fmt.Sprintf("comment-%d", i))
+ require.Len(t, sent, len(recipients))
+ var delivered []string
+ for range recipients {
+ delivered = append(delivered, <-sent)
+ }
+ require.ElementsMatch(t, endpoints, delivered)
+ }
+ sender.OnSpaceComment(actor, recipients, owner, 42, "over-limit")
+ require.Empty(t, sent)
+ sender.OnSpaceFriendAdded(actor, recipients[0].UserID)
+ require.Empty(t, sent)
+ })
+ }
+}
+
+func (n *recordingSpaceActivityNotifier) OnSpaceComment(actor SpaceActivityActor, recipients []repo.CommentNotificationRecipient, postOwner SpaceActivityActor, postID int64, commentID string) {
+ for _, recipient := range recipients {
+ n.events <- recordedSpaceActivity{
+ event: recipient.Kind,
+ actorUserID: actor.UserID,
+ actorSpaceID: actor.SpaceID,
+ actorSlug: actor.Slug,
+ postID: postID,
+ postOwner: postOwner,
+ commentID: commentID,
+ recipientIDs: []int64{recipient.UserID},
+ }
}
}
diff --git a/server/space/controller/test_helpers_test.go b/server/space/controller/test_helpers_test.go
index 71cb851c79..d68ba9ff33 100644
--- a/server/space/controller/test_helpers_test.go
+++ b/server/space/controller/test_helpers_test.go
@@ -28,7 +28,7 @@ func setupPostsControllerTest(t *testing.T) (*PostsController, *spacerepo.Module
type noopSpaceActivityNotifier struct{}
-func (noopSpaceActivityNotifier) OnSpaceComment(SpaceActivityActor, int64, SpaceActivityActor, int64, string, string) {
+func (noopSpaceActivityNotifier) OnSpaceComment(SpaceActivityActor, []spacerepo.CommentNotificationRecipient, SpaceActivityActor, int64, string) {
}
func (noopSpaceActivityNotifier) OnSpacePostCreated(SpaceActivityActor, int64) {}
diff --git a/server/space/repo/comments.go b/server/space/repo/comments.go
index 76dd5b5749..48e3b8c223 100644
--- a/server/space/repo/comments.go
+++ b/server/space/repo/comments.go
@@ -52,6 +52,34 @@ const commentVisibleSQL = `NOT EXISTS (
WHERE NOT a.has_content OR account.encrypted_email IS NULL
)`
+const commentRecipientsSQL = `WITH RECURSIVE hidden_comments AS (
+ SELECT c.comment_id FROM space_comments c
+ LEFT JOIN spaces author ON author.space_id = c.author_space_id
+ LEFT JOIN users account ON account.user_id = author.owner_id
+ WHERE c.post_id = $2 AND (c.cipher IS NULL OR account.encrypted_email IS NULL)
+ UNION
+ SELECT child.comment_id FROM hidden_comments parent
+ CROSS JOIN LATERAL (
+ SELECT c.comment_id FROM space_comments c
+ WHERE c.reply_to_id = parent.comment_id AND c.post_id = $2
+ OFFSET 0
+ ) child
+)
+SELECT ARRAY(
+ SELECT participant.space_id FROM (
+ SELECT $1::text AS space_id
+ UNION
+ SELECT c.author_space_id FROM space_comments c WHERE c.post_id = $2 AND NOT EXISTS (
+ SELECT 1 FROM hidden_comments hidden WHERE hidden.comment_id = c.comment_id
+ )
+ UNION
+ SELECT l.actor_space_id FROM space_post_likes l WHERE l.post_id = $2
+ ) participant
+ JOIN spaces s ON s.space_id = participant.space_id
+ JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
+ WHERE participant.space_id <> $3
+)`
+
func discussionPostTx(ctx context.Context, tx *sql.Tx, viewer string, postID int64, forUpdate bool) (string, error) {
locking := "FOR SHARE OF s, p"
if forUpdate {
@@ -183,48 +211,54 @@ func (r *CommentsRepository) List(ctx context.Context, viewer string, postID int
}
func (r *CommentsRepository) Create(ctx context.Context, viewer string, postID int64, req models.CreateCommentRequest, cipher []byte) error {
+ _, err := r.CreateWithCreated(ctx, viewer, postID, req, cipher)
+ return err
+}
+
+func (r *CommentsRepository) CreateWithCreated(ctx context.Context, viewer string, postID int64, req models.CreateCommentRequest, cipher []byte) (bool, error) {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
- return err
+ return false, err
}
defer tx.Rollback()
owner, err := discussionPostTx(ctx, tx, viewer, postID, true)
if err != nil {
- return err
+ return false, err
+ }
+ var matches bool
+ err = tx.QueryRowContext(ctx, `SELECT post_id = $2 AND COALESCE(author_space_id, '') = $3 AND COALESCE(reply_to_id, '') = $4
+ FROM space_comments WHERE comment_id = $1`, req.CommentID, postID, viewer, req.ReplyToID).Scan(&matches)
+ if err == nil {
+ if !matches {
+ return false, ente.NewConflictError("comment ID already used")
+ }
+ return false, nil
+ }
+ if err != sql.ErrNoRows {
+ return false, err
}
var parent, replyRecipient string
if req.ReplyToID != "" {
if err := tx.QueryRowContext(ctx, `SELECT COALESCE(c.parent_id, c.comment_id), c.author_space_id FROM space_comments c
WHERE c.comment_id = $1 AND c.post_id = $2 AND `+commentVisibleSQL, req.ReplyToID, postID).Scan(&parent, &replyRecipient); err != nil {
- return err
+ return false, err
}
}
res, err := tx.ExecContext(ctx, `INSERT INTO space_comments (comment_id, post_id, author_space_id, parent_id, reply_to_id, cipher)
VALUES ($1, $2, $3, NULLIF($4, ''), NULLIF($5, ''), $6) ON CONFLICT (comment_id) DO NOTHING`, req.CommentID, postID, viewer, parent, req.ReplyToID, cipher)
if err != nil {
- return err
+ return false, err
}
count, err := res.RowsAffected()
if err != nil {
- return err
+ return false, err
}
if count == 0 {
- return ente.NewConflictError("discussion changed; refresh and retry")
+ return false, ente.NewConflictError("comment ID already used")
}
var recipients pq.StringArray
- if err := tx.QueryRowContext(ctx, `SELECT ARRAY(
- SELECT participant.space_id FROM (
- SELECT $1::text AS space_id
- UNION
- SELECT c.author_space_id FROM space_comments c WHERE c.post_id = $2 AND `+commentVisibleSQL+`
- UNION
- SELECT l.actor_space_id FROM space_post_likes l WHERE l.post_id = $2
- ) participant
- JOIN spaces s ON s.space_id = participant.space_id
- JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
- WHERE participant.space_id <> $3
- )`, owner, postID, viewer).Scan(&recipients); err != nil {
- return err
+ if err := tx.QueryRowContext(ctx, commentRecipientsSQL, owner, postID, viewer).Scan(&recipients); err != nil {
+ return false, err
}
for _, recipient := range recipients {
kind := "comment"
@@ -232,10 +266,13 @@ func (r *CommentsRepository) Create(ctx context.Context, viewer string, postID i
kind = "comment_reply"
}
if _, err := commentNotificationTx(ctx, tx, owner, viewer, recipient, req.CommentID, kind); err != nil {
- return err
+ return false, err
}
}
- return tx.Commit()
+ if err := tx.Commit(); err != nil {
+ return false, err
+ }
+ return true, nil
}
func commentNotificationTx(ctx context.Context, tx *sql.Tx, owner, actor, recipient, commentID, kind string) (bool, error) {
diff --git a/server/space/repo/comments_test.go b/server/space/repo/comments_test.go
index 63fb205b88..79931ddc6c 100644
--- a/server/space/repo/comments_test.go
+++ b/server/space/repo/comments_test.go
@@ -4,14 +4,115 @@ import (
"context"
"database/sql"
"encoding/json"
+ "net/http"
"testing"
"time"
"github.com/ente/museum/ente"
"github.com/ente/museum/space/models"
+ "github.com/lib/pq"
"github.com/stretchr/testify/require"
)
+func TestCommentCreationRetriesPreserveTheOriginal(t *testing.T) {
+ module := newSpaceTestModule(t)
+ ctx := t.Context()
+ owner, friend := notificationTestSpaces(t, module)
+ postID, err := testCreatePost(ctx, module, owner.OwnerID, owner.SpaceID, "post-key", nil, 1, nil)
+ require.NoError(t, err)
+ otherPostID, err := testCreatePost(ctx, module, owner.OwnerID, owner.SpaceID, "other-key", nil, 1, nil)
+ require.NoError(t, err)
+ require.NoError(t, module.Comments.Create(ctx, owner.SpaceID, postID, models.CreateCommentRequest{CommentID: "parent"}, []byte("parent")))
+ request := models.CreateCommentRequest{CommentID: "retry", ReplyToID: "parent"}
+ created, err := module.Comments.CreateWithCreated(ctx, friend.SpaceID, postID, request, []byte("original"))
+ require.NoError(t, err)
+ require.True(t, created)
+ created, err = module.Comments.CreateWithCreated(ctx, friend.SpaceID, postID, request, []byte("reencrypted"))
+ require.NoError(t, err)
+ require.False(t, created)
+ var cipher []byte
+ require.NoError(t, module.Comments.DB.QueryRowContext(ctx, `SELECT cipher FROM space_comments WHERE comment_id = 'retry'`).Scan(&cipher))
+ require.Equal(t, []byte("original"), cipher)
+ require.EqualValues(t, 1, countSpaceRows(t, module, `SELECT count(*) FROM space_notifications WHERE comment_id = 'retry'`))
+ for _, test := range []struct {
+ name, actor, replyTo string
+ postID int64
+ }{
+ {"different-author", owner.SpaceID, "parent", postID},
+ {"different-post", friend.SpaceID, "parent", otherPostID},
+ {"different-target", friend.SpaceID, "", postID},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ created, err := module.Comments.CreateWithCreated(ctx, test.actor, test.postID, models.CreateCommentRequest{CommentID: "retry", ReplyToID: test.replyTo}, []byte("other"))
+ require.False(t, created)
+ var apiError *ente.ApiError
+ require.ErrorAs(t, err, &apiError)
+ require.Equal(t, http.StatusConflict, apiError.HttpStatusCode)
+ })
+ }
+ require.NoError(t, module.Comments.Delete(ctx, owner.SpaceID, postID, "parent"))
+ created, err = module.Comments.CreateWithCreated(ctx, friend.SpaceID, postID, request, []byte("retry-after-deletion"))
+ require.NoError(t, err)
+ require.False(t, created)
+ require.NoError(t, module.Comments.DB.QueryRowContext(ctx, `SELECT cipher FROM space_comments WHERE comment_id = 'retry'`).Scan(&cipher))
+ require.Empty(t, cipher)
+ require.Zero(t, countSpaceRows(t, module, `SELECT count(*) FROM space_notifications WHERE comment_id = 'retry'`))
+}
+
+func TestCommentRecipientWorkScalesWithReplyChainLength(t *testing.T) {
+ for _, hidden := range []string{"visible", "deleted-comment", "deleted-author"} {
+ t.Run(hidden, func(t *testing.T) {
+ module := newSpaceTestModule(t)
+ ctx := t.Context()
+ owner, friend := notificationTestSpaces(t, module)
+ var previousBlocks int64
+ for _, length := range []int{128, 512} {
+ postID, err := testCreatePost(ctx, module, owner.OwnerID, owner.SpaceID, "post-key", nil, 1, nil)
+ require.NoError(t, err)
+ _, err = module.Posts.DB.ExecContext(ctx, `INSERT INTO space_comments
+ (comment_id, post_id, author_space_id, parent_id, reply_to_id, cipher)
+ SELECT $1::text || ':' || i, $1::bigint, CASE WHEN i = 1 THEN $2 ELSE $3 END,
+ CASE WHEN i > 1 THEN $1::text || ':1' END,
+ CASE WHEN i > 1 THEN $1::text || ':' || (i - 1) END,
+ CASE WHEN i = 1 AND $5 = 'deleted-comment' THEN NULL ELSE '\x01'::bytea END
+ FROM generate_series(1, $4::int) i`, postID, owner.SpaceID, friend.SpaceID, length, hidden)
+ require.NoError(t, err)
+ if hidden == "deleted-author" {
+ _, err = module.Posts.DB.ExecContext(ctx, `UPDATE users SET encrypted_email = NULL WHERE user_id = $1`, owner.OwnerID)
+ require.NoError(t, err)
+ }
+ _, err = module.Posts.DB.ExecContext(ctx, `ANALYZE space_comments`)
+ require.NoError(t, err)
+ var recipients pq.StringArray
+ require.NoError(t, module.Posts.DB.QueryRowContext(ctx, commentRecipientsSQL, owner.SpaceID, postID, owner.SpaceID).Scan(&recipients))
+ if hidden == "visible" {
+ require.Equal(t, pq.StringArray{friend.SpaceID}, recipients)
+ } else {
+ require.Empty(t, recipients)
+ }
+ var planJSON []byte
+ require.NoError(t, module.Posts.DB.QueryRowContext(ctx, `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) `+commentRecipientsSQL, owner.SpaceID, postID, owner.SpaceID).Scan(&planJSON))
+ var plans []struct {
+ Plan struct {
+ Hits int64 `json:"Shared Hit Blocks"`
+ Reads int64 `json:"Shared Read Blocks"`
+ }
+ }
+ require.NoError(t, json.Unmarshal(planJSON, &plans))
+ require.Len(t, plans, 1)
+ blocks := plans[0].Plan.Hits + plans[0].Plan.Reads
+ t.Logf("%d comments: %d buffer accesses", length, blocks)
+ if previousBlocks > 0 {
+ require.Less(t, blocks, previousBlocks*8)
+ }
+ previousBlocks = blocks
+ _, err = module.Posts.DB.ExecContext(ctx, `UPDATE users SET encrypted_email = '\x00'::bytea WHERE user_id = $1`, owner.OwnerID)
+ require.NoError(t, err)
+ }
+ })
+ }
+}
+
func TestPostCommentCountWorkScalesWithReplyChainLength(t *testing.T) {
for _, hidden := range []bool{false, true} {
name := "visible"
diff --git a/web/apps/space/src/components/PostComments.tsx b/web/apps/space/src/components/PostComments.tsx
index a8a50dfcdc..09afde0b86 100644
--- a/web/apps/space/src/components/PostComments.tsx
+++ b/web/apps/space/src/components/PostComments.tsx
@@ -1293,20 +1293,35 @@ export const PostComments: React.FC<{
sendDisabled={loading}
placeholder={replyTarget ? "Reply…" : "Add a comment…"}
onSend={async (text) => {
- setDraft((value) => ({ ...value, sending: true }));
+ const replyToId =
+ replyTarget?.status == "selected"
+ ? replyTarget.commentId
+ : undefined;
+ const submission =
+ draft.pendingSubmission?.text == text &&
+ draft.pendingSubmission.replyToId == replyToId
+ ? draft.pendingSubmission
+ : {
+ commentId: crypto.randomUUID(),
+ text,
+ replyToId,
+ };
+ setDraft((value) => ({
+ ...value,
+ pendingSubmission: submission,
+ sending: true,
+ }));
try {
- const commentId = crypto.randomUUID();
await createCurrentComment(
viewer,
owner,
postId,
- commentId,
- replyTarget?.status == "selected"
- ? replyTarget.commentId
- : undefined,
- text,
+ submission.commentId,
+ submission.replyToId,
+ submission.text,
);
- submittedCommentId.current = commentId;
+ submittedCommentId.current =
+ submission.commentId;
setDraft({ text: "", sending: true });
} finally {
setDraft((value) => ({
diff --git a/web/apps/space/src/utils/comments.ts b/web/apps/space/src/utils/comments.ts
index a3bad2ad2f..ddb9080ee2 100644
--- a/web/apps/space/src/utils/comments.ts
+++ b/web/apps/space/src/utils/comments.ts
@@ -32,6 +32,7 @@ export interface CommentDraft {
text: string;
replyTarget?: CommentReplyTarget;
sending?: boolean;
+ pendingSubmission?: { commentId: string; text: string; replyToId?: string };
}
export const validateCommentReplyTarget = (
diff --git a/web/apps/space/tests/comment-mutations.test.tsx b/web/apps/space/tests/comment-mutations.test.tsx
index 4bcdd3fded..1d8225da83 100644
--- a/web/apps/space/tests/comment-mutations.test.tsx
+++ b/web/apps/space/tests/comment-mutations.test.tsx
@@ -2,6 +2,7 @@ import React, { type EffectCallback, type SetStateAction } from "react";
import { beforeEach, expect, test, vi } from "vitest";
import { PostComments } from "../src/components/PostComments";
import type { SpaceComment } from "../src/services/space";
+import type { CommentDraft } from "../src/utils/comments";
const mocks = vi.hoisted(() => ({
hooks: [] as unknown[],
@@ -105,6 +106,8 @@ const comment: SpaceComment = {
type Element = React.ReactElement<Record<string, unknown>>;
+let draft: CommentDraft;
+
const elements = (node: React.ReactNode): Element[] => {
if (Array.isArray(node)) return node.flatMap(elements);
if (!React.isValidElement<Record<string, unknown>>(node)) return [];
@@ -128,8 +131,10 @@ const render = () => {
viewer: "viewer",
owner: "owner",
postId: 42,
- draft: { text: "New comment" },
- setDraft: vi.fn(),
+ draft,
+ setDraft: (update) => {
+ draft = typeof update == "function" ? update(draft) : update;
+ },
onClose: vi.fn(),
}) as React.ReactNode,
);
@@ -156,12 +161,59 @@ beforeEach(async () => {
vi.resetAllMocks();
mocks.hooks = [];
mocks.effects = [];
+ draft = { text: "New comment" };
mocks.load.mockResolvedValue([comment]);
render();
mocks.effects[0]!();
await vi.waitFor(() => expect(composer().props.sendDisabled).toBe(false));
});
+test("a lost creation response keeps the submission ID through reopening and retry", async () => {
+ mocks.create.mockRejectedValueOnce(new Error("Response lost"));
+ await expect(
+ (composer().props.onSend as (text: string) => Promise<void>)(
+ draft.text,
+ ),
+ ).rejects.toThrow("Response lost");
+ const submission = draft.pendingSubmission!;
+ expect(submission.commentId).toEqual(expect.any(String));
+ expect(draft.text).toBe("New comment");
+ expect(draft.sending).toBe(false);
+ mocks.hooks = [];
+ mocks.create.mockResolvedValueOnce(undefined);
+ await (composer().props.onSend as (text: string) => Promise<void>)(
+ draft.text,
+ );
+ expect(mocks.create.mock.calls[1]).toEqual(mocks.create.mock.calls[0]);
+ expect(draft.text).toBe("");
+ expect(draft.pendingSubmission).toBeUndefined();
+});
+
+test.each(["text", "reply"])(
+ "changing the %s after a failed send creates a new submission",
+ async (change) => {
+ mocks.create.mockRejectedValueOnce(new Error("Request failed"));
+ await expect(
+ (composer().props.onSend as (text: string) => Promise<void>)(
+ draft.text,
+ ),
+ ).rejects.toThrow("Request failed");
+ const firstID = draft.pendingSubmission!.commentId;
+ if (change == "text") draft.text = "Changed comment";
+ else draft.replyTarget = { status: "selected", commentId: "comment" };
+ await (composer().props.onSend as (text: string) => Promise<void>)(
+ draft.text,
+ );
+ expect(mocks.create.mock.calls[1]![3]).not.toBe(firstID);
+ expect(mocks.create.mock.calls[1]![4]).toBe(
+ change == "reply" ? "comment" : undefined,
+ );
+ expect(mocks.create.mock.calls[1]![5]).toBe(
+ change == "text" ? "Changed comment" : "New comment",
+ );
+ },
+);
+
test.each(["react", "delete"] as const)(
"a failed %s keeps the composer usable when the discussion refresh succeeds",
async (kind) => {