Skip to content

fix: page import task - #1551

Merged
Philipinho merged 4 commits into
mainfrom
fix/import
Sep 13, 2025
Merged

Philipinho merged 4 commits into
mainfrom
fix/import

Conversation

@Philipinho

@Philipinho Philipinho commented Sep 13, 2025 •

Copy link
Copy Markdown
Member

Fix bug which causes imports with attachments to stall and crash the server.
Closes #1550.

Summary by CodeRabbit

  • New Features

    • Enhanced imports: Confluence-aware processing, smarter per-element attachment handling, automatic Draw.io diagram generation/embedding, and preservation of page icons during import.
  • Improvements

    • Faster attachment uploads with higher concurrency.
    • More resilient document indexing via longer retry backoff.
    • Enriched attachment metadata (sizes, MIME) and inclusion of unreferenced assets.
  • Style

    • Editor content: thinner horizontal rules with reduced spacing for a cleaner look.
  • Chores

    • Updated internal dependency reference.

- support notion page icon import
- fix horizontal rule css
- rename service file
@Philipinho Philipinho changed the title fix import fix: page import task Sep 13, 2025
@coderabbitai

coderabbitai Bot commented Sep 13, 2025 •

Copy link
Copy Markdown

Walkthrough

Refactors the import pipeline: renames FileTaskService to FileImportTaskService, expands HTML formatting to extract page icons, overhauls attachment processing with Confluence-aware logic and Draw.io handling, increases upload concurrency and indexing backoff, adjusts providers, and tweaks an editor hr style. Also updates a server submodule pointer.

Changes

Cohort / File(s) Summary of changes
Editor style tweak
apps/client/src/features/editor/styles/core.css
ProseMirror hr: border-top reduced 2px→1px; removed vertical margin; no other changes.
EE submodule pointer
apps/server/src/ee
Updated submodule reference SHA; no direct code changes.
Import service rename & wiring
apps/server/src/integrations/import/import.module.ts, apps/server/src/integrations/import/processors/file-task.processor.ts, apps/server/src/integrations/import/services/file-import-task.service.ts
Renamed FileTaskService → FileImportTaskService; updated imports, providers, and constructor injection; logger updated; service now handles pageIcon from formatter and sets page.icon.
Attachment processing overhaul
apps/server/src/integrations/import/services/import-attachment.service.ts
processAttachments signature adds isConfluenceImport?; increased concurrent uploads 3→5; gated Draw.io pairing to Confluence; per-element path resolution; Draw.io SVG generation and placeholder embedding; rewrite of img/video/a/attachment nodes; append unreferenced pageAttachments; post-upload size enrichment; increased indexing backoff (30s→3m); MIME handling improvements.
Import formatting enhancements
apps/server/src/integrations/import/utils/import-formatter.ts
formatImportHtml signature expanded (filePathToPageMetaMap, creatorId, sourcePageId, workspaceId); returns pageIcon?; extracts Unicode-based page icon; removes Notion page header icon and cover; backlinks logic retained.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as Import Job
  participant P as FileTaskProcessor
  participant S as FileImportTaskService
  participant F as formatImportHtml (utils)
  participant A as ImportAttachmentService
  participant St as StorageService
  participant Idx as Indexer

  U->>P: enqueue(import-task)
  P->>S: process(job)
  S->>F: formatImportHtml(html, meta...)
  Note right of F: Extract backlinks<br/>Remove Notion header/cover<br/>Detect pageIcon (Unicode)
  F-->>S: { html, backlinks, pageIcon? }
  S->>A: processAttachments(html, opts{..., isConfluenceImport?})
  alt Confluence import
    Note over A: Draw.io pairing + SVG generation
  else Non-Confluence
    Note over A: Skip Draw.io pairing
  end
  A->>St: upload attachments (concurrency=5)
  A-->>S: transformed HTML
  S->>Idx: schedule indexing (backoff=3m)
  S-->>P: page created/updated (icon set if provided)
  P-->>U: job complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • fix: confluence drawio import #1518 — Touches the same import attachment service and Draw.io pairing/SVG embedding logic, with similar signature extensions and processing flow changes.

Poem

In cables of code I twitch my nose,
Draw.io blooms where the diagram grows.
Five hops upload, with backoff grace,
A page finds its icon, a Unicode face.
Imports march on—no stalls, no fright—
Thump-thump, I ship this change tonight. 🐇✨

✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/import

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Pre-merge checks

❌ Failed checks (2 warnings, 2 inconclusive)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning There are out-of-scope changes in this PR: the client CSS tweak (apps/client/src/features/editor/styles/core.css) and the EE submodule pointer update (apps/server/src/ee) are unrelated to fixing import-task stalls and should be separated; renames and import-service refactors are borderline but generally relevant to the import flow. Split unrelated cosmetic and repository-meta changes (the core.css change and the ee submodule bump) into separate PRs or commits and keep this PR focused on the import-task fixes, or clearly document why those changes must be bundled here to aid review and reduce scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Linked Issues Check ❓ Inconclusive The changes modify the attachment pipeline, add per-element resolution, gate expensive Draw.io pairing to Confluence flows, and increase backoff for indexing which align with addressing import stalls reported in #1550; however the PR lacks reproduction logs, test coverage, or benchmark results demonstrating the stall is resolved on constrained hardware (4 vCPU / 4GB), and the increased concurrency may have side effects, so it is not possible to confirm the issue is fully fixed from the diff alone. Add before/after logs or CI/integration tests that reproduce the stall, include benchmarks or a reproduction report on a 4 vCPU/4GB environment, and make concurrency/backoff settings configurable (with conservative defaults) so reviewers can verify the fix and rule out regressions.
Title Check ❓ Inconclusive The current title "fix import" is related to the changeset because many import-related modules and attachment-processing behaviors were modified, but the title is overly terse and lacks specificity about what was fixed or its scope. Because it does not clearly communicate the primary change to a reviewer scanning history, the check is inconclusive. Rename the PR to a concise, descriptive title such as "fix: page import task" or "fix(import): prevent attachment-related stalls (fixes #1550)" so the main change and scope are clear to reviewers and future readers.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

@Philipinho
Philipinho merged commit 7ada3cb into main Sep 13, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server/src/integrations/import/services/file-import-task.service.ts (2)

106-116: Early return leaks tmp files and leaves task unresolved when EE module is missing.

Returning here skips cleanup and status update, causing the worker to look “stalled.”

Throw to trigger failure handling and cleanup:

-        } catch (err) {
-          this.logger.error(
-            'Confluence import requested but EE module not bundled in this build',
-          );
-          return;
-        }
+        } catch (err) {
+          throw new Error(
+            'Confluence import requested but EE module not bundled in this build'
+          );
+        }

257-304: Unbounded Promise.all can starve the event loop and trigger BullMQ stalls on large imports. Limit concurrency.

Process pages in small batches (e.g., CPUs-1, capped at 4–8).

