Repository navigation
feat(connector): add SitemapConnector for sitemap.xml-based web ingestion - #16040
vincentlambert wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds ChangesSitemap Connector Feature
Sequence Diagram(s)sequenceDiagram
participant SyncWorker
participant Sitemap
participant SitemapConnector
participant _iter_sitemap_urls
participant _fetch_raw
participant trafilatura
rect rgba(70, 130, 180, 0.5)
Note over SyncWorker,Sitemap: Full sync (reindex=True)
SyncWorker->>Sitemap: _generate(doc)
Sitemap->>SitemapConnector: load_from_state()
end
rect rgba(100, 160, 100, 0.5)
Note over SyncWorker,Sitemap: Incremental sync
SyncWorker->>Sitemap: _generate(doc)
Sitemap->>SitemapConnector: poll_source(start, end)
end
SitemapConnector->>_iter_sitemap_urls: parse sitemap XML recursively
_iter_sitemap_urls-->>SitemapConnector: (loc, lastmod) pairs
SitemapConnector->>_fetch_raw: fetch URL (SSRF-safe, redirect-following)
_fetch_raw-->>SitemapConnector: (content_bytes, content_type)
alt content_type == text/html
SitemapConnector->>trafilatura: extract(content_bytes) → markdown
trafilatura-->>SitemapConnector: markdown text
else content_type == application/pdf
SitemapConnector->>SitemapConnector: wrap raw bytes as Document
end
SitemapConnector-->>Sitemap: yield Document batches
Sitemap->>Sitemap: sanitize semantic_identifier (strip http/https)
Sitemap-->>SyncWorker: sanitized Document batches
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
pyproject.toml (1)
43-43: Consider pinning an upper bound on the trafilatura version constraint.The
>=2.0.0constraint is open-ended. While trafilatura is a stable library (latest is 2.1.0, compatible with Python 3.13+), adding an upper bound like<3.0.0would prevent unexpected breaking changes from future major versions and improve long-term maintainability.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pyproject.toml` at line 43, The trafilatura dependency specification at line 43 in pyproject.toml uses an open-ended version constraint of `>=2.0.0` without an upper bound. To prevent unexpected breaking changes from future major versions, add an upper bound constraint to the trafilatura dependency specification by changing it from `>=2.0.0` to `>=2.0.0,<3.0.0` to maintain compatibility while protecting against major version upgrades.common/data_source/sitemap_connector.py (1)
178-181: Usedefusedxmlfor parsing external sitemap XML as a defense-in-depth best practice.While
xml.etree.ElementTreein Python 3.13+ does not expand external entities by default and is protected against billion laughs DoS attacks via Expat 2.4.1+, usingdefusedxmlis recommended when parsing untrusted XML to provide consistent hardened protection across all XML-based threats.Additionally, consider adding logging at line 179 to track XML parsing attempts for the new sitemap parsing flow, as required by coding guidelines.
Suggested fix
-from xml.etree import ElementTree as ET +import defusedxml.ElementTree as ETAdd
defusedxmlto project dependencies.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@common/data_source/sitemap_connector.py` around lines 178 - 181, The code uses `ET.fromstring()` to parse external sitemap XML, which should use `defusedxml` instead for hardened protection against XML-based threats. Replace the `ET.fromstring(content)` call in the try block with the equivalent from `defusedxml.ElementTree`, add logging to track XML parsing attempts after the root assignment (at line 179) as required by coding guidelines, and ensure `defusedxml` is added to the project dependencies.test/unit_test/data_source/test_sitemap_connector_unit.py (1)
85-87: ⚡ Quick winAssert SSRF guard invocation in at least one representative fetch-path test.
_patch_ssrfcurrently stubs safety behavior but doesn’t let tests verify the guard was actually called. A regression that bypasses SSRF checks could still pass.Also applies to: 240-353
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/data_source/test_sitemap_connector_unit.py` around lines 85 - 87, The `_patch_ssrf` function currently stubs the SSRF guard with a simple lambda that doesn't track invocations, making it impossible to verify the guard was actually called and allowing SSRF bypass regressions to go undetected. Replace the lambda stub with a spy or mock object that tracks calls, then add assertions in at least one representative fetch-path test (and in the other affected tests in the 240-353 range) to verify that `assert_url_is_safe` was actually invoked during the fetch operation. This ensures that any regression bypassing SSRF checks will be caught by the tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@common/data_source/sitemap_connector.py`:
- Around line 69-73: Remove the redundant regex re-compilation validation block
(the try-except that calls re.compile on self._url_filter.pattern) since
self._url_filter is already a compiled re.Pattern object from __init__ and will
never raise re.error when re-compiling a pattern that already compiled
successfully. Instead, move the regex validation to the __init__ method (around
lines 54-56 where self._url_filter is first created) to catch invalid regex
patterns at initialization time, before the Pattern object is stored.
In `@rag/svr/sync_data_source.py`:
- Around line 549-568: The _generate method for the Sitemap sync flow is missing
a self.log_connection(...) call that exists in other sync sources for
observability. Add a self.log_connection(...) call in the _generate method after
the connector is initialized and validated (after
self.connector.validate_connector_settings()) but before the data loading or
polling occurs, to ensure consistent logging across all sync source connectors
as required by the coding guidelines.
- Around line 541-546: The current reconstruction of semantic_identifier at line
544 uses only netloc and path from the parsed URL, which drops query parameters
and fragments. This causes distinct URLs (e.g., different query strings) to
collapse into the same semantic_identifier, leading to data loss when documents
overwrite each other. Preserve URL uniqueness by including the query and
fragment components in the rebuilt semantic_identifier string when
reconstructing the si variable in the URL processing block.
In `@test/unit_test/data_source/test_sitemap_connector_unit.py`:
- Around line 7-12: Add required pytest priority markers to all test functions
and test classes in the test_sitemap_connector_unit.py module to comply with the
coding guidelines. Apply one of the priority markers (p1, p2, or p3) as a
decorator to each test function and test class using the `@pytest.mark.p1`,
`@pytest.mark.p2`, or `@pytest.mark.p3` syntax. The marker choice should reflect the
priority level of each test based on your testing strategy.
- Around line 93-97: The _patch_trafilatura function directly assigns to
sys.modules which can leak mocked module state across tests. Replace the
sys.modules assignment on line 96 with monkeypatch.setitem(sys.modules,
"trafilatura", mock) to ensure proper cleanup via pytest fixtures. Additionally,
all 21 test functions in this file are missing required pytest priority markers.
Add `@pytest.mark.p1`, `@pytest.mark.p2`, or `@pytest.mark.p3` decorators to each test
function according to the coding guideline for test files.
---
Nitpick comments:
In `@common/data_source/sitemap_connector.py`:
- Around line 178-181: The code uses `ET.fromstring()` to parse external sitemap
XML, which should use `defusedxml` instead for hardened protection against
XML-based threats. Replace the `ET.fromstring(content)` call in the try block
with the equivalent from `defusedxml.ElementTree`, add logging to track XML
parsing attempts after the root assignment (at line 179) as required by coding
guidelines, and ensure `defusedxml` is added to the project dependencies.
In `@pyproject.toml`:
- Line 43: The trafilatura dependency specification at line 43 in pyproject.toml
uses an open-ended version constraint of `>=2.0.0` without an upper bound. To
prevent unexpected breaking changes from future major versions, add an upper
bound constraint to the trafilatura dependency specification by changing it from
`>=2.0.0` to `>=2.0.0,<3.0.0` to maintain compatibility while protecting against
major version upgrades.
In `@test/unit_test/data_source/test_sitemap_connector_unit.py`:
- Around line 85-87: The `_patch_ssrf` function currently stubs the SSRF guard
with a simple lambda that doesn't track invocations, making it impossible to
verify the guard was actually called and allowing SSRF bypass regressions to go
undetected. Replace the lambda stub with a spy or mock object that tracks calls,
then add assertions in at least one representative fetch-path test (and in the
other affected tests in the 240-353 range) to verify that `assert_url_is_safe`
was actually invoked during the fetch operation. This ensures that any
regression bypassing SSRF checks will be caught by the tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2ffbffdd-b766-49e4-8adb-010c5c1db24c
📒 Files selected for processing (7)
common/constants.pycommon/data_source/__init__.pycommon/data_source/config.pycommon/data_source/sitemap_connector.pypyproject.tomlrag/svr/sync_data_source.pytest/unit_test/data_source/test_sitemap_connector_unit.py
9820328 to
8068352
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@common/data_source/sitemap_connector.py`:
- Around line 161-163: The return type annotation for the _iter_sitemap_urls
method is incorrect. The function uses yield statements (at lines 190 and 205)
making it a generator, but the return type is annotated as list[tuple[str,
datetime | None]] which indicates a list. Change the return type annotation to
Generator[tuple[str, datetime | None], None, None] from the typing module, or
alternatively use Iterable[tuple[str, datetime | None]] for a broader type that
better represents that this function yields values rather than returning a
concrete list.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 5b4bfff2-bb8e-4d9c-8a6e-88eda4d849d4
📒 Files selected for processing (7)
common/constants.pycommon/data_source/__init__.pycommon/data_source/config.pycommon/data_source/sitemap_connector.pypyproject.tomlrag/svr/sync_data_source.pytest/unit_test/data_source/test_sitemap_connector_unit.py
🚧 Files skipped from review as they are similar to previous changes (4)
- common/data_source/config.py
- common/constants.py
- common/data_source/init.py
- pyproject.toml
8068352 to
b4bf1bb
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@common/data_source/sitemap_connector.py`:
- Around line 356-365: The _parse_lastmod function rejects ISO/RFC3339
timestamps with fractional seconds (e.g., `2023-01-01T12:34:56.789Z`) because
the format strings do not include the microsecond pattern. Add format strings to
the list that include the fractional seconds pattern to handle these common
timestamp formats. This will prevent these timestamps from returning None and
being skipped during incremental polling when a start timestamp is set.
- Around line 73-75: The current code materializes the entire sitemap into a
list via the list comprehension just to check if it is empty, which is
inefficient for large sitemaps. Instead, use short-circuit evaluation with the
any() function to check if at least one URL matches the filter by passing the
generator expression to any() without materializing it, then only build the full
urls list when needed. This way the iteration stops as soon as a matching URL is
found during the validation check, avoiding unnecessary memory and time overhead
from processing the entire sitemap.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d005d4fd-5c14-4e0e-8e0e-eb995dd5c231
📒 Files selected for processing (7)
common/constants.pycommon/data_source/__init__.pycommon/data_source/config.pycommon/data_source/sitemap_connector.pypyproject.tomlrag/svr/sync_data_source.pytest/unit_test/data_source/test_sitemap_connector_unit.py
✅ Files skipped from review due to trivial changes (1)
- common/data_source/init.py
🚧 Files skipped from review as they are similar to previous changes (3)
- pyproject.toml
- common/constants.py
- common/data_source/config.py
…tion Adds a new data source connector that crawls web pages listed in a sitemap.xml and syncs them as Markdown documents into the knowledge base. Features: - Standard urlset and sitemap index (recursive, up to 5 levels) - Incremental polling via <lastmod> timestamps - HTML→Markdown extraction via trafilatura (noise removal, link/table preservation, recall-optimised) - PDF detection via Content-Type: raw PDF bytes are stored and parsed by the existing RAGFlow PDF pipeline - Optional PDF link following from HTML pages with: - parent_url metadata for traceability - configurable domain restriction (default: same domain only) - global deduplication across pages - url_filter regex to restrict which URLs are indexed - SSRF protection via assert_url_is_safe on every fetch - Configurable user_agent and batch_size Closes infiniflow#12328 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
b4bf1bb to
0e5af0c
Compare
|
Regarding the data source, since we don't have enough manpower for testing, and this PR does not use the SDK but instead constructs HTTP requests directly, we will at least require official API documentation or test screenshots before we will consider merging it. |
mkaaad
left a comment
There was a problem hiding this comment.
Could you please resolve the conflicts?
|
If you still want to continue contributing, please reopen this PR after resolving the issue. |
|
@mkaaad @JinHai-CN Thanks for the feedback, and sorry for the silence over the summer. I tried to reopen this PR as suggested, but GitHub refuses ("Could not open the pull request", HTTP 422), so the work continues in #19344, rebased on
On the "no SDK" point: a sitemap is a public XML standard (sitemaps.org protocol), not a vendor API, so there is no SDK to use. The connector does what the merged RSS connector does, a plain HTTP |
Summary
Closes #12328
Adds a
SitemapConnectorthat ingests web pages listed in asitemap.xmlinto a RAGFlow knowledge base, with incremental sync support.urlsetsitemaps andsitemapindexfiles (recursive, up to 5 levels)<lastmod>timestamps — only pages modified since the last sync are re-fetchedContent-Type: application/pdfare stored as raw.pdfblobs and processed by the existing RAGFlow PDF pipelinefollow_pdf_links), with domain restriction and global deduplicationurl_filterregex to restrict which URLs are indexedassert_url_is_safeon every HTTP requestuser_agentandbatch_sizeFiles changed
common/data_source/sitemap_connector.pycommon/constants.pyFileSource.SITEMAP = "sitemap"common/data_source/config.pyDocumentSource.SITEMAP = "sitemap"common/data_source/__init__.pySitemapConnectorrag/svr/sync_data_source.pySitemap(SyncBase)class +func_factoryentrypyproject.tomltrafilatura>=2.0.0dependencytest/unit_test/data_source/test_sitemap_connector_unit.pyTest plan
pytest test/unit_test/data_source/test_sitemap_connector_unit.py)🤖 Generated with Claude Code