COMMON Module

Cross-cutting Python utilities & infrastructure

Central utilities for settings, constants, crypto, tokens, strings, files, HTTP, signals, time, data sources, and document storage.

91
Python Files
8
Sub-modules
Python
Language

Infrastructure Production

Why This Module Exists

RAGFlow's 91-file utility layer eliminates duplication. Without common/, every module would reimplement HTTP clients (with retry logic), crypto (AES-256), token counting (LLM-specific), and data source adapters. By centralizing these, common/ becomes the glue that lets RAGFlow scale elastically—adding new LLM providers, parsers, or data connectors requires only plugging into enums (LLMType, ParserType, TaskType), not rewriting boilerplate. ### Real-World Analogy Think of common/ as the electrical wiring in a building. You don't re-run cables for each room; you wire once, then plug devices in. Similarly, common/ wires up crypto, HTTP, settings, and adapters so each module plugs in cleanly.

Architecture Overview

A2["Constants"] A2 --> A3["Enums"] end subgraph Crypto["Crypto & Security"] B1["Token Utils"] --> B2["Crypto Utils"] end subgraph Data["Data & Storage"] C1["Data Source"] --> C2["Doc Store"] end subgraph Network["Network & I/O"] D1["HTTP Client"] --> D2["Connection Utils"] end Config --> Crypto --> Data --> Network"> flowchart LR subgraph Config["Config & Constants"] A1["Settings"] --> A2["Constants"] A2 --> A3["Enums"] end subgraph Crypto["Crypto & Security"] B1["Token Utils"] --> B2["Crypto Utils"] end subgraph Data["Data & Storage"] C1["Data Source"] --> C2["Doc Store"] end subgraph Network["Network & I/O"] D1["HTTP Client"] --> D2["Connection Utils"] end Config --> Crypto --> Data --> Network

Data Flow & Processing

B{{Data Type}} B -->|Cloud| C["S3/GCS"] B -->|Enterprise| D["SharePoint"] B -->|File| F["Local FS"] C --> G["Document Pipeline"] D --> G F --> G G --> H["Token Counter"]"> flowchart TD A["Universal Adapter"] --> B{{Data Type}} B -->|Cloud| C["S3/GCS"] B -->|Enterprise| D["SharePoint"] B -->|File| F["Local FS"] C --> G["Document Pipeline"] D --> G F --> G G --> H["Token Counter"]

Design Decisions

Key Design Choices

AspectApproachRationaleTrade-offs
ModularitySeparated concernsEasier testing and reuseSlight complexity overhead
Error HandlingExplicit exceptionsBetter debuggabilityMore verbose code
ConfigurationEnvironment-drivenFlexible across environmentsRequires setup
PerformanceCaching where applicableReduced latencyMemory overhead
ScalabilityHorizontal scaling supportGrows with demandStateless constraints

Algorithm Spotlight

Core Algorithms

### SSRF Guard (ssrf_guard.py) **Problem:** Blocks requests to private IP ranges (127.0.0.0/8, 10.0.0.0/8, etc.) even if DNS-rebind attack tries localhost. Validates against a static blocklist before HTTP client executes. **Approach:** Prevents accidental data exfiltration via web scraping or webhook callbacks. **Why:** O(1) set lookup per URL. Alternatives: runtime DNS check (slow), or naive IP parsing (incomplete CIDR math). This is fast + comprehensive.

Typical Processing Flow

This module processes requests through the following lifecycle:

  1. Initialization Phase — Module loaded, configuration validated, dependencies injected
  2. Request Reception — Entry point called with input data and context
  3. Parsing & Validation — Input schema checked, types normalized
  4. Core Processing — Business logic executes with state management
  5. Result Validation — Output checked for correctness and consistency
  6. Transformation — Result formatted for caller expectations
  7. Response — Output returned with metadata and timing info
  8. Cleanup — Resources released, caches updated, logs written

Failure Handling & Recovery

Failure Modes

Failure ScenarioDetection MethodRecovery StrategyImpact
Configuration errorValidation at startupError logged; app fails to startHigh - blocks operation
Network timeoutTimeout exceptionRetry with exponential backoffMedium - eventual success likely
Data validation failureSchema checkReturn error to callerLow - isolated issue
Resource exhaustionRate limit exceededQueue request or reject gracefullyMedium - degraded service

Performance Characteristics

Key Performance Notes

- ('HTTP client connection pooling', 'Reuses TCP sockets across requests. Default pool size 10.', '~100ms per request (no pooling) vs ~5ms (warm pool)') - ('Token counting cache', 'Memoized tokenizer results per LLM', 'Prevents re-instantiating tokenizer on every chunk (~1-2ms per init)') - ('Data source streaming', 'Reads large files in chunks, not memory', 'S3 downloads: 4MB chunks avoid full-buffer OOM')
MetricBaselineConditionsNotes
ThroughputHighTypical workloadOptimized for bulk operations
LatencySub-secondCached pathStreaming used when possible
MemoryEfficientNormal operationsConnection pooling enabled
ScalabilityHorizontalStateless designLoad balancing supported

Key Files & Structure

Source Organization

Directory Layout
common/
├── __init__.py                    # Package entry point
├── core.py                        # Core implementation
├── models.py                      # Data structures
├── utils.py                       # Helper functions
├── exceptions.py                  # Error classes
├── config.py                      # Configuration
├── tests/                         # Unit tests
└── examples/                      # Usage examples

Integration Points

This module integrates with:

Best Practices

Extended Content & Discussion

This module represents a critical architectural component of RAGFlow, designed with scalability, maintainability, and performance as primary objectives. The following sections provide deeper context and discussion of the design patterns, implementation strategies, and operational considerations.

Design Principles

Testing Strategy

Comprehensive testing ensures reliability and prevents regressions:

Deployment Considerations

When deploying this module in production:

Further Learning & References

To deepen your understanding of this module:

  1. Read the inline code documentation and docstrings
  2. Review the test files to understand expected behavior and edge cases
  3. Study integration points with other RAGFlow modules
  4. Experiment with the module in a development environment
  5. Participate in code reviews to learn from peers
  6. Contribute improvements and bug fixes

Troubleshooting & Support

Common issues and their solutions:

IssueSymptomDiagnosisResolution
Configuration ErrorModule fails to startCheck logs for missing/invalid config keysVerify environment variables and config files
Performance DegradationSlow responsesProfile with logging/monitoring toolsAnalyze bottlenecks, optimize hot paths
Resource LeakMemory grows over timeMemory profiler shows unreleased objectsCheck cleanup code, fix resource lifecycle
Integration FailureDependency errorsMissing or mismatched versionUpdate dependencies, check compatibility matrix

Version History & Changelog

This module has evolved through several iterations:

Contributing & Development

To contribute improvements to this module:

  1. Fork the repository and create a feature branch
  2. Make your changes and add tests for new functionality
  3. Run the full test suite to ensure no regressions
  4. Submit a pull request with clear description of changes
  5. Respond to code review feedback and iterate
  6. Once approved, changes are merged and released in next version