-    const pageResults = await Promise.all(
-      Array.from(pagesMap.values()).map(async (page) => {
-        const htmlContent =
-          await this.importAttachmentService.processAttachments({
-            html: page.content,
-            pageRelativePath: page.filePath,
-            extractDir,
-            pageId: page.id,
-            fileTask,
-            attachmentCandidates,
-          });
-
-        const { html, backlinks, pageIcon } = await formatImportHtml({
-          html: htmlContent,
-          currentFilePath: page.filePath,
-          filePathToPageMetaMap: filePathToPageMetaMap,
-          creatorId: fileTask.creatorId,
-          sourcePageId: page.id,
-          workspaceId: fileTask.workspaceId,
-        });
-
-        const pmState = getProsemirrorContent(
-          await this.importService.processHTML(html),
-        );
-
-        const { title, prosemirrorJson } =
-          this.importService.extractTitleAndRemoveHeading(pmState);
-
-        const insertablePage: InsertablePage = {
-          id: page.id,
-          slugId: page.slugId,
-          title: title || page.name,
-          icon: pageIcon || null,
-          content: prosemirrorJson,
-          textContent: jsonToText(prosemirrorJson),
-          ydoc: await this.importService.createYdoc(prosemirrorJson),
-          position: page.position!,
-          spaceId: fileTask.spaceId,
-          workspaceId: fileTask.workspaceId,
-          creatorId: fileTask.creatorId,
-          lastUpdatedById: fileTask.creatorId,
-          parentPageId: page.parentPageId,
-        };
-
-        return { insertablePage, backlinks };
-      }),
-    );
+    const pages = Array.from(pagesMap.values());
+    const concurrency = Math.min(8, Math.max(1, require('os').cpus().length - 1));
+    const pageResults: { insertablePage: InsertablePage; backlinks: any[] }[] = [];
+
+    for (let i = 0; i < pages.length; i += concurrency) {
+      const batch = pages.slice(i, i + concurrency);
+      const batchResults = await Promise.all(
+        batch.map(async (page) => {
+          const htmlContent =
+            await this.importAttachmentService.processAttachments({
+              html: page.content,
+              pageRelativePath: page.filePath,
+              extractDir,
+              pageId: page.id,
+              fileTask,
+              attachmentCandidates,
+            });
+
+          const { html, backlinks, pageIcon } = await formatImportHtml({
+            html: htmlContent,
+            currentFilePath: page.filePath,
+            filePathToPageMetaMap: filePathToPageMetaMap,
+            creatorId: fileTask.creatorId,
+            sourcePageId: page.id,
+            workspaceId: fileTask.workspaceId,
+          });
+
+          const pmState = getProsemirrorContent(
+            await this.importService.processHTML(html),
+          );
+          const { title, prosemirrorJson } =
+            this.importService.extractTitleAndRemoveHeading(pmState);
+
+          const insertablePage: InsertablePage = {
+            id: page.id,
+            slugId: page.slugId,
+            title: title || page.name,
+            icon: pageIcon || null,
+            content: prosemirrorJson,
+            textContent: jsonToText(prosemirrorJson),
+            ydoc: await this.importService.createYdoc(prosemirrorJson),
+            position: page.position!,
+            spaceId: fileTask.spaceId,
+            workspaceId: fileTask.workspaceId,
+            creatorId: fileTask.creatorId,
+            lastUpdatedById: fileTask.creatorId,
+            parentPageId: page.parentPageId,
+          };
+          return { insertablePage, backlinks };
+        }),
+      );
+      pageResults.push(...batchResults);
+    }

If you prefer a small util, I can refactor this into a reusable mapWithConcurrency.

🧹 Nitpick comments (13)
apps/client/src/features/editor/styles/core.css (1)

95-102: HR thickness change: verify contrast and selection affordance.

Dropping to 1px looks fine; ensure it remains visible in dark mode and when selected.

Consider using theme tokens for consistency:

-    border-top: 1px solid #ced4da;
+    border-top: 1px solid var(--mantine-color-gray-4);
apps/server/src/integrations/import/utils/import-formatter.ts (2)

7-11: Emoji detection can be more robust.

Checking only the first code point >127 can misclassify multi-codepoint emojis/ZWJ sequences.

Use Unicode property escapes:

-function isUnicodeCharacter(text: string): boolean {
-  return text.length > 0 && text.codePointAt(0)! > 127; // Non-ASCII characters
-}
+function isUnicodeCharacter(text: string): boolean {
+  // Matches extended pictographic (emoji) or any non-ASCII char
+  return /\p{Extended_Pictographic}|\P{ASCII}/u.test(text);
+}

40-50: Broaden selector to reliably capture Notion icons.

Some Notion exports don’t nest under a

, or the emoji may be on .page-header-icon directly.

-  const headerIconSpan = $root.find('header .page-header-icon .icon');
+  const headerIconSpan = $root.find(
+    'header .page-header-icon .icon, .page-header-icon .icon, .page-header-icon'
+  );
apps/server/src/integrations/import/processors/file-task.processor.ts (2)

20-34: Method name nit: “processZIpImport” → “processZipImport”.

Cosmetic, but avoid confusion and grep misses.

Apply rename in service and here:

-          await this.fileTaskService.processZIpImport(job.data.fileTaskId);
+          await this.fileTaskService.processZipImport(job.data.fileTaskId);

41-62: Improve stalled-job visibility.

Optional: handle BullMQ “stalled” to aid debugging of issue #1550.

Add:

@OnWorkerEvent('stalled')
onStalled(job: Job) {
  this.logger.warn(`Stalled ${job.name} job for File task ID ${job.data?.fileTaskId}`);
}

Also prefer this.logger.error(message, err instanceof Error ? err.stack : undefined).

apps/server/src/integrations/import/services/file-import-task.service.ts (1)

49-69: Nit: method name “processZIpImport”.

Rename to “processZipImport” for consistency. Remember to update the processor call.

