fix: Prevent Notion imports looping forever (#14456)

* fix: Prevent Notion import looping on self-referencing pages

* fix: Stop import tasks once the import has finished
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-03 08:27:14 -05:00
1 parent e5b90b50c7
commit fb2f0e76d1
4 files changed
+157 -17

No files matched your search

@@ -0,0 +1,105 @@
import { randomUUID } from "node:crypto";
import { ImportState, ImportTaskPhase, ImportTaskState } from "@shared/types";
import { ImportTask } from "@server/models";
import { buildImport } from "@server/test/factories";
import { mockTaskSchedule } from "@server/test/support";
import { NotionClient } from "../notion";
import type { Block } from "../../shared/types";
import { PageType } from "../../shared/types";
import NotionAPIImportTask from "./NotionAPIImportTask";
const childPage = (id: string) =>
({
object: "block",
id,
type: "child_page",
has_children: false,
child_page: { title: id },
}) as unknown as Block;
const mockFetchPage = (blocks: Block[]) =>
vi.spyOn(NotionClient.prototype, "fetchPage").mockResolvedValue({
title: "Page",
blocks,
});
describe("NotionAPIImportTask", () => {
const schedule = mockTaskSchedule();
const buildImportTask = async (
importId: string,
item: { externalId: string; ancestorExternalIds?: string[] }
) =>
ImportTask.create({
state: ImportTaskState.InProgress,
phase: ImportTaskPhase.Page,
input: [{ type: PageType.Page, ...item }],
importId,
});
const createdTasks = (importId: string) =>
ImportTask.findAll({
where: { importId, state: ImportTaskState.Created },
});
it("should not queue a page that lists itself as a child", async () => {
const importModel = await buildImport();
const pageId = randomUUID();
const childId = randomUUID();
const importTask = await buildImportTask(importModel.id, {
externalId: pageId,
});
mockFetchPage([childPage(pageId), childPage(childId)]);
await new NotionAPIImportTask().perform({ importTaskId: importTask.id });
const tasks = await createdTasks(importModel.id);
expect(tasks).toHaveLength(1);
expect(tasks[0].input).toEqual([
expect.objectContaining({
externalId: childId,
parentExternalId: pageId,
ancestorExternalIds: [pageId],
}),
]);
expect(schedule).toHaveBeenCalledTimes(1);
});
it("should not queue an ancestor or a repeated child", async () => {
const importModel = await buildImport();
const rootId = randomUUID();
const pageId = randomUUID();
const childId = randomUUID();
const importTask = await buildImportTask(importModel.id, {
externalId: pageId,
ancestorExternalIds: [rootId],
});
mockFetchPage([childPage(rootId), childPage(childId), childPage(childId)]);
await new NotionAPIImportTask().perform({ importTaskId: importTask.id });
const tasks = await createdTasks(importModel.id);
expect(tasks).toHaveLength(1);
expect(tasks[0].input).toEqual([
expect.objectContaining({
externalId: childId,
ancestorExternalIds: [rootId, pageId],
}),
]);
});
it("should stop when the import has already finished", async () => {
const importModel = await buildImport({ state: ImportState.Completed });
const importTask = await buildImportTask(importModel.id, {
externalId: randomUUID(),
});
const fetchPage = mockFetchPage([childPage(randomUUID())]);
await new NotionAPIImportTask().perform({ importTaskId: importTask.id });
await importTask.reload();
expect(importTask.state).toEqual(ImportTaskState.Canceled);
expect(fetchPage).not.toHaveBeenCalled();
expect(schedule).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,5 @@
import { APIResponseError, APIErrorCode } from "@notionhq/client";
import { uniqBy } from "es-toolkit/compat";
import type { ImportTaskInput, ImportTaskOutput } from "@shared/schema";
import type { IntegrationService, ProsemirrorDoc } from "@shared/types";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
@@ -49,15 +50,24 @@ export default class NotionAPIImportTask extends APIImportTask<IntegrationServic
const client = new NotionClient(integration.authentication.token);
const parsedPages: (ParsePageOutput | null)[] = [];
const parsedPages: (ParsePageOutput & { ancestorExternalIds: string[] })[] =
[];
for (const item of importTask.input) {
parsedPages.push(await this.parsePage({ item, client }));
const parsedPage = await this.parsePage({ item, client });
// Skip pages/databases that couldn't be accessed
if (parsedPage) {
parsedPages.push({
...parsedPage,
ancestorExternalIds: [
...(item.ancestorExternalIds ?? []),
item.externalId,
],
});
}
}
// Filter out any null results (from pages/databases that couldn't be accessed)
const validParsedPages = parsedPages.filter(Boolean) as ParsePageOutput[];
const taskOutput: ImportTaskOutput = validParsedPages.map((parsedPage) => ({
const taskOutput: ImportTaskOutput = parsedPages.map((parsedPage) => ({
externalId: parsedPage.externalId,
title: parsedPage.title,
icon: parsedPage.icon,
@@ -68,13 +78,26 @@ export default class NotionAPIImportTask extends APIImportTask<IntegrationServic
}));
const childTasksInput: ImportTaskInput<IntegrationService.Notion> =
validParsedPages.flatMap((parsedPage) =>
parsedPage.children.map((childPage) => ({
type: childPage.type,
externalId: childPage.externalId,
parentExternalId: parsedPage.externalId,
collectionExternalId: parsedPage.collectionExternalId,
}))
parsedPages.flatMap((parsedPage) =>
uniqBy(parsedPage.children, "externalId")
.filter((childPage) => {
// A page that contains one of its ancestors would be queued forever.
if (parsedPage.ancestorExternalIds.includes(childPage.externalId)) {
Logger.warn(
`Skipping Notion page ${childPage.externalId} - it is an ancestor of ${parsedPage.externalId}`,
{ importId: importTask.importId }
);
return false;
}
return true;
})
.map((childPage) => ({
type: childPage.type,
externalId: childPage.externalId,
parentExternalId: parsedPage.externalId,
collectionExternalId: parsedPage.collectionExternalId,
ancestorExternalIds: parsedPage.ancestorExternalIds,
}))
);
return { taskOutput, childTasksInput };
+2
View File
@@ -16,6 +16,8 @@ export type NotionImportInput = z.infer<typeof NotionImportInputItemSchema>[];
export const NotionImportTaskInputItemSchema =
BaseImportTaskInputItemSchema.extend({
type: z.enum(PageType),
/** External ids of the pages above this page, from the root down. */
ancestorExternalIds: z.array(z.string()).optional(),
});
export type NotionImportTaskInput = z.infer<
+14 -4
View File
@@ -40,6 +40,13 @@ export type ProcessOutput<T extends ImportableIntegrationService> = {
childTasksInput: ImportTaskInput<T>;
};
const FinishedImportStates = [
ImportState.Processed,
ImportState.Completed,
ImportState.Errored,
ImportState.Canceled,
];
type Props = {
/** id of the import_task */
importTaskId: string;
@@ -71,10 +78,13 @@ export default abstract class APIImportTask<
return;
}
// Don't process any further when the associated import is canceled by the user.
if (importTask.import.state === ImportState.Canceled) {
importTask.state = ImportTaskState.Canceled;
await importTask.save();
// Don't process any further when the associated import is canceled by the
// user or has already finished.
if (FinishedImportStates.includes(importTask.import.state)) {
if (importTask.state !== ImportTaskState.Completed) {
importTask.state = ImportTaskState.Canceled;
await importTask.save();
}
return;
}