perf: Avoid N+1 query in share subscription notifications (#13719)

This commit is contained in:
Tom Moor authored and GitHub committed 2026-09-10 10:11:11 -04:00
1 parent 9c874b1e9a
commit b21174ccbf
3 files changed
+103 -14

No files matched your search

+58
View File
@@ -15,6 +15,7 @@ import {
buildGuestUser,
} from "@server/test/factories";
import { withAPIContext } from "@server/test/support";
import { sequelize } from "@server/storage/database";
import GroupMembership from "./GroupMembership";
import GroupUser from "./GroupUser";
import UserMembership from "./UserMembership";
@@ -260,6 +261,63 @@ describe("#findAllChildDocumentIds", () => {
});
});
describe("#findAllParentDocumentIds", () => {
test("should return empty array if there is no parent", async () => {
const document = await buildDocument();
expect(await document.findAllParentDocumentIds()).toEqual([]);
});
test("should return nested parent document ids in one query", async () => {
const parent = await buildDocument();
const child = await buildDocument({
parentDocumentId: parent.id,
collectionId: parent.collectionId,
teamId: parent.teamId,
userId: parent.createdById,
});
const grandchild = await buildDocument({
parentDocumentId: child.id,
collectionId: parent.collectionId,
teamId: parent.teamId,
userId: parent.createdById,
});
const query = sequelize.query.bind(sequelize);
const spy = vi.spyOn(sequelize, "query").mockImplementation(query);
try {
const results = await grandchild.findAllParentDocumentIds();
expect(results).toEqual([child.id, parent.id]);
expect(spy).toHaveBeenCalledTimes(1);
} finally {
spy.mockRestore();
}
});
test("should stop at soft-deleted parents unless paranoid is false", async () => {
const parent = await buildDocument();
const child = await buildDocument({
parentDocumentId: parent.id,
collectionId: parent.collectionId,
teamId: parent.teamId,
userId: parent.createdById,
});
const grandchild = await buildDocument({
parentDocumentId: child.id,
collectionId: parent.collectionId,
teamId: parent.teamId,
userId: parent.createdById,
});
await child.destroy();
expect(await grandchild.findAllParentDocumentIds()).toEqual([]);
expect(
await grandchild.findAllParentDocumentIds({ paranoid: false })
).toEqual([child.id, parent.id]);
});
});
describe("#membershipDocumentIds", () => {
it("should return empty array when the user has no document memberships", async () => {
const user = await buildUser();
+40
View File
@@ -1214,6 +1214,46 @@ class Document extends ArchivableModel<
return rows.map((row) => row.id);
};
/**
* Calculate all parent document ids for this document by recursively
* following parentDocumentId references in one query.
*
* @param options the query options.
* @returns a promise that resolves to parent document ids, nearest first.
*/
findAllParentDocumentIds = async (
options?: FindOptions<Document>
): Promise<string[]> => {
if (!this.parentDocumentId) {
return [];
}
const paranoid = options?.paranoid ?? true;
const rows = await this.sequelize!.query<{ id: string }>(
`
WITH RECURSIVE parents AS (
SELECT documents.id, documents."parentDocumentId", 1 AS depth
FROM documents
WHERE documents.id = :parentDocumentId
${paranoid ? 'AND documents."deletedAt" IS NULL' : ""}
UNION ALL
SELECT documents.id, documents."parentDocumentId", parents.depth + 1
FROM documents
INNER JOIN parents ON documents.id = parents."parentDocumentId"
${paranoid ? 'WHERE documents."deletedAt" IS NULL' : ""}
)
SELECT id FROM parents ORDER BY depth
`,
{
replacements: { parentDocumentId: this.parentDocumentId },
transaction: options?.transaction,
type: QueryTypes.SELECT,
}
);
return rows.map((row) => row.id);
};
publish = async (
ctx: APIContext,
{
@@ -14,20 +14,11 @@ export default class ShareSubscriptionNotificationsTask extends BaseTask<Revisio
return;
}
// Collect the document's ID and all ancestor IDs by walking up the tree.
// A subscription scoped to any of these documents covers the updated one.
const scopeIds: string[] = [document.id];
let parentId = document.parentDocumentId;
while (parentId) {
scopeIds.push(parentId);
const parent = await Document.findByPk(parentId, {
attributes: ["id", "parentDocumentId"],
});
if (!parent) {
break;
}
parentId = parent.parentDocumentId;
}
// A subscription scoped to this document or any ancestor covers the update.
const scopeIds = [
document.id,
...(await document.findAllParentDocumentIds()),
];
// Find all active subscriptions scoped to this document or any ancestor,
// joined to a published share that allows subscriptions.