Sources¶
base
¶
Abstract base class for source readers.
BaseSourceReader[DF] uses the Template Method pattern:
- Public :meth:
readhandles timing, watermark filtering, count/max calculation, file-info columns, and error wrapping. - Subclasses implement :meth:
_read_internal(and optionally :meth:_read_data) with format-specific logic.
The reader delegates all DataFrame operations to a :class:BaseEngine.
BaseSourceReader
¶
BaseSourceReader(engine: BaseEngine[DF])
Bases: ABC, Generic[DF]
Abstract source reader with Template Method lifecycle.
Subclasses must implement :meth:_read_internal. Optionally they
may also implement :meth:_read_data for the raw read step.
Type parameter DF is the concrete DataFrame class.
merge_watermark
¶
merge_watermark(
existing: Optional[Dict[str, Any]],
candidate: Optional[WatermarkCandidate],
) -> Dict[str, Any]
Merge a source observation using this reader's semantics.
Watermark column membership only controls which source observations may
be persisted. It does not grant ordering semantics: unclassified
values, including cursor-like strings, remain opaque and replace their
own key. Built-in readers may override
:meth:_watermark_ordering_kinds for source-specific typed fields.
read
¶
read(
source: Source, *, request: SourceReadRequest
) -> SourceReadResult[DF]
Read data and return the sole typed source contract.
validate_watermark
¶
Reject binary bounds until a backend has qualified ordering.
The JSON codec can preserve bytes, but comparison semantics belong to the source/engine boundary. A reader that has a qualified native ordering may override this protected hook; built-in readers fail before a query or destination mutation is started.
contracts
¶
Source-owned value contracts.
The contracts in this module are deliberately independent of any engine implementation. A reader owns the resolved selection and candidate returned for one invocation; runtime is a detached projection of that same evidence.
SourceReadMode
¶
Bases: str, Enum
Finite source selection modes.
SourceReadUpperOrigin
¶
Bases: str, Enum
Whether a selection ceiling was authored or generated by the source.
SourceReadRange
dataclass
¶
SourceReadRange(
column: str,
start: Any,
end: Any,
lower_operator: str = ">=",
upper_operator: str = "<",
)
Exact source-owned range for one bounded read.
SourceReadRequest
dataclass
¶
SourceReadRequest(
reference_time: datetime,
watermark_start: dict[str, Any] | None = None,
watermark_end: dict[str, Any] | None = None,
watermark_start_operator: str | None = None,
watermark_end_operator: str | None = None,
read_range: SourceReadRange | None = None,
)
Caller-owned input for exactly one source read.
SourceReadSelection
dataclass
¶
SourceReadSelection(
mode: SourceReadMode = FULL,
lower: dict[str, Any] | None = None,
upper: dict[str, Any] | None = None,
lower_operator: str = ">",
upper_operator: str = "<",
combine_operator: str = "OR",
upper_origin: SourceReadUpperOrigin = NONE,
)
Source-resolved predicate used by one read.
SourceReadResult
dataclass
¶
SourceReadResult(
frame: DF | None,
rows_read: int,
selection: SourceReadSelection,
candidate: WatermarkCandidate | None = None,
runtime: SourceRuntimeInfo | None = None,
)
Bases: Generic[DF]
Frame and source-owned control evidence produced together.
runtime
¶
Runtime projection for one source read.
SourceRuntimeInfo
dataclass
¶
SourceRuntimeInfo(
start_time: datetime = utc_now(),
end_time: Optional[datetime] = None,
status: str = PENDING.value,
message: Optional[str] = None,
rows_read: int | None = None,
source_action: dict[str, Any] = dict(),
selection: SourceReadSelection | None = None,
)
Bases: RuntimeInfo
Detached source-phase observation.
file_reader
¶
File-based source reader (Parquet, CSV, JSON, Avro, etc.).
Reads flat files from storage, supporting date-folder partitioning patterns and optional platform-based folder discovery.
FileReader
¶
FileReader(engine: BaseEngine[DF])
Bases: BaseSourceReader[DF]
Source reader for flat files (Parquet, CSV, JSON, Avro, etc.).
Supports:
* Single path and multi-path reads.
* Date-folder partition patterns ({year}/{month}/{day}...).
* Watermark-based incremental reads with folder pruning.
* File-info column injection (__file_name, etc.).
delta_reader
¶
Delta Lake source reader.
Reads Delta tables via :meth:engine.read_delta with support for
watermark-based incremental reads and SQL queries.
DeltaReader
¶
DeltaReader(engine: BaseEngine[DF])
Bases: BaseSourceReader[DF]
Source reader for Delta Lake tables.
Supports:
* Full and incremental reads (watermark filtering).
* SQL query mode (source.query).
iceberg_reader
¶
Iceberg source reader.
Reads Iceberg tables via SQL (SELECT * FROM table_name) using
the catalog-aware fully qualified table name. Falls back to path-based
reads when no catalog is configured.
IcebergReader
¶
IcebergReader(engine: BaseEngine[DF])
Bases: BaseSourceReader[DF]
Source reader for Apache Iceberg tables.
Prefers SQL-based reads via full_table_name (catalog-aware).
Falls back to path-based reads when no catalog is configured.
database_reader
¶
Database source reader.
Reads data from relational databases via :meth:engine.read_database,
supporting both table and query modes.
DatabaseReader
¶
DatabaseReader(engine: BaseEngine[DF])
Bases: BaseSourceReader[DF]
Source reader for relational databases.
Uses :meth:engine.read_database which delegates to the
engine-specific external database reader (JDBC in Spark,
connectorx/ADBC in Polars, etc.).
Supports: * Table mode — read entire table (or schema.table). * Query mode — arbitrary SQL query executed on the source database. * Watermark-based incremental reads pushed down to SQL.
api_reader
¶
Public API source reader facade.
The reader owns source configuration, DataFrame conversion, and runtime state.
HTTP/auth/pagination/watermark/record helpers live in the private _api
package so the public component remains easy to discover.
APIReader
¶
APIReader(engine: BaseEngine[DF])
Bases: BaseSourceReader[DF]
Source reader for HTTP/REST APIs.
Fetches JSON data from paginated REST endpoints, converts the collected records to a DataFrame via the engine, and supports incremental reads through watermark filtering.
API configuration is supplied through source.connection.configure
and source.configure:
Connection-level (source.connection.configure):
- base_url (str): Base URL for the API (required).
- auth_type (str): "bearer", "basic", "api_key", or
"oauth2_client_credentials".
- auth_token (str): Bearer token value (for auth_type="bearer").
- username / password (str): Basic auth credentials.
- api_key_header (str): Header name for API key auth.
- api_key_value (str): API key value.
- token_url (str): OAuth2 token endpoint (for oauth2_client_credentials).
- client_id (str): OAuth2 client ID.
- client_secret (str): OAuth2 client secret — use secrets_ref so
it is resolved from a secret store at runtime rather than stored in plain text.
- scope (str): Optional space-separated OAuth2 scopes.
- token_auth_method (str): How to send client credentials to the token
endpoint. "client_secret_post" (default) puts client_id and
client_secret in the POST body. "client_secret_basic" sends them
as HTTP Basic Auth (required by Okta, Ping Identity, and some others).
- token_request_body_format (str): "form" (default,
application/x-www-form-urlencoded) or "json"
(application/json) — some providers (e.g. GitHub Apps) expect JSON.
- token_request_extras (dict): Extra fields forwarded to the token POST body.
- watermark_to_param_timezone (str, optional): Default timezone for
generated request-end bounds and for advancing request-end watermarks.
Can be overridden per source via the source-level key of the same name
(source wins).
Accepts IANA names or UTC offset strings; defaults to "UTC".
auth_type="aws_sigv4" (API Gateway IAM auth, direct AWS service endpoints):
Signs every request with AWS Signature Version 4 via botocore.
When aws_access_key_id is omitted, the standard boto3 credential chain
is used (env vars, ~/.aws/credentials, EC2/ECS instance role, etc.).
- aws_region (str): AWS region, e.g. "us-east-1".
- aws_service (str): AWS service name (default "execute-api" for
API Gateway). Use "s3", "lambda", etc. for other endpoints.
- aws_access_key_id (str, optional): Override access key — use
secrets_ref rather than hard-coding.
- aws_secret_access_key (str, optional): Override secret — use
secrets_ref.
- aws_session_token (str, optional): Temporary session token for
role-assumed or STS credentials.
- default_headers (dict): Headers applied to every request.
- timeout (int/float): Request timeout in seconds (default 30).
Source-level (source.configure):
- endpoint (str): API endpoint path appended to base_url.
- method (str): HTTP method (default "GET").
- params (dict): Query parameters.
- body (dict): Request body (for POST/PUT).
- pagination_type (str): "offset", "cursor",
or "next_link".
- page_size (int): Number of records per page (default 100).
- max_pages (int): Safety limit on pages fetched (default 1000).
- data_path (str): Dot-separated path to records array in response
JSON (e.g. "data.items"). Defaults to root-level list.
- next_link_path (str): Dot-separated path to the next-page URL.
- cursor_path (str): Dot-separated path to the cursor token.
- cursor_param (str): Query param name for cursor (default "cursor").
- offset_param (str): Query param for offset (default "offset").
- limit_param (str): Query param for page size (default "limit").
- rate_limit_delay (float): Seconds to wait between requests (default 0).
- max_retries (int): Maximum number of retries on HTTP 429 rate-limit
responses (default 10). When the Retry-After response header is
present its value is used as the wait duration; otherwise exponential backoff
applies: min(2 ** attempt, 30) seconds per retry
(1 s, 2 s, 4 s, 8 s, 16 s, 30 s, 30 s, …), capped at 30 s.
Raises :class:~datacoolie.core.exceptions.SourceError once all
retries are exhausted.
- total_path (str, optional): Dot-separated path to the total record count
in the first-page response JSON (e.g. "meta.total" or
"pagination.count"). Only applies when pagination_type="offset".
When set, the reader fetches page 0 to discover the total, calculates the
number of remaining pages, and dispatches them concurrently via
:class:~concurrent.futures.ThreadPoolExecutor. Without this key,
offset pagination falls back to sequential page-by-page fetching (stopping
when a page returns fewer records than page_size).
- offset_max_workers (int): Maximum number of parallel workers used when
total_path is configured for concurrent offset fetching (default 4).
Has no effect when total_path is absent.
Canonical watermark and bounded range push-down
(source.configure.range_param_mapping):
Each mapped field declares separate lower and upper endpoint
parameters, their operators and locations, wire format, response
column, and watermark meaning ("observed_max" or
"request_end"). Lower and upper bindings may use the shorthand
parameter names or the explicit {"name": ..., "location": ...,
"operator": ...} form. Supported formats include "iso",
"date", "timestamp", "timestamp_ms", "datetime",
"datetime_ms", "integer", and "number".
A bounded replay requires both lower and upper bindings and uses
the exact authored operators. Replay may select a mapped field
even when it is not listed in ``source.watermark_columns``; the
mapping controls selection while only authored watermark columns
are eligible for persisted state. Ordinary unmapped watermark
columns continue to use response-side filtering.
``watermark_to_param_timezone`` (str, optional) selects the timezone
used for generated request-end bounds and date/datetime alignment.
It accepts IANA names or UTC offset strings and defaults to ``UTC``.
Range-split / parallel fetch (source.configure):
Splits a large watermark window into equal-sized intervals and calls
the API concurrently for each sub-range. Requires one canonical
range mapping with lower and upper bindings.
- ``watermark_range_interval_unit`` (str): Interval unit for each sub-range
— ``"hour"``, ``"day"``, ``"month"``, or ``"year"``. When set, range
splitting is enabled; otherwise a single API call is made (default).
- ``watermark_range_interval_amount`` (int): Number of units per interval
(default ``1``). E.g. ``unit="hour", amount=3`` → 3-hour windows.
- ``watermark_range_start`` (str): ISO-8601 datetime used as the initial
lower bound when no stored watermark exists yet (first run). Required
when ``watermark_range_interval_unit`` is set and no watermark has been
saved.
- ``watermark_range_max_workers`` (int): Maximum parallel HTTP workers
(default ``4``).
Each split request receives the exact contiguous interval boundary.
validate_watermark
¶
Validate canonical ISO precision before look-back parsing.
BaseSourceReader applies date_backward before the API binding
compiler sees a stored lower bound. Validate the caller-owned string
first so datetime.fromisoformat cannot silently discard digits.
The check applies to every canonical range binding before the base
reader can coerce a stored ISO value and discard fractional digits.
validate_api_bounded_range
¶
validate_api_bounded_range(
source: Source, column: str
) -> None
Validate the API-owned mapping needed for an exact bounded read.
The selected field can be a selection-only field; it does not need to be
listed in source.watermark_columns. Persisted state remains limited to
the authored watermark columns in the reader's runtime path.
python_function_reader
¶
Python function source reader.
Reads data by importing and calling a user-defined Python function that
returns a DataFrame. This is intended for complex source logic that
cannot be expressed as a simple source.query.
The function path is specified on :attr:Source.python_function as a
dotted module path, e.g. "mypackage.loaders.load_orders".
Two-phase watermark filtering:
- Before — the previous watermark dict is passed to the function so it can apply efficient source-side filtering (e.g. a WHERE clause).
- After — the framework applies :meth:
_apply_watermark_filteron the returned DataFrame for precise, engine-level filtering — identical to what other readers do.
The function signature must be::
def my_loader(engine, source, watermark_start, watermark_end) -> DataFrame | None
engine— the active :class:BaseEngineinstance.source— the :class:Sourcemodel.watermark_start— previous watermark values (Noneon first run).watermark_end— replay ceiling watermark (Nonefor normal incremental reads).
PythonFunctionReader
¶
PythonFunctionReader(
engine: BaseEngine[DF],
allowed_prefixes: Optional[List[str]] = None,
)
Bases: BaseSourceReader[DF]
Source reader that delegates to a user-defined Python function.
The function path is read from source.python_function and must
be a fully-qualified dotted path (e.g. "my_module.load_data").
The function signature must be::
def my_loader(engine, source, watermark_start, watermark_end) -> DataFrame | None
Watermark handling follows a before / after pattern:
- The
watermark_startandwatermark_enddicts are passed to the function so it can pre-filter at the source (optional — the function may ignore them). - After the function returns, the framework applies
:meth:
_apply_watermark_filterfor precise row-level filtering, consistent with other readers.
Source reader extension hooks¶
Custom source readers implement the selected protected hooks below. The base reader owns request validation, range and watermark filtering, timing, result construction, and error wrapping; subclasses provide the source read operation and may opt into exact range support or typed watermark ordering.
The sole public read entry is
read(source, *, request: SourceReadRequest) -> SourceReadResult[DF]. The
request carries the caller's original bounds, optional SourceReadRange, and
required reference_time. The result carries .frame, .rows_read, the
resolved .selection, an optional typed .candidate, and an optional detached
.runtime projection. Orchestration uses the result for selection, replacement,
and the source-empty gate; runtime observations never become control input.
The ETL orchestration boundary requires callable read, validate_watermark,
and merge_watermark methods. Registered readers inherit these from
BaseSourceReader; structurally injected readers may implement the same
contract without inheriting the ABC. Capability and request validation fail
before source I/O. Source runtime evidence is returned with the read result or
attached to a source error; there is no separate source runtime accessor.
Keep _read_internal(source, request) as the normal extension seam. The base
template calls it once and constructs the typed result. If a custom reader
replaces the public read() template, it must preserve the same request/result
contract and return a SourceReadResult.
_supports_read_range
¶
Whether this reader implements the source-owned range contract.
_watermark_ordering_kinds
¶
Return source-authorized ordering kinds for typed observations.
The base/custom reader contract is opaque by default. Built-in readers
that know their row maxima are ordered may opt in through
:meth:_typed_row_watermark_ordering_kinds; membership in
source.watermark_columns alone is not enough.
_read_internal
abstractmethod
¶
_read_internal(
source: Source, request: SourceReadRequest
) -> Optional[DF]
Read data from the source (subclass implementation).
This is the core reading logic. The base class handles timing, error wrapping, and runtime-info population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Source
|
Pipeline source configuration. |
required |
request
|
SourceReadRequest
|
The complete caller-owned read request. |
required |
Returns:
| Type | Description |
|---|---|
Optional[DF]
|
DataFrame or |