diff --git a/app/editor/components/LinkEditor.tsx b/app/editor/components/LinkEditor.tsx index 8306052d6a..dc63b272a0 100644 --- a/app/editor/components/LinkEditor.tsx +++ b/app/editor/components/LinkEditor.tsx @@ -19,9 +19,9 @@ import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import Flex from "~/components/Flex"; import { ResizingHeightContainer } from "~/components/ResizingHeightContainer"; import Scrollable from "~/components/Scrollable"; +import useDebouncedValue from "~/hooks/useDebouncedValue"; import useRequest from "~/hooks/useRequest"; import useStores from "~/hooks/useStores"; -import { client } from "~/utils/ApiClient"; import Input from "./Input"; import SuggestionsMenuItem from "./SuggestionsMenuItem"; import ToolbarButton from "./ToolbarButton"; @@ -29,6 +29,9 @@ import Tooltip from "./Tooltip"; import useOnClickOutside from "~/hooks/useOnClickOutside"; import { useEditor } from "./EditorContext"; +/** The time in milliseconds the query must stay the same before it is sent. */ +const RequestDelay = 100; + type Props = { mark?: Mark; view: EditorView; @@ -67,18 +70,30 @@ const LinkEditor: React.FC = ({ ? documents.findByQuery(trimmedQuery, { maxResults: 25 }) : []; + // Results from the store show at once, the server is only asked for more + // when the user stops typing. + const requestQuery = useDebouncedValue(trimmedQuery, RequestDelay); + const { request } = useRequest( - React.useCallback(async () => { - const res = await client.post("/suggestions.mention", { query }); - res.data.documents.map(documents.add); - }, [documents, query]) + React.useCallback( + () => + documents.searchTitles({ + query: requestQuery, + limit: 25, + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }), + [documents, requestQuery] + ) ); useEffect(() => { - if (trimmedQuery) { + if (requestQuery) { void request(); } - }, [trimmedQuery, request]); + }, [requestQuery, request]); // Focus imperatively rather than with the autoFocus attribute, which only // applies on mount – the editor can already be open when focus is requested. diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx index 5f45ceafca..8fe1ced1ad 100644 --- a/app/editor/components/MentionMenu.tsx +++ b/app/editor/components/MentionMenu.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; import { v4 as uuidv4 } from "uuid"; import { runInAction } from "mobx"; -import { useState, useCallback, useEffect } from "react"; +import { useState, useCallback, useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { MentionType } from "@shared/types"; @@ -25,6 +25,7 @@ import { groupMentionItem, userMentionItem, } from "~/editor/menus/mention"; +import useDebouncedValue from "~/hooks/useDebouncedValue"; import useRequest from "~/hooks/useRequest"; import useStores from "~/hooks/useStores"; import useUserLocale from "~/hooks/useUserLocale"; @@ -36,6 +37,9 @@ import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu"; import SuggestionsMenu from "./SuggestionsMenu"; import SuggestionsMenuItem from "./SuggestionsMenuItem"; +/** The time in milliseconds the search must stay the same before it is sent. */ +const RequestDelay = 100; + type Props = Omit< SuggestionsMenuProps, "renderMenuItem" | "items" | "embeds" @@ -122,13 +126,24 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { ]; } + // Results from the store show at once, the server is only asked for more + // when the user stops typing. + const requestSearch = useDebouncedValue(search, RequestDelay); + const latestRequestId = useRef(0); + const { loading, request } = useRequest( useCallback(async () => { + const requestId = ++latestRequestId.current; const res = await client.post("/suggestions.mention", { - query: search, - limit: maxResultsInSection, + query: requestSearch, + limit: requestSearch ? 25 : 5, }); + // A newer request was sent while this one was in progress. + if (requestId !== latestRequestId.current) { + return; + } + runInAction(() => { res.data.documents.map(documents.add); res.data.users.map(users.add); @@ -143,7 +158,7 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { ...Object.entries(res.data.familiarity ?? {}), ]) ); - }, [search, documents, users, collections, groups, maxResultsInSection]) + }, [requestSearch, documents, users, collections, groups]) ); // Suggestions that the current user is familiar with, for example a member of diff --git a/app/hooks/useDebouncedValue.ts b/app/hooks/useDebouncedValue.ts new file mode 100644 index 0000000000..f1892d3b28 --- /dev/null +++ b/app/hooks/useDebouncedValue.ts @@ -0,0 +1,20 @@ +import { useEffect, useState } from "react"; + +/** + * Returns a value that only changes after the given value has stayed the same + * for the wait time. The first value is returned at once. + * + * @param value the value to debounce. + * @param wait the time in milliseconds the value must stay the same. + * @returns the last value that stayed the same for the wait time. + */ +export default function useDebouncedValue(value: T, wait: number): T { + const [debounced, setDebounced] = useState(value); + + useEffect(() => { + const timeout = setTimeout(() => setDebounced(value), wait); + return () => clearTimeout(timeout); + }, [value, wait]); + + return debounced; +} diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index c9d16e58f5..d1a630052d 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -1443,7 +1443,7 @@ describe("#collections.memberships", () => { it("should allow filtering members in collection by name", async () => { const team = await buildTeam(); - const user = await buildUser({ teamId: team.id }); + const user = await buildUser({ teamId: team.id, name: "Alice Smith" }); const collection = await buildCollection({ userId: user.id, teamId: team.id, diff --git a/server/routes/api/suggestions/suggestions.test.ts b/server/routes/api/suggestions/suggestions.test.ts index f368ca0768..cb3b36fdc3 100644 --- a/server/routes/api/suggestions/suggestions.test.ts +++ b/server/routes/api/suggestions/suggestions.test.ts @@ -7,6 +7,7 @@ import { buildUser, } from "@server/test/factories"; import { getTestServer } from "@server/test/support"; +import SearchProviderManager from "@server/utils/SearchProviderManager"; const server = getTestServer(); @@ -116,6 +117,27 @@ describe("#suggestions.mention", () => { expect(body.data.users).toEqual([]); }); + it("should return the other sections when a section is too slow", async () => { + const user = await buildUser(); + const other = await buildUser({ teamId: user.teamId, name: "Elizabeth" }); + const spy = vi + .spyOn(SearchProviderManager.getProvider(), "searchTitlesForUser") + .mockReturnValue(new Promise(() => undefined)); + + try { + const res = await server.post("/api/suggestions.mention", user); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.documents).toEqual([]); + expect(body.data.users.map((u: { id: string }) => u.id)).toContain( + other.id + ); + } finally { + spy.mockRestore(); + } + }); + it("should require authentication", async () => { const res = await server.post("/api/suggestions.mention"); expect(res.status).toEqual(401); diff --git a/server/routes/api/suggestions/suggestions.ts b/server/routes/api/suggestions/suggestions.ts index 28b94bd1b2..ed674ee9ed 100644 --- a/server/routes/api/suggestions/suggestions.ts +++ b/server/routes/api/suggestions/suggestions.ts @@ -1,6 +1,9 @@ import Router from "@koa/router"; import { Op } from "sequelize"; import { Sequelize } from "sequelize-typescript"; +import { Second } from "@shared/utils/time"; +import { withinTimeLimit } from "@shared/utils/timers"; +import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer"; import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; import { Group, User } from "@server/models"; @@ -22,6 +25,9 @@ import * as T from "./schema"; const router = new Router(); +/** The time each section of the suggestions may take before it is left out. */ +const sectionTimeLimit = Second.ms; + router.post( "suggestions.mention", auth(), @@ -80,23 +86,51 @@ router.post( }; }; + const timedOut: string[] = []; + const withinLimit = ( + section: string, + run: () => Promise, + fallback: T + ) => + withinTimeLimit(run, sectionTimeLimit, fallback, () => { + timedOut.push(section); + }); + + // Presentation is part of each section, as presenters can also query. const [documents, { users, familiarity }, groups, collections] = await Promise.all([ - SearchProviderManager.getProvider().searchTitlesForUser(actor, { - query, - offset, - limit, - filter: { - operator: "AND", - filters: [ - { field: "archivedAt", operator: "isNull" }, - { field: "publishedAt", operator: "isNotNull" }, - ], - }, - }), - suggestUsers(), - can(actor, "listGroups", actor.team) - ? Group.findAll({ + withinLimit( + "documents", + async () => + presentDocuments( + ctx, + await SearchProviderManager.getProvider().searchTitlesForUser( + actor, + { + query, + offset, + limit, + filter: { + operator: "AND", + filters: [ + { field: "archivedAt", operator: "isNull" }, + { field: "publishedAt", operator: "isNotNull" }, + ], + }, + } + ) + ), + [] + ), + withinLimit("users", suggestUsers, { users: [], familiarity: {} }), + withinLimit( + "groups", + async () => { + if (!can(actor, "listGroups", actor.team)) { + return []; + } + + const found = await Group.findAll({ where: { teamId: actor.teamId, disableMentions: false, @@ -107,34 +141,49 @@ router.post( : {}, }, order: [["name", "ASC"]], - replacements: { query: QueryHelper.likeContains(query ?? "") }, + replacements: { + query: QueryHelper.likeContains(query ?? ""), + }, offset, limit, - }) - : [], - SearchProviderManager.getProvider().searchCollectionsForUser(actor, { - query, - offset, - limit, - }), + }); + return Promise.all(found.map((group) => presentGroup(group))); + }, + [] + ), + withinLimit( + "collections", + () => + SearchProviderManager.getProvider().searchCollectionsForUser( + actor, + { + query, + offset, + limit, + } + ), + [] + ), ]); - const [presentedDocuments, presentedGroups] = await Promise.all([ - presentDocuments(ctx, documents), - Promise.all(groups.map((group) => presentGroup(group))), - ]); + if (timedOut.length) { + addTags( + { "suggestions.timedOut": timedOut.join(",") }, + getRootSpanFromRequestContext(ctx) + ); + } ctx.body = { pagination: ctx.state.pagination, data: { - documents: presentedDocuments, + documents, users: users.map((user) => presentUser(user, { includeEmail: !!can(actor, "readEmail", user), includeDetails: !!can(actor, "readDetails", user), }) ), - groups: presentedGroups, + groups, collections, familiarity, }, diff --git a/shared/utils/timers.test.ts b/shared/utils/timers.test.ts new file mode 100644 index 0000000000..8f68e5d167 --- /dev/null +++ b/shared/utils/timers.test.ts @@ -0,0 +1,50 @@ +import { withinTimeLimit } from "./timers"; + +describe("withinTimeLimit", () => { + it("should return the result when the function finishes in time", async () => { + const onTimeout = vi.fn(); + + const result = await withinTimeLimit( + async () => "done", + 100, + "fallback", + onTimeout + ); + + expect(result).toEqual("done"); + expect(onTimeout).not.toHaveBeenCalled(); + }); + + it("should return the fallback when the function is too slow", async () => { + vi.useFakeTimers(); + + try { + const onTimeout = vi.fn(); + const promise = withinTimeLimit( + () => new Promise(() => undefined), + 100, + "fallback", + onTimeout + ); + + await vi.advanceTimersByTimeAsync(100); + + await expect(promise).resolves.toEqual("fallback"); + expect(onTimeout).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it("should throw the error of a function that fails in time", async () => { + await expect( + withinTimeLimit( + async () => { + throw new Error("failed"); + }, + 100, + "fallback" + ) + ).rejects.toThrow("failed"); + }); +}); diff --git a/shared/utils/timers.ts b/shared/utils/timers.ts index 1620d79a1c..7caf3112ed 100644 --- a/shared/utils/timers.ts +++ b/shared/utils/timers.ts @@ -1,3 +1,5 @@ +import { TimeoutError, withTimeout } from "es-toolkit"; + /** * Returns a promise that resolves after a specified number of milliseconds. * @@ -6,3 +8,37 @@ export function sleep(ms = 1) { return new Promise((resolve) => setTimeout(resolve, ms)); } + +/** + * Runs an async function with a time limit, and returns a fallback value when + * the function takes too long. The function is not canceled, its result is + * ignored when it settles after the time limit. + * + * @param run the function to run. + * @param ms the time limit in milliseconds. + * @param fallback the value to return when the time limit is reached. + * @param onTimeout called when the time limit is reached. + * @returns the result of the function, or the fallback. + * @throws the error of the function, when it fails within the time limit. + */ +export async function withinTimeLimit( + run: () => Promise, + ms: number, + fallback: T, + onTimeout?: () => void +): Promise { + const controller = new AbortController(); + + try { + return await withTimeout(run, ms, { signal: controller.signal }); + } catch (err) { + if (err instanceof TimeoutError) { + onTimeout?.(); + return fallback; + } + throw err; + } finally { + // Clears the timer when the function finished within the time limit. + controller.abort(); + } +}