Metadata-Version: 2.4
Name: jc-etlforge
Version: 0.7.1
Summary: A minimalist, plugin-driven ETL framework with declarative pipelines, concurrency, and CLI support.
Author-email: Jacivaldo Carvalho <jacivaldocarvalho@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/jacivaldocarvalho/jc-etlforge
Project-URL: Repository, https://github.com/jacivaldocarvalho/jc-etlforge
Project-URL: Issues, https://github.com/jacivaldocarvalho/jc-etlforge/issues
Project-URL: Changelog, https://github.com/jacivaldocarvalho/jc-etlforge/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/jacivaldocarvalho/jc-etlforge/tree/main/docs
Keywords: etl,pipeline,data-engineering,framework,plugins,cli
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.1
Requires-Dist: pyyaml>=6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Requires-Dist: pre-commit>=3.7; extra == "dev"
Dynamic: license-file

# JC Etlforge

[![CI](https://github.com/jacivaldocarvalho/jc-etlforge/actions/workflows/ci.yml/badge.svg)](https://github.com/jacivaldocarvalho/jc-etlforge/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/jc-etlforge.svg)](https://pypi.org/project/jc-etlforge/)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)


A **minimalist, plugin-driven ETL framework** for Python with declarative
pipelines, concurrency, and a first-class CLI.

```bash
pip install jc-etlforge
jc-etlforge run pipeline.yaml
```

`jc-etlforge` is the **pytest of ETL**: small, composable, extensible, and
installable from PyPI. It does not try to be Airflow — it tries to replace
the ad-hoc Python script that copies data from one place to another.

---

## Table of contents

- [JC Etlforge](#jc-etlforge)
  - [Table of contents](#table-of-contents)
  - [Why jc-etlforge](#why-jc-etlforge)
  - [Install](#install)
  - [Quickstart](#quickstart)
  - [How it works](#how-it-works)
    - [Layers](#layers)
    - [Data flow](#data-flow)
    - [Execution model](#execution-model)
  - [Built-in components](#built-in-components)
    - [Sources](#sources)
    - [Transformers](#transformers)
    - [Sinks](#sinks)
  - [Pipeline config](#pipeline-config)
    - [Format conversion is just a config choice](#format-conversion-is-just-a-config-choice)
  - [CLI reference](#cli-reference)
    - [Exit codes](#exit-codes)
  - [Plugins](#plugins)
  - [Where to use it](#where-to-use-it)
    - [Legacy data migration](#legacy-data-migration)
    - [SaaS integration](#saas-integration)
    - [CI/CD data pipelines](#cicd-data-pipelines)
    - [Spreadsheet cleanup](#spreadsheet-cleanup)
    - [Plugin ecosystem](#plugin-ecosystem)
  - [Design decisions](#design-decisions)
  - [Development](#development)
  - [Roadmap](#roadmap)
  - [License](#license)
  - [Author](#author)

---

## Why jc-etlforge

Most ETL tools are either **too heavy** (full platforms with scheduler,
UI, and database) or **too ad-hoc** (one-off scripts that each reimplement
parsing, retry, logging, and tests).

`jc-etlforge` sits in the sweet spot: a **small, declarative framework**
built around four primitives:

- **Source** — where data comes from (JSON, CSV, positional files, …).
- **Transformer** — how data is reshaped (regex, rename, filter, …).
- **Sink** — where data goes (JSON, CSV, positional files, …).
- **Pipeline** — a chain that wires sources, transformers, and sinks.

Pipelines are declared in **YAML or JSON**, executed by pluggable engines
(**threaded** or **multiprocessing**), and extended through **entry-point
plugins** — no forks required.

---

## Install

Requires **Python 3.10+**.

```bash
pip install jc-etlforge
```

Verify:

```bash
jc-etlforge --version
jc-etlforge info
```

For development, see [Development](#development).

---

## Quickstart

Create `data/in.json`:

```json
[
  {"id": 1, "name": "Alice", "email": "alice@example.com"},
  {"id": 2, "name": "Bob",   "email": "bob@example.com"},
  {"id": 3, "name": "Carol", "email": "carol@example.com"}
]
```

Create `pipeline.yaml`:

```yaml
name: quickstart
source:
  type: JsonSource
  path: data/in.json
transformers:
  - type: RegexTransformer
    field: email
    pattern: "@example\\.com$"
    replacement: "@example.org"
sink:
  type: CsvSink
  path: output/out.csv
  fields: [id, name, email]
```

Validate and run:

```bash
jc-etlforge validate pipeline.yaml
jc-etlforge run pipeline.yaml
```

Output:

```
INFO jc_etlforge: pipeline quickstart starting (executor=thread, workers=1, retries=1)
INFO jc_etlforge: pipeline quickstart finished in 0.001s: {'rows.read': 3, 'rows.written': 3, 'rows.transformed': 3}
pipeline 'quickstart' finished in 0.001s
  rows.read: 3
  rows.transformed: 3
  rows.written: 3
```

`output/out.csv`:

```csv
id,name,email
1,Alice,alice@example.org
2,Bob,bob@example.org
3,Carol,carol@example.org
```

That's it. No Python code, no `if __name__ == "__main__"`, no retry
boilerplate.

![Demo](docs/demo/demo.gif)

---

## How it works

### Layers

```mermaid
flowchart TB
    subgraph CLI["CLI"]
        info["info"]
        validate["validate"]
        run["run"]
        plugins["plugins list"]
    end

    subgraph Config["Config"]
        load["load_config\n(YAML/JSON → dict)"]
        from_config["Pipeline.from_config\n(dict → Pipeline)"]
    end

    subgraph Core["Core"]
        pipeline["Pipeline\n(Source → Transformer… → Sink)"]
        context["PipelineContext\n(logger, metrics, config)"]
        executor["Executor\n(thread | process | sequential)"]
        retry["with_retry\n(exponential backoff)"]
    end

    subgraph Components["Built-in components"]
        sources["Sources: JsonSource,\nCsvSource, PositionalFileSource"]
        transformers["Transformers: RegexTransformer,\nRenameTransformer, FilterTransformer"]
        sinks["Sinks: JsonSink,\nCsvSink, PositionalFileSink"]
    end

    subgraph Plugins["Plugins (entry points)"]
        third_party["jc_etlforge.transformers\n(third-party packages)"]
    end

    info --> Core
    validate --> Config
    run --> Config
    plugins --> Plugins
    load --> from_config
    from_config --> pipeline
    pipeline --> context
    pipeline --> executor
    executor --> retry
    pipeline --> sources
    pipeline --> transformers
    pipeline --> sinks
    from_config -.->|resolve type| Components
    from_config -.->|resolve type| Plugins
```

The **CLI** is a thin shell: it parses arguments, loads config, and
delegates to the core. The **core** is engine-agnostic: it wires a
`Source`, zero or more `Transformer`s, and a `Sink`, and lets an
`Executor` decide how to fan out `process` calls.

### Data flow

A pipeline is a **lazy stream** of `dict[str, Any]` records. Nothing is
read until the sink pulls; each transformer yields records one at a time.
Memory usage is bounded by the largest single record, not by the input
size.

```mermaid
sequenceDiagram
    participant CLI
    participant Pipeline
    participant Source
    participant Transformer
    participant Sink
    participant Context

    CLI->>Pipeline: from_config(dict)
    CLI->>Context: __enter__()
    CLI->>Pipeline: run(ctx, executor, workers, retries)
    Pipeline->>Source: read(ctx)
    loop for each record
        Source-->>Pipeline: record
        Pipeline->>Transformer: process(record, ctx)
        Transformer-->>Pipeline: transformed | None | list
        Pipeline->>Context: record("rows.transformed")
    end
    Pipeline->>Sink: write(record, ctx)
    Sink-->>Pipeline: None
    Pipeline->>Context: record("rows.written")
    CLI->>Context: __exit__()
    CLI-->>CLI: print metrics
```

### Execution model

`Pipeline.run` accepts three knobs:

| Knob | Default | Effect |
|------|---------|--------|
| `executor` | `"thread"` | `"thread"` uses `ThreadPoolExecutor`; `"process"` uses `ProcessPoolExecutor`. |
| `max_workers` | `1` | `1` runs sequentially (no pool overhead); `>1` fans out `transformer.process` across workers. |
| `retries` | `1` | Total attempts per record when `process` raises. `1` means "no retry". |

```bash
# Sequential (default)
jc-etlforge run pipeline.yaml

# 4 threads (I/O-bound transformers)
jc-etlforge run pipeline.yaml --workers 4

# 4 processes (CPU-bound transformers)
jc-etlforge run pipeline.yaml --executor process --workers 4

# Retry up to 3 times with 0.5s base backoff
jc-etlforge run pipeline.yaml --retries 3 --retry-backoff 0.5
```

Metrics (`rows.read`, `rows.transformed`, `rows.written`, `rows.filtered`,
`rows.failed`) are counted in the **parent** process, so they are accurate
even with `--executor process`.

---

## Built-in components

### Sources

| Class | Reads | Args |
|-------|-------|------|
| `JsonSource` | JSON array or wrapped object | `path`, `records_key`, `encoding` |
| `CsvSource` | CSV with header | `path`, `delimiter`, `encoding` |
| `PositionalFileSource` | Fixed-width text | `path`, `layout`, `encoding`, `skip_blank_lines` |

### Transformers

| Class | Does | Args |
|-------|------|------|
| `RegexTransformer` | Regex substitution on one or more fields | `field`, `pattern`, `replacement`, `flags`, `missing` |
| `RenameTransformer` | Rename fields via mapping | `mapping` |
| `FilterTransformer` | Keep records matching a predicate | `field`, `op` (`eq`/`ne`/`in`/`not_in`/`regex`/`not_regex`), `value` |

### Sinks

| Class | Writes | Args |
|-------|--------|------|
| `JsonSink` | JSON array (pretty-printed) | `path`, `encoding` |
| `CsvSink` | CSV with header | `path`, `fields`, `delimiter`, `encoding` |
| `PositionalFileSink` | Fixed-width text | `path`, `layout`, `encoding` |

`PositionalFileSink` accepts a `layout` of either plain `(start, end)`
tuples (space-padded, left-aligned) or `FieldSpec(start, end, align, fill)`
for zero-padding and right-alignment:

```yaml
layout:
  id:   {start: 0, end: 5, align: right, fill: "0"}   # → "00001"
  name: {start: 5, end: 15, align: left, fill: " "}   # → "Alice     "
```

---

## Pipeline config

A pipeline is a YAML or JSON file with **`source`**, optional
**`transformers`**, and **`sink`**. Each is a mapping with a `type` key
(resolved against built-in components, then plugins) and constructor
kwargs.

```yaml
name: my-pipeline          # optional, defaults to "pipeline"
source:
  type: JsonSource
  path: data/in.json
transformers:
  - type: FilterTransformer
    field: status
    op: eq
    value: active
  - type: RenameTransformer
    mapping:
      full_name: name
sink:
  type: CsvSink
  path: output/out.csv
  fields: [id, name, email]
```

`jc-etlforge validate pipeline.yaml` parses and validates the config
**without executing** — useful in CI to catch bad configs before they run.

### Format conversion is just a config choice

Because every component speaks `dict[str, Any]`, any combination works:

| From → To | Source | Transformers | Sink |
|-----------|--------|--------------|------|
| JSON → CSV | `JsonSource` | (optional) | `CsvSink` |
| CSV → JSON | `CsvSource` | (optional) | `JsonSink` |
| CSV → CSV (clean) | `CsvSource` | `Filter`/`Rename`/`Regex` | `CsvSink` |
| JSON → JSON (clean) | `JsonSource` | `Filter`/`Rename`/`Regex` | `JsonSink` |
| Positional → CSV | `PositionalFileSource` | (optional) | `CsvSink` |
| CSV → Positional | `CsvSource` | (optional) | `PositionalFileSink` |

> **Note on types:** `CsvSource` reads every value as a string (that is
> what `csv.DictReader` does). If you need `id` as an integer in the
> output JSON, add a `CastTransformer` (see
> [`examples/plugins/`](examples/plugins/)).

---

## CLI reference

```
jc-etlforge [OPTIONS] COMMAND [ARGS]...

Commands:
  info           Print version and environment info.
  run            Execute a pipeline from a YAML/JSON config.
  validate       Validate a config without executing it.
  plugins list   List transformers discovered via entry points.
```

### Exit codes

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Unmapped exception (bug — please report) |
| 2 | CLI usage error (reserved by `click`) |
| 3 | `ConfigurationError` — bad config file or unknown component |
| 4 | `PipelineError` / `ExecutionError` — pipeline failed |
| 5 | `PluginError` — plugin failed to load or validate |

Scripts can branch on these:

```bash
jc-etlforge run pipeline.yaml
case $? in
  0) echo "ok" ;;
  3) echo "fix your config" >&2; exit 1 ;;
  4) echo "pipeline failed" >&2; exit 2 ;;
  *) echo "unexpected: $?" >&2; exit 3 ;;
esac
```

---

## Plugins

Third parties extend `jc-etlforge` by publishing a package that declares
an entry point under `jc_etlforge.transformers`:

```toml
[project.entry-points."jc_etlforge.transformers"]
titlecase = "my_pkg:TitleCaseTransformer"
```

After `pip install my-pkg`, the transformer is available by name in any
pipeline config:

```yaml
transformers:
  - type: titlecase
    field: name
```

List discovered plugins:

```bash
jc-etlforge plugins list
```

See [`examples/plugins/`](examples/plugins/) for a full working example
(`TitleCaseTransformer` and `CastTransformer`).

---

## Where to use it

### Legacy data migration

```mermaid
flowchart LR
    mainframe["Mainframe\n(EBCDIC, fixed-width)"] --> src["PositionalFileSource"]
    src --> regex["RegexTransformer\n(trim padding)"]
    regex --> sink["JsonSink / CsvSink"]
    sink --> cloud["Cloud warehouse"]
```

A 30-year-old Cobol export becomes a versioned `pipeline.yaml` per layout,
testable with `jc-etlforge validate` in CI.

### SaaS integration

```mermaid
flowchart LR
    stripe["Stripe API"] --> p1["Plugin: StripeSource"]
    zendesk["Zendesk API"] --> p2["Plugin: ZendeskSource"]
    p1 --> merge["Merge / filter"]
    p2 --> merge
    merge --> sink["CsvSink / JsonSink"]
    sink --> bi["BI dashboard"]
```

Two 30-line plugins + one YAML file. Runs on a $5/month VPS on a cron.

### CI/CD data pipelines

```mermaid
flowchart LR
    cron["GitHub Actions\n(scheduled)"] --> validate["jc-etlforge validate"]
    validate -->|valid| run["jc-etlforge run"]
    validate -->|invalid| fail["fail the build"]
    run --> s3["S3 (CSV)"] --> filter["FilterTransformer"] --> pg["Postgres"]
```

`validate` in CI catches broken configs **before** the cron runs;
`--executor process` uses all cores of the runner.

### Spreadsheet cleanup

```mermaid
flowchart LR
    xlsx["clientes.xlsx\n(exported CSV)"] --> src["CsvSource"]
    src --> filter["FilterTransformer\n(valid CPF)"]
    filter --> rename["RenameTransformer\n(standard columns)"]
    rename --> regex["RegexTransformer\n(strip phone)"]
    regex --> sink["CsvSink"]
    sink --> clean["clientes_limpos.csv"]
```

The monthly spreadsheet cleanup becomes a reusable YAML file, run in
seconds instead of hours.

### Plugin ecosystem

```mermaid
flowchart TB
    core["jc-etlforge (core)"]
    core --> salesforce["jc-etlforge-salesforce"]
    core --> snowflake["jc-etlforge-snowflake"]
    core --> kafka["jc-etlforge-kafka"]
    core --> excel["jc-etlforge-excel"]
```

The same model that made `pytest` and `mkdocs` ecosystems: a small core
plus many focused extensions.

---

## Design decisions

Architectural decisions are recorded as
[ADRs](docs/adr/README.md):

| ID | Decision |
|----|----------|
| [0001](docs/adr/0001-use-modern-typing-and-python-310.md) | Use modern typing and Python 3.10+ |
| [0002](docs/adr/0002-pipeline-context-and-metrics.md) | PipelineContext and metrics |
| [0003](docs/adr/0003-executor-abstraction-and-pickling.md) | Executor abstraction and pickling |
| [0004](docs/adr/0004-plugin-system-via-entry-points.md) | Plugin system via entry points |
| [0005](docs/adr/0005-config-format-and-exit-codes.md) | Config format and exit codes |

See [`docs/architecture.md`](docs/architecture.md) for the full layered
architecture and data flow.

---

## Development

```bash
git clone https://github.com/jacivaldocarvalho/jc-etlforge.git
cd jc-etlforge
python -m venv .venv
source .venv/bin/activate
make install    # editable install with dev extras
make check      # ruff + pytest (what CI runs)
make build      # sdist + wheel + twine check
```

See the [`Makefile`](Makefile) for the full task list (`make help`).

---

## Roadmap

| Version | Status | Highlights |
|---------|--------|------------|
| 0.1–0.6 | ✅ | Core, components, executors, plugins, CLI |
| 0.7 | 🚧 | Docs, ADRs, `examples/plugins/`, PyPI release |
| 1.0 | 📋 | API freeze, `CastTransformer` built-in, async executor |
| 1.x | 📋 | DAG pipelines, aggregate transformers, DB/API sources |

Roadmap items are not commitments — they are directions. See
[issues](https://github.com/jacivaldocarvalho/jc-etlforge/issues) for
the live list.

---

## License

MIT — see [LICENSE](LICENSE).

---

## Author

**Jacivaldo Carvalho**

Telecommunications Engineer | DevOps Engineer | SRE | Networking

[GitHub](https://github.com/jacivaldocarvalho) | [LinkedIn](https://www.linkedin.com/in/jacivaldocarvalho) | [Website](https://www.jacivaldocarvalho.com/)
