Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Fix comment mutation errors and deep reply count performance

Anand Baburajanb73bfc59e294
diff --git a/server/space/repo/comments_test.go b/server/space/repo/comments_test.go
index ea80101715..63fb205b88 100644
--- a/server/space/repo/comments_test.go
+++ b/server/space/repo/comments_test.go
@@ -3,6 +3,7 @@ package repo
import (
"context"
"database/sql"
+ "encoding/json"
"testing"
"time"
@@ -11,6 +12,67 @@ import (
"github.com/stretchr/testify/require"
)
+func TestPostCommentCountWorkScalesWithReplyChainLength(t *testing.T) {
+ for _, hidden := range []bool{false, true} {
+ name := "visible"
+ if hidden {
+ name = "hidden-author"
+ }
+ t.Run(name, func(t *testing.T) {
+ module := newSpaceTestModule(t)
+ ctx := t.Context()
+ owner, friend := notificationTestSpaces(t, module)
+ if hidden {
+ _, err := module.Posts.DB.ExecContext(ctx, `UPDATE users SET encrypted_email = NULL WHERE user_id = $1`, friend.OwnerID)
+ require.NoError(t, err)
+ }
+ 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 $4 ELSE $2 END,
+ CASE WHEN i > 1 THEN $1::text || ':1' END,
+ CASE WHEN i > 1 THEN $1::text || ':' || (i - 1) END,
+ '\x01'::bytea
+ FROM generate_series(1, $3::int) i`, postID, owner.SpaceID, length, friend.SpaceID)
+ require.NoError(t, err)
+ _, err = module.Posts.DB.ExecContext(ctx, `ANALYZE space_comments`)
+ require.NoError(t, err)
+ post, err := module.Posts.GetPost(ctx, postID, owner.SpaceID)
+ require.NoError(t, err)
+ if hidden {
+ require.Zero(t, post.CommentCount)
+ } else {
+ require.EqualValues(t, length, post.CommentCount)
+ }
+ var planJSON []byte
+ err = module.Posts.DB.QueryRowContext(ctx, `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) `+
+ postRecordSelectSQL("FALSE", "$2")+`
+ FROM space_posts p JOIN spaces w ON w.space_id = p.space_id
+ `+spaceActorAvatarJoin("w", "w_avatar")+`
+ WHERE p.post_id = $1`, postID, owner.SpaceID).Scan(&planJSON)
+ require.NoError(t, err)
+ 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
+ }
+ })
+ }
+}
+
func TestDiscussionParentDeletionRemovesWholeThread(t *testing.T) {
for _, deleteAsOwner := range []bool{false, true} {
name := "author"
diff --git a/server/space/repo/posts.go b/server/space/repo/posts.go
index 72e3ecc4cd..559a6a6eed 100644
--- a/server/space/repo/posts.go
+++ b/server/space/repo/posts.go
@@ -80,8 +80,23 @@ func postRecordSelectSQL(viewerLikedExpr string, viewerSpaceParam string) string
p.encrypted_post_key, p.caption_cipher,
p.key_version, p.created_at,
` + viewerLikedExpr + ` AS viewer_liked,
- (SELECT COUNT(*) FROM space_comments c
- WHERE c.post_id = p.post_id AND ` + commentVisibleSQL + `) AS comment_count,
+ (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 = p.post_id 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 = p.post_id
+ OFFSET 0
+ ) child
+ )
+ SELECT COUNT(*) FROM space_comments c
+ WHERE c.post_id = p.post_id AND NOT EXISTS (
+ SELECT 1 FROM hidden_comments hidden WHERE hidden.comment_id = c.comment_id
+ )) AS comment_count,
CASE WHEN p.space_id = ` + viewerSpaceParam + ` THEN (
SELECT COUNT(*) FROM space_post_likes l
JOIN spaces actor ON actor.space_id = l.actor_space_id
diff --git a/web/apps/space/src/components/PostComments.tsx b/web/apps/space/src/components/PostComments.tsx
index 082087c953..33bf91df12 100644
--- a/web/apps/space/src/components/PostComments.tsx
+++ b/web/apps/space/src/components/PostComments.tsx
@@ -594,6 +594,7 @@ export const PostComments: React.FC<{
const threads = commentThreads(comments);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState<string>();
+ const [mutationError, setMutationError] = React.useState<string>();
const [open, setOpen] = React.useState(true);
const [entered, setEntered] = React.useState(false);
const [highlightedCommentId, setHighlightedCommentId] =
@@ -670,6 +671,7 @@ export const PostComments: React.FC<{
if (current != generation.current) return;
setComments(items);
setError(undefined);
+ setMutationError(undefined);
setDraft((value) => ({
...value,
replyTarget: validateCommentReplyTarget(
@@ -853,12 +855,13 @@ export const PostComments: React.FC<{
}, [action, comments, entered, loading, open, viewer]);
const mutate = async (action: () => Promise<void>) => {
setMutating(true);
+ setMutationError(undefined);
try {
await action();
await refresh();
} catch {
await refresh();
- setError("Couldn't save your change. Refresh and try again.");
+ setMutationError("Couldn't save your change. Please try again.");
} finally {
setMutating(false);
}
@@ -1203,7 +1206,7 @@ export const PostComments: React.FC<{
)}
</Box>
))}
- {error && (
+ {(error || mutationError) && (
<Box
role="alert"
sx={{
@@ -1213,7 +1216,7 @@ export const PostComments: React.FC<{
fontSize: 13,
}}
>
- {error}{" "}
+ {error || mutationError}{" "}
<Box
component="button"
type="button"
diff --git a/web/apps/space/tests/comment-mutations.test.tsx b/web/apps/space/tests/comment-mutations.test.tsx
new file mode 100644
index 0000000000..4bcdd3fded
--- /dev/null
+++ b/web/apps/space/tests/comment-mutations.test.tsx
@@ -0,0 +1,201 @@
+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";
+
+const mocks = vi.hoisted(() => ({
+ hooks: [] as unknown[],
+ index: 0,
+ effects: [] as EffectCallback[],
+ load: vi.fn(),
+ react: vi.fn(),
+ delete: vi.fn(),
+ create: vi.fn(),
+}));
+
+vi.mock("react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("react")>();
+ const useState = <T,>(initial?: T | (() => T)) => {
+ const index = mocks.index++;
+ if (!(index in mocks.hooks))
+ mocks.hooks[index] =
+ typeof initial == "function" ? (initial as () => T)() : initial;
+ return [
+ mocks.hooks[index] as T,
+ (value: SetStateAction<T>) => {
+ mocks.hooks[index] =
+ typeof value == "function"
+ ? (value as (previous: T) => T)(mocks.hooks[index] as T)
+ : value;
+ },
+ ] as const;
+ };
+ return {
+ ...actual,
+ default: {
+ ...actual,
+ useState,
+ useRef: <T,>(value: T) => useState({ current: value })[0],
+ useCallback: <T,>(callback: T) => callback,
+ useMemo: <T,>(callback: () => T) => callback(),
+ useEffect: (effect: EffectCallback) => mocks.effects.push(effect),
+ useLayoutEffect: vi.fn(),
+ },
+ };
+});
+vi.mock("@mui/material", () => ({
+ Box: "box",
+ CircularProgress: "progress",
+ ClickAwayListener: "click-away",
+ Dialog: "dialog",
+ Grow: "grow",
+ Popper: "popper",
+ Slide: "slide",
+ useMediaQuery: () => false,
+}));
+vi.mock("components/AvatarImage", () => ({ SpaceAvatarImage: "avatar" }));
+vi.mock("components/BottomSheetTransition", () => ({
+ SpaceBottomSheetTransition: "transition",
+}));
+vi.mock("components/CommentComposer", () => ({
+ SpaceCommentComposer: "composer",
+}));
+vi.mock("components/MessageActionMenu", () => ({
+ CopyIcon: "copy",
+ DeleteIcon: "delete",
+ ReplyIcon: "reply",
+ MessageActionMenuItem: "menu-item",
+ MessageActionMenuList: "menu",
+}));
+vi.mock("components/MessageReactionPicker", () => ({
+ MessageQuickReactions: "quick-reactions",
+ MessageReactionPicker: "picker",
+}));
+vi.mock("components/ReplyComposerPreview", () => ({
+ ReplyComposerPreview: "preview",
+}));
+vi.mock("data/emojis", () => ({ emojiName: () => "emoji" }));
+vi.mock("hooks/use-browser-back-close", () => ({
+ useBrowserBackClose: vi.fn(),
+}));
+vi.mock("hooks/use-pwa-install-prompt", () => ({ isSpaceIOS: () => false }));
+vi.mock("styles/colors", () => import("../src/styles/colors"));
+vi.mock("utils/route-transitions", () => ({ useSpaceRouter: vi.fn() }));
+vi.mock("services/space", () => ({
+ loadCurrentComments: mocks.load,
+ setCurrentCommentReaction: mocks.react,
+ deleteCurrentComment: mocks.delete,
+ createCurrentComment: mocks.create,
+ loadCurrentFriendAvatarURL: vi.fn(),
+ markCurrentNotificationItemsRead: vi.fn(),
+ removeCurrentCommentReaction: vi.fn(),
+}));
+
+const comment: SpaceComment = {
+ commentId: "comment",
+ parentId: "",
+ replyToId: "",
+ text: "Hello",
+ createdAt: "2026-10-21T00:00:00Z",
+ deleted: false,
+ canDelete: true,
+ reactions: [],
+ unreadNotificationIds: [],
+};
+
+type Element = React.ReactElement<Record<string, unknown>>;
+
+const elements = (node: React.ReactNode): Element[] => {
+ if (Array.isArray(node)) return node.flatMap(elements);
+ if (!React.isValidElement<Record<string, unknown>>(node)) return [];
+ const children = node.props.children;
+ return [
+ node,
+ ...elements(
+ typeof children == "function"
+ ? (children as (props: object) => React.ReactNode)({
+ placement: "bottom-start",
+ })
+ : (children as React.ReactNode),
+ ),
+ ];
+};
+
+const render = () => {
+ mocks.index = 0;
+ return elements(
+ PostComments({
+ viewer: "viewer",
+ owner: "owner",
+ postId: 42,
+ draft: { text: "New comment" },
+ setDraft: vi.fn(),
+ onClose: vi.fn(),
+ }) as React.ReactNode,
+ );
+};
+
+const composer = () => render().find((node) => node.type == "composer")!;
+const alert = () => render().find((node) => node.props.role == "alert");
+
+const mutate = (kind: "react" | "delete") => {
+ const row = render().find((node) => node.props.comment === comment)!;
+ if (kind == "react") {
+ (row.props.onReact as (emoji: string) => void)("❀️");
+ } else {
+ (row.props.onOpenActions as (anchor: object, source: string) => void)(
+ {},
+ "contextmenu",
+ );
+ const button = render().find((node) => node.props.label == "Delete")!;
+ (button.props.onClick as () => void)();
+ }
+};
+
+beforeEach(async () => {
+ vi.resetAllMocks();
+ mocks.hooks = [];
+ mocks.effects = [];
+ mocks.load.mockResolvedValue([comment]);
+ render();
+ mocks.effects[0]!();
+ await vi.waitFor(() => expect(composer().props.sendDisabled).toBe(false));
+});
+
+test.each(["react", "delete"] as const)(
+ "a failed %s keeps the composer usable when the discussion refresh succeeds",
+ async (kind) => {
+ mocks[kind].mockRejectedValueOnce(new Error("Request failed"));
+ mutate(kind);
+ await vi.waitFor(() => expect(alert()).toBeDefined());
+ expect(mocks.load).toHaveBeenCalledTimes(2);
+ expect(composer().props.disabled).toBeFalsy();
+ await (composer().props.onSend as (text: string) => Promise<void>)(
+ "Still able to comment",
+ );
+ expect(mocks.create).toHaveBeenCalledWith(
+ "viewer",
+ "owner",
+ 42,
+ expect.any(String),
+ undefined,
+ "Still able to comment",
+ );
+ mocks[kind].mockResolvedValueOnce(undefined);
+ mutate(kind);
+ await vi.waitFor(() => expect(mocks.load).toHaveBeenCalledTimes(3));
+ expect(alert()).toBeUndefined();
+ expect(composer().props.disabled).toBeFalsy();
+ },
+);
+
+test("a failed refresh still disables the unavailable discussion after a mutation fails", async () => {
+ mocks.react.mockRejectedValueOnce(new Error("Request failed"));
+ mocks.load.mockRejectedValueOnce(new Error("Access denied"));
+ mutate("react");
+ await vi.waitFor(() => expect(alert()).toBeDefined());
+ expect(composer().props.disabled).toBe(true);
+ expect(alert()!.props.children).toContain(
+ "Discussion unavailable. Access may have changed or the post may have been deleted.",
+ );
+});