Metadata-Version: 2.5
Name: c5tools
Version: 0.9.0a1
Summary: Validator for COUNTER R5.0 and R5.1 reports and COUNTER API responses
Project-URL: Homepage, https://github.com/Big-Dig-Data/c5tools
Project-URL: Documentation, https://github.com/Big-Dig-Data/c5tools/blob/python/python/docs/guide.md
Project-URL: Source, https://github.com/Big-Dig-Data/c5tools/tree/python/python
Project-URL: Issues, https://github.com/Big-Dig-Data/c5tools/issues
Author-email: Bernd Oberknapp <bo@ub.uni-freiburg.de>
Maintainer-email: Beda Kosata <beda@bigdigdata.com>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: COUNTER,COUNTER API,COUNTER Metrics,SUSHI,usage statistics,validation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: httpx>=0.28
Requires-Dist: xlrd>=2.0.2
Provides-Extra: server
Requires-Dist: starlette>=1.10.0; extra == 'server'
Requires-Dist: uvicorn>=0.54.0; extra == 'server'
Description-Content-Type: text/markdown

# c5tools (Python)

Python port of the c5tools, a validator for COUNTER R5.0 and R5.1 reports and COUNTER API responses. The port is
work in progress, see [`docs/REWRITE_PLAN.md`](https://github.com/Big-Dig-Data/c5tools/blob/python/docs/REWRITE_PLAN.md). The PHP implementation in the repository
root is the specification: the Python implementation must produce the same snapshots for the test corpus in
[`tests/corpus`](https://github.com/Big-Dig-Data/c5tools/tree/python/tests/corpus) as recorded in [`tests/expected`](https://github.com/Big-Dig-Data/c5tools/tree/python/tests/expected) (see
[`tests/README.md`](https://github.com/Big-Dig-Data/c5tools/blob/python/tests/README.md)).

## Installation

The package is published on [PyPI](https://pypi.org/project/c5tools/) as `c5tools` (pre-releases until the switch
from the PHP implementation, so pin the version or allow pre-releases):

```console
pip install c5tools==0.9.0a1            # or: pip install --pre c5tools
poetry add c5tools@0.9.0a1              # Poetry
pip install "c5tools[server]==0.9.0a1"  # with the REST service
```

It needs Python 3.12 or newer and depends only on httpx and xlrd. The development version can be installed from the
repository with `pip install "c5tools @ git+https://github.com/Big-Dig-Data/c5tools@python#subdirectory=python"`.

## Command Line Tools

The package installs two console scripts, the equivalents of the PHP scripts in [`demo`](https://github.com/Big-Dig-Data/c5tools/tree/python/demo):

```console
c5tools-validate-file -f report.json            # validate a report file (JSON, CSV, TSV, xlsx, xls, ods)
c5tools-validate-file -f report.tsv -j          # also print the JSON representation of a usable report
c5tools-validate-file -f report.xlsx -x result.xlsx   # save the validation result as Excel file
c5tools-validate-api -u 'https://example.com/r51/reports/tr?customer_id=...&begin_date=...&end_date=...'
```

`-m` and `-t` print the memory and time used. The output is the PHP scripts' output, the exit code 0, 5 for invalid
options and 255 for an unexpected error.

## Library

See the [library guide](https://github.com/Big-Dig-Data/c5tools/blob/python/python/docs/guide.md) for validating report files, buffers and COUNTER API requests, reading the
result (JSON, text, Excel) and the parsed report, and how errors are reported.

## REST Service

The REST service has the JSON contract of the PHP service (`public/index.php`, `public/file.php` and
`public/api.php`), as the optional extra `c5tools[server]` (Starlette, uvicorn):

| Endpoint | Request | Response |
| --- | --- | --- |
| `GET /` (`/index.php`) | | `{"status": "OK", ...}` |
| `POST /file.php?extension=<json\|csv\|tsv\|xlsx\|xls\|ods>` (`/file`) | the report file as body | `{"memory": <int>, "result": <CheckResult JSON>}` |
| `POST /api.php` (`/api`) | `{"url": "<COUNTER API request URL>"}` | `{"memory": <int>, "result": <CheckResult JSON>, "report": <response JSON, zlib (level 3) and base64> or null}` |

Other methods get 405, an invalid `api.php` body 400 with `{"error": ...}`, a body larger than the maximum 413 with
`{"error": ...}`. A file or a COUNTER API response that can't be validated is a fatal error in the result. Where PHP
fails with an uncaught `Error` (and answers 500), the service answers 500 with `{"error": "internal server error"}`
and logs the error. The bodies are PHP's byte for byte, except `memory` (the peak resident set size of the process)
and the content type of the 400 responses (`application/json` instead of PHP's default `text/html`).

COUNTER API requests may only connect to public addresses: the host is resolved, every address is checked, and the
connection is made to a checked address (no DNS rebinding); redirects are checked the same way. The timeouts are
PHP's: 30 seconds to connect, 300 seconds for a request (see `c5tools.api.guard`).

Configuration (environment variables):

| Variable | Default | Meaning |
| --- | --- | --- |
| `C5TOOLS_MAX_UPLOAD_SIZE` | `100M` | maximum request body size in bytes, with optional unit `K`, `M`, `G` (1024-based); `0` for unlimited |
| `C5TOOLS_API_ALLOW_PRIVATE_ADDRESSES` | `false` | `true` allows COUNTER API requests to private, loopback, link-local and other non-public addresses (no SSRF protection) |
| `C5TOOLS_API_ALLOWED_NETWORKS` | | comma-separated networks (CIDR) that COUNTER API requests may connect to although they aren't public, e.g. `10.1.2.0/24,fd00::/64` |
| `C5TOOLS_API_MAX_RESPONSE_SIZE` | `500M` | maximum size of a COUNTER API response (bytes received), like `C5TOOLS_MAX_UPLOAD_SIZE` |
| `WEB_CONCURRENCY` | `1` | number of worker processes (uvicorn) |

Invalid values stop the service at startup. Run it with any ASGI server, e.g.

```console
pip install "c5tools[server]==0.9.0a1"
uvicorn --factory c5tools.server:create_app --host 0.0.0.0 --port 8080
uv run --extra server uvicorn --factory c5tools.server:create_app --port 8080   # in python/, for development
```

### Docker

`Dockerfile` builds a small image (multi-stage, `python:3.12-slim`, the dependencies from `uv.lock`, non-root user
`c5tools`, port 8080, health check on `/`). In the repository root:

```console
docker build -t c5tools-server python/
docker run --rm -p 8080:8080 -e WEB_CONCURRENCY=2 c5tools-server
curl -X POST --data-binary @tests/corpus/reports/r51/cop/TR_sample_r51.json 'http://localhost:8080/file.php?extension=json'
curl -X POST -d '{"url": "https://example.com/r51/status"}' http://localhost:8080/api.php
```

Behind a TLS-intercepting proxy, pass its CA certificates to the build with `--secret
id=ca-bundle,src=/path/to/ca-bundle.crt` (and the proxy with `--build-arg HTTPS_PROXY=...`). The CI job `docker`
builds the image and runs `scripts/smoke_test_server.py`, which posts corpus files to the running service and
compares the results with `tests/expected` (`uv run python scripts/smoke_test_server.py http://localhost:8080`).

## Development

Requires [uv](https://docs.astral.sh/uv/) and Python 3.12 or newer. All commands are run in `python/`:

```console
uv sync                                     # create .venv with the package and the dev tools
uv run pytest                               # unit tests and parity tests
uv run ruff check                           # lint
uv run ruff format --check                  # formatting (uv run ruff format to fix)
uv run mypy                                 # type check (strict)
uv run coverage run -m pytest && uv run coverage report   # branch coverage
```

## Releases

The package is published to PyPI by the workflow `.github/workflows/publish.yml` when a tag `python-v<version>` is
pushed. The workflow builds the sdist and the wheel (`uv build --no-sources`) on the self-hosted runner, checks that
the tag matches the package version, checks the distributions with `twine check --strict`, installs the wheel into a
new virtual environment and validates a corpus file with it, and uploads the distributions as artifact; a second
job on a GitHub-hosted runner publishes them with PyPI's trusted publishing (`pypa/gh-action-pypi-publish`, OpenID
Connect, no API token) in the GitHub environment `pypi`.

One-time setup:

1. On pypi.org, log in with the account that should own the project, open *Your account* → *Publishing* and add a
   *pending publisher* (GitHub): PyPI project name `c5tools`, owner `Big-Dig-Data`, repository `c5tools`, workflow
   name `publish.yml`, environment name `pypi`. The first upload creates the project; the pending publisher becomes
   its trusted publisher. Add the co-maintainers to the project afterwards.
2. In the GitHub repository, create the environment `pypi` (*Settings* → *Environments*). Recommended: required
   reviewers, so that every upload is approved, and a deployment tag rule `python-v*`.

Release:

1. Set the version in `src/c5tools/__init__.py` (`__version__`, the single source of the version; PEP 440, e.g.
   `0.9.0a2`, `0.9.0rc1`, `1.0.0`), update the version in the installation instructions above and in
   `docs/guide.md`, run `uv lock` (the lock file records the version), and commit.
2. When CI is green for the commit, tag and push it: `git tag python-v0.9.0a2 && git push origin python-v0.9.0a2`.
3. Approve the deployment in the workflow run if the environment requires it; check the release on
   https://pypi.org/project/c5tools/.

A version can't be uploaded twice: to fix a broken release, publish a new version (and yank the broken one on
PyPI). To check the build locally: `uv build --no-sources && uvx twine check --strict dist/*`.

## Configuration

The COUNTER configuration in `src/c5tools/config/r50` and `r51` is generated from the PHP configuration in
[`src/config`](https://github.com/Big-Dig-Data/c5tools/tree/python/src/config) (requires `php`); don't edit the generated modules, change the PHP files and run

```console
uv run python scripts/convert_config.py             # regenerate the modules
uv run python scripts/convert_config.py --check     # exit with 1 if they are not up to date (run in CI)
```

Check methods are referenced as functions in `c5tools.checks` (`checkedCountryCode` becomes
`checks.checked_country_code`). Each check takes a `c5tools.checks.CheckContext` followed by the PHP arguments.

The ISBN range data in `src/c5tools/isbn/ranges.py` is generated from the nicebooks/isbn package in
`composer.lock` (requires `php` and the Composer dependencies), so that ISBNs are hyphenated like
`RangeService::format`; regenerate it when the package is updated:

```console
uv run python scripts/convert_isbn_ranges.py             # regenerate the module
uv run python scripts/convert_isbn_ranges.py --check     # exit with 1 if it is not up to date (run in CI)
```

## PHP Oracles

The scripts in [`tests/oracles`](https://github.com/Big-Dig-Data/c5tools/tree/python/tests/oracles) run parts of the PHP implementation for differential tests.
Oracles that need only PHP are run by the tests (skipped if `php` is missing, unless `C5TOOLS_REQUIRE_PHP=1` is set
as in CI): `config-lookups.php` by `tests/test_config.py`, `php-functions.php` (`json_decode`, `finfo`, `fgetcsv`,
...) by `tests/test_readers_php.py`, (`strtotime`, `date`, `DateTime::createFromFormat`) by
`tests/test_timelib_php.py`, (`preg_match`, `parse_url`) by `tests/test_checks_identifiers.py` and (`parse_str`,
`rawurlencode`) by `tests/test_api.py`. Oracles that need the Composer dependencies write fixtures that are committed:

```console
php ../tests/oracles/check-result-roundtrip.php > tests/data/check-result-roundtrip.json
php ../tests/oracles/dump-cells.php --write          # tests/data/cell-grids (the PHP CI job runs --check)
php ../tests/oracles/format-values.php > tests/data/format-values.json
uv run python scripts/generate_reader_fixtures.py    # edge case spreadsheets in tests/data/spreadsheets
```

The field checks are compared with PHP call by call: `checks.php` runs the methods of `src/traits/Checks.php` on
a host class that uses the traits, `tests/check_oracle.py` runs the same calls with the Python checks and compares
the results (`tests/test_checks_*.py`). This oracle needs the Composer dependencies and runs on the fly (the CI
job installs them; locally the tests are skipped without `vendor/`). The date checks depend on the current time;
`check-clock.php` lets the oracle use the time of the call (`CheckCall.now`, `CheckContext.now` in Python). The
test inputs include element values
collected from the corpus:

```console
uv run python scripts/collect_check_values.py            # tests/data/check-values.json (CI runs --check)
```

`dump-cells.php` dumps the cell grids of all tabular corpus files and of the edge cases in `tests/data/spreadsheets`
as the validation sees them; `tests/test_readers_tabular.py` compares the readers with them. Regenerate the dumps
when tabular corpus files are added or changed.

The report validation is compared with PHP on generated variants of the corpus samples: `report-snapshots.php`
prints the snapshots of a list of report files (`Snapshot::forReport`), `tests/test_report_php.py` generates the
variants of the JSON samples and `tests/test_report_tabular_php.py` those of the TSV samples (also written as xlsx,
ods and CSV files) and compare them with the Python snapshots (on the fly, needs the Composer dependencies like the
check oracle). Likewise the COUNTER API validation: `api-snapshots.php` prints the snapshots of API case files
(`Snapshot::forApi`), `tests/test_api_php.py` generates request URLs, list and exception responses, reports checked
against the request and variants of the corpus API cases; `tests/test_api_client.py` tests the `CounterApiClient`
with the recorded responses.

The Excel output is compared by content: `check-result-xlsx.php` writes check results with `CheckResult::saveXlsx`
and dumps the PHP and the Python file as the PhpSpreadsheet reader loads them (cells with data types and styles,
merged cells, auto filter, frozen pane, column widths); `tests/test_spreadsheet_php.py` compares the check results
of the corpus cases and generated values (on the fly, needs the Composer dependencies). `tests/test_cli.py` compares
the command line tools with `demo/validate_file.php` and `demo/validate_api.php` (the API cases are served to both
by a local HTTPS server with a self-signed certificate, made with `openssl`, see `tests/https_server.py`), and
`tests/test_server.py` the REST service with the PHP service (`php -S` on a copy of `public/`).

`file-response.php` runs the code of `public/file.php` with a set current time (for the dates in the checks and
the `datetime` of the result); `tests/test_shadow.py` compares its responses with `c5tools.shadow.compare_file`
(around midnight and the turn of the year, and with the content-based reader choice), and
`scripts/shadow_case.py` uses it to reproduce the differences of the shadow run (see the
[library guide](https://github.com/Big-Dig-Data/c5tools/blob/python/python/docs/guide.md#shadow-run)).

## Parity Harness

`c5tools.testing.snapshot(case)` creates the snapshot of a corpus case (e.g. `reports/r51/cop/TR_sample_r51.json` or
`api/r51/status-valid.json`) in the format of `tests/src/Snapshot.php`. The parity report compares the snapshots of
all corpus cases with the expected PHP snapshots:

```console
uv run python -m c5tools.testing.parity                     # report as Markdown
uv run python -m c5tools.testing.parity --diff CASE [CASE ...]   # differences for single cases
uv run python -m c5tools.testing.parity --only reports/r51/  # report on the cases starting with a prefix
uv run python -m c5tools.testing.parity --update            # update tests/parity-matching.txt
uv run python -m c5tools.testing.parity --check             # exit with 1 if tests/parity-matching.txt is outdated
```

The report shows

* the matching cases per corpus group (directory) and in total, and the cases with order-only differences, errors
  (exceptions other than `NotImplementedError`) and not implemented parts,
* the matching messages per position prefix: `.Report_Header` and `.Report_Items` for JSON reports, header cells
  (rows 1-14) and body for tabular reports, and the case type (file name prefix: `status`, `members`, `reports`,
  `report`, `exception`, `request`, `response`) for API cases. Messages are matched per position regardless of their
  order, positions with the same messages in a different order are counted separately, since messages at the same
  position must be in the same order as in PHP.

Every corpus case matches (since stage 8b) without tolerated differences; `test_parity.py` checks that every case
is in the list of matching cases. A case whose validation raises `NotImplementedError` (e.g. a spreadsheet feature
the readers don't support, `UnsupportedSpreadsheetError`) counts as not implemented.

The CI job adds the report to the job summary.

### Parity Tests and the List of Matching Cases

`tests/test_parity.py` runs every corpus case. `tests/parity-matching.txt` lists the cases that match: these must
keep matching, all other cases are expected to fail (strict `xfail`). When a change makes more cases match, they
fail as `XPASS(strict)` until the list is updated with `--update`, so commit the updated list with the change. A
regression of a listed case fails the tests.

### Tolerated Differences

Differences that can't or shouldn't be fixed are listed in `src/c5tools/testing/tolerated.py` with the case, the
part of the snapshot (`result`, `text`, `usable`, `json`, `crash` or `*`) and the reason. A tolerated difference
needs approval in the PR review, the goal is an empty list. The tests fail for entries that are no longer needed.

The corpus is found relative to the package (`../tests`); set `C5TOOLS_TESTS_DIR` to use another `tests` directory.