-  async processZIpImport(fileTaskId: string): Promise<void> {
+  async processZipImport(fileTaskId: string): Promise<void> {
apps/server/src/integrations/import/services/import-attachment.service.ts (7)

38-38: Make upload concurrency configurable (avoid regressions on constrained hosts).

Hardcoding 5 may hurt low‑RAM/IO boxes (like the Proxmox report). Read from env/config with a sane default.

-  private readonly CONCURRENT_UPLOADS = 5;
+  private readonly CONCURRENT_UPLOADS = parseInt(
+    process.env.IMPORT_CONCURRENT_UPLOADS ?? '5',
+    10,
+  );

101-108: Preserve diagram names and surface sizes for Draw.io placeholders.

  • Use ${pair.baseName}.drawio.svg instead of a generic filename.
  • Store svgBuffer.length and set data-size on created <div data-type="drawio">.
@@
-    const drawioSvgMap = new Map<
-      string,
-      {
-        attachmentId: string;
-        apiFilePath: string;
-        fileName: string;
-      }
-    >();
+    const drawioSvgMap = new Map<
+      string,
+      {
+        attachmentId: string;
+        apiFilePath: string;
+        fileName: string;
+        size: number;
+      }
+    >();
@@
-        const fileName = 'diagram.drawio.svg';
+        const fileName = `${pair.baseName || 'diagram'}.drawio.svg`;
@@
-        drawioSvgMap.set(drawioHref, { attachmentId, apiFilePath, fileName });
+        drawioSvgMap.set(drawioHref, {
+          attachmentId,
+          apiFilePath,
+          fileName,
+          size: svgBuffer.length,
+        });
         if (pair.pngFile) {
-          drawioSvgMap.set(pair.pngFile.href, {
-            attachmentId,
-            apiFilePath,
-            fileName,
-          });
+          drawioSvgMap.set(pair.pngFile.href, {
+            attachmentId,
+            apiFilePath,
+            fileName,
+            size: svgBuffer.length,
+          });
         }
@@
         const $drawio = $('<div>')
           .attr('data-type', 'drawio')
           .attr('data-src', drawioSvg.apiFilePath)
           .attr('data-title', 'diagram')
           .attr('data-width', '100%')
           .attr('data-align', 'center')
-          .attr('data-attachment-id', drawioSvg.attachmentId);
+          .attr('data-attachment-id', drawioSvg.attachmentId)
+          .attr('data-size', String(drawioSvg.size));
@@
         const $drawio = $('<div>')
           .attr('data-type', 'drawio')
           .attr('data-src', drawioSvg.apiFilePath)
           .attr('data-title', 'diagram')
           .attr('data-width', '100%')
           .attr('data-align', 'center')
-          .attr('data-attachment-id', drawioSvg.attachmentId);
+          .attr('data-attachment-id', drawioSvg.attachmentId)
+          .attr('data-size', String(drawioSvg.size));
@@
       const $drawio = $('<div>')
         .attr('data-type', 'drawio')
         .attr('data-src', drawioSvg.apiFilePath)
         .attr('data-title', 'diagram')
         .attr('data-width', '100%')
         .attr('data-align', 'center')
-        .attr('data-attachment-id', drawioSvg.attachmentId);
+        .attr('data-attachment-id', drawioSvg.attachmentId)
+        .attr('data-size', String(drawioSvg.size));

Also applies to: 127-135, 173-181, 257-269, 357-369, 457-465


243-254: Skip non-relative image URLs (data:, blob:, mailto:, etc.).

The current check only handles http(s). Broaden it to avoid unnecessary work and edge errors.

-      const src = cleanUrlString($img.attr('src') ?? '')!;
-      if (!src || src.startsWith('http')) continue;
+      const src = cleanUrlString($img.attr('src') ?? '')!;
+      if (!src || /^(?:[a-z][a-z0-9+.+-]*:)/i.test(src)) continue; // http, https, data, blob, mailto, etc.

286-299: Handle

Notion/Confluence exports often use nested . Also broaden the scheme guard like images.

-      const $vid = $(vidEl);
-      const src = cleanUrlString($vid.attr('src') ?? '')!;
-      if (!src || src.startsWith('http')) continue;
+      const $vid = $(vidEl);
+      const src = cleanUrlString(
+        $vid.attr('src') ?? $vid.find('source[src]').first().attr('src') ?? '',
+      )!;
+      if (!src || /^(?:[a-z][a-z0-9+.+-]*:)/i.test(src)) continue;

341-353: Anchor rewrite: avoid touching external/data/mailto/tel links.

-      const href = cleanUrlString($a.attr('href') ?? '')!;
-      if (!href || href.startsWith('http')) continue;
+      const href = cleanUrlString($a.attr('href') ?? '')!;
+      if (!href || /^(?:https?:|mailto:|tel:|data:|blob:|ftp:)/i.test(href)) continue;

404-416: Skip non-relative data-src for excalidraw/drawio blocks.

-        const rawSrc = cleanUrlString($oldDiv.attr('data-src') ?? '')!;
-        if (!rawSrc || rawSrc.startsWith('http')) continue;
+        const rawSrc = cleanUrlString($oldDiv.attr('data-src') ?? '')!;
+        if (!rawSrc || /^(?:[a-z][a-z0-9+.+-]*:)/i.test(rawSrc)) continue;

530-555: Avoid O(n^2) lookup when adding data-size; also skip Draw.io already sized.

Build a small map once to resolve ids to paths in O(1) and keep loop linear.

-    const elementsNeedingSize = $('[data-attachment-id]:not([data-size])');
-    for (const element of elementsNeedingSize.toArray()) {
-      const $el = $(element);
-      const attachmentId = $el.attr('data-attachment-id');
-      if (!attachmentId) continue;
-
-      // Find the corresponding processed file info
-      const processedEntry = Array.from(processed.values()).find(
-        (entry) => entry.attachmentId === attachmentId,
-      );
-
-      if (processedEntry) {
-        try {
-          const stat = await fs.stat(processedEntry.abs);
-          $el.attr('data-size', stat.size.toString());
-        } catch (error) {
-          this.logger.debug(
-            `Could not get size for ${processedEntry.abs}:`,
-            error,
-          );
-        }
-      }
-    }
+    const elementsNeedingSize = $('[data-attachment-id]:not([data-size])');
+    // Build id -> abs lookup (O(n))
+    const processedById = new Map<string, { abs: string }>();
+    for (const entry of processed.values()) {
+      processedById.set(entry.attachmentId, { abs: entry.abs });
+    }
+    for (const element of elementsNeedingSize.toArray()) {
+      const $el = $(element);
+      const attachmentId = $el.attr('data-attachment-id');
+      if (!attachmentId) continue;
+      const processedEntry = processedById.get(attachmentId);
+      if (!processedEntry) continue;
+      try {
+        const stat = await fs.stat(processedEntry.abs);
+        $el.attr('data-size', String(stat.size));
+      } catch (error) {
+        this.logger.debug(
+          `Could not get size for ${processedEntry.abs}:`,
+          error,
+        );
+      }
+    }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47c5417 and 7ccd886.

📒 Files selected for processing (7)
  • apps/client/src/features/editor/styles/core.css (1 hunks)
  • apps/server/src/ee (1 hunks)
  • apps/server/src/integrations/import/import.module.ts (2 hunks)
  • apps/server/src/integrations/import/processors/file-task.processor.ts (2 hunks)
  • apps/server/src/integrations/import/services/file-import-task.service.ts (3 hunks)
  • apps/server/src/integrations/import/services/import-attachment.service.ts (8 hunks)
  • apps/server/src/integrations/import/utils/import-formatter.ts (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
apps/server/src/integrations/import/utils/import-formatter.ts (1)
apps/server/src/database/types/entity.types.ts (1)
  • InsertableBacklink (90-90)
apps/server/src/integrations/import/services/file-import-task.service.ts (1)
apps/server/src/integrations/import/utils/import-formatter.ts (1)
  • formatImportHtml (12-69)
apps/server/src/integrations/import/services/import-attachment.service.ts (4)
apps/server/src/integrations/import/utils/file.utils.ts (1)
  • cleanUrlString (183-187)
apps/server/src/integrations/import/utils/import.utils.ts (1)
  • resolveRelativeAttachmentPath (28-43)
apps/server/src/integrations/import/utils/import-formatter.ts (1)
  • unwrapFromParagraph (221-236)
apps/server/src/common/helpers/file.helper.ts (1)
  • getMimeType (4-7)
🔇 Additional comments (9)
apps/server/src/ee (1)

1-1: Confirm EE submodule bump: verify commit provenance, CI submodule update, and breaking changes.

  • .gitmodules: apps/server/src/ee -> https://github.com/docmost/ee. HEAD submodule commit is d03a6a3f2de77df4447b56135e1600243bd67173 (previous d90ce7a…); commits not present locally — confirm d03a6a3 is an audited/tagged EE release and contains only the intended import-task fixes (link tag/changelog/compare in the PR).
  • Ensure CI runs submodule sync/update so builds use the new EE commit:
    git submodule sync --recursive && git submodule update --init --recursive
  • Prefer pinning the submodule to a tag for auditability; if no tag exists, add a PR note linking the EE changelog/compare for this range.
  • Sanity-check for new DB migrations or breaking API changes in EE that could affect import processors/queues.
apps/server/src/integrations/import/utils/import-formatter.ts (2)

24-28: Return shape extension (pageIcon): LGTM.

Also applies to: 65-68


93-96: Removing header icon/cover from Notion HTML: LGTM.

Prevents duplicate rendering once icon is saved separately.

apps/server/src/integrations/import/import.module.ts (1)

12-17: Provider rename wiring: LGTM.

Module correctly provides FileImportTaskService in place of FileTaskService.

apps/server/src/integrations/import/processors/file-task.processor.ts (1)

13-16: Service rename injection: LGTM.

apps/server/src/integrations/import/services/file-import-task.service.ts (3)

36-38: Class rename + logger context: LGTM.


126-137: Cleanup order on success: LGTM.

Status update, tmp cleanup, then storage delete is fine; deletion failure is logged without flipping status.


332-346: DB status update error handling: LGTM.

Silent failure is logged; acceptable for non-critical path.

apps/server/src/integrations/import/services/import-attachment.service.ts (1)

56-57: Pass isConfluenceImport from callers (Confluence=true; others false/undefined).

processAttachments(...) is invoked at apps/server/src/integrations/import/services/file-import-task.service.ts:260 but no isConfluenceImport is passed; import-attachment.service.ts declares the param (fn signature at line 48) and early-returns when !isConfluenceImport (if (!isConfluenceImport) at line 569). Ensure the Confluence EE import path calls processAttachments with isConfluenceImport: true, and Notion/generic callers pass false or leave it undefined.

backoff: {
type: 'exponential',
delay: 30 * 1000,
delay: 3 * 60 * 1000,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Good call on longer indexing backoff; add an upload timeout to prevent job stalls.

Stalls are often blocked streams. Wrap uploadStream with a per‑file timeout and abort the read stream on expiry.

// Add once near other constants:
private readonly UPLOAD_TIMEOUT_MS =
  parseInt(process.env.IMPORT_UPLOAD_TIMEOUT_MS ?? '120000', 10);

// Inside uploadWithRetry() before/around uploadStream():
const fileStream = createReadStream(abs);
try {
  await Promise.race([
    this.storageService.uploadStream(storageFilePath, fileStream),
    new Promise((_, reject) =>
      setTimeout(() => {
        try { fileStream.destroy(new Error('upload timeout')); } catch {}
        reject(new Error(`Upload timed out after ${this.UPLOAD_TIMEOUT_MS} ms`));
      }, this.UPLOAD_TIMEOUT_MS),
    ),
  ]);
} finally {
  // Best-effort close
  try { fileStream.destroy(); } catch {}
}
🤖 Prompt for AI Agents
In apps/server/src/integrations/import/services/import-attachment.service.ts
around line 836, the upload can stall because uploadStream may block
indefinitely; add a per-file upload timeout to abort stalled uploads by: define
a UPLOAD_TIMEOUT_MS constant (from process.env IMPORT_UPLOAD_TIMEOUT_MS with a
sensible default like 120000), then when creating the read stream for a file
wrap the upload call in a Promise.race between storageService.uploadStream(...)
and a timeout Promise that destroys the read stream and rejects with a timeout
error after UPLOAD_TIMEOUT_MS, and finally ensure a best-effort cleanup by
destroying/closing the file stream in a finally block so stuck streams are
aborted and jobs don’t hang.

@coderabbitai coderabbitai Bot mentioned this pull request Sep 17, 2025
github-actions Bot added a commit to antiagingrecord/docmost that referenced this pull request Oct 9, 2025
4231ba9 Merge commit '042836cb6d7cc1f71af3ce44c7957f8abbbf8f25' into feat/aar_edition
042836c sync
4f1f0ba fix
3164b69 feat: api keys management (EE) (docmost#1665)
16c1e86 fix comment space
c9b1cad sync
bf8cf62 feat: Typesense search driver (EE) (docmost#1664)
5a2e16a Merge commit '31350303760163384113bf49d07127e886f94907' into feat/aar_edition
3bc710d Adds CLAUDE.md documentation
16914f1 Block search for non-indexed shares
ca75e29 Set default page mode to Read
3135030 fix editor converter (docmost#1647)
3fae41a fix: editor performance improvements (docmost#1648)
b50e256 sync
1f3b0c7 cloud fix
3c4cab0 v0.23.2
4de25a8 invalidate queries on space deletion
cf5bbb1 fix import html processing
ac17521 sync
9ac180f fix: enhance page import (docmost#1570)
46669fe (cloud) disable page sharing in trial mode
fe6ecdf fix: update combobox props in SpaceSelect component (docmost#1564)
04ae1d7 Allow lastColumnResizable in table
1280f96 feat: implement space and workspace icons (docmost#1558)
61d1cf8 fix: reset file inputs after import
f413720 - sync - reinstantiate S3 client to fix file upload errors during import - delete import zip file after use
8e16ad9 v0.23.1
7ada3cb fix: page import task (docmost#1551)
47c5417 sync
dc06502 sync
091e790 fix attachment search in cloud
ae24ea2 v0.23.0
9df6061 lock file
31053e2 update mermaid
eb8e850 use debug
c99bfb8 make print better
26ea04e sync
6cc58c5 sync
7d2ff34 UI fixes
b08d37f fix
d43ee77 remove debug log
5d91eb4 feat: queue imported attachments for indexing
3e9f6b1 Remove version from docker-compose.yml [deprecated] (docmost#1011)
db55de9 feat: progressive web app (docmost#614)
1919eba New Crowdin updates (docmost#1522)
7951b2e New Crowdin updates (docmost#1509)
73b78f6 more translations
cf7534d fix version display
adec36d fix: adjust margins - use default browser highlight background
f9e1080 sync
00e499b Fixing extra page bug on print (docmost#1478)
5ee6e46 checkbox aligned to text (docmost#1486)
1f797c3 fix: confluence drawio import (docmost#1518)
f12866c feat(EE): full-text search in attachments (docmost#1502)
dcbb65d feat(EE): LDAP integration (docmost#1515)
5968764 feat: emoji callout icon (docmost#1323)
242fb6b fix: set mermaid theme based on computed color scheme (docmost#1438)
74cd890 feat(EE): implement SSO group sync for SAML and OIDC (docmost#1452)
509622a ignore type error
937386e fix: hide table handles in readonly mode
60a373f fix: readonly editor table responsiveness
73ee6ee feat: subpages (child pages) list node (docmost#1462)
7d1e5bc feat: table row/column drag and drop (docmost#1467)
aa58e27 fix: exclude deleted pages (docmost#1494)
08135a2 sync
d92a942 sync
5012a68 sync
5a33777 feat: debug mode env variable (docmost#1450)
3b85f4b fix: enforce C collation for page position ordering to ensure consistent behavior in Postgres 17+ (docmost#1446)
cb2a039 fix: invalidate trashed page from tree state
95b7be6 fix: hide trash from can view permission (docmost#1445)
b0c5572 fix nested taskList in markdown export (docmost#1443)
dddfd48 feat: add attachments support for single page exports (docmost#1440)
aa6eec7 fix: exclude trashed pages from position generation
97a7701 fix local storage copy function (docmost#1442)
b97eb85 sync

git-subtree-dir: vendor/app
git-subtree-split: 4231ba9
@Philipinho
Philipinho deleted the fix/import branch December 14, 2025 19:06
nulluserid pushed a commit to N2con-Inc/docmost that referenced this pull request Dec 17, 2025
* fix import

* - fix notion importer
- support notion page icon import
- fix horizontal rule css
- rename service file

* sync

* 3 mins delay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Proxmox + Docmost Import Task Issue (Notion zip import stalls)

1 participant