Metadata-Version: 2.4
Name: presolv
Version: 0.2.1
Requires-Dist: dnspython>=2.4
Requires-Dist: pytest>=7 ; extra == 'test'
Provides-Extra: test
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Summary: High-performance bulk/streaming DNS resolver (Rust core, dnspython API)
License: MIT OR Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Issues, https://github.com/inabox099/presolv/issues
Project-URL: Repository, https://github.com/inabox099/presolv

# presolv

High-performance DNS resolver for Python. The core engine is Rust/tokio
(exposed via PyO3); the Python surface is synchronous, dnspython-based, and
built for bulk and streaming resolution — resolving large query lists,
draining queues, or feeding results to/from message brokers.

- **Throughput**: all network I/O is asynchronous (tokio) regardless of the
  synchronous Python API.
- **Bounded resources**: a global rate limiter and connection pool cap
  concurrency against downstream nameservers.
- **Streaming-friendly**: `resolve()`/`resolve_stream()` accept any iterable
  — lists, generators, or a generator wrapping a broker consumer — and
  presolv has no broker-specific dependencies.
- **Lame-server detection**: nameservers that repeatedly fail to respond are
  temporarily blacklisted so they stop being sent queries.

See `spec.md` for the full design; this README covers install and usage.

## Install

```bash
pip install presolv
```

## Example

```python
import presolv
import dns.message

resolver = presolv.Resolver(rate_limit=200, pool_size=50, concurrency=500)

queries = [
    presolv.Query(dns.message.make_query("example.com", "A"), nameserver="8.8.8.8",
                  protocol="tcp", metadata={"probe_id": "probe-001"}),
    presolv.Query(dns.message.make_query("example.org", "AAAA"), nameserver="1.1.1.1",
                  metadata={"probe_id": "probe-002"}),
]

results = []
for result in resolver.resolve(queries):
    if result.status == presolv.ResultStatus.TIMEOUT:
        print(f"probe {result.metadata['probe_id']} timed out: {result.error}")
    elif result.error is not None:
        print(f"probe {result.metadata['probe_id']} failed ({result.status.value}): {result.error}")
    else:
        results.append(result.response)

resolver.close()
```

Results arrive in **completion order**, not input order; each `Result`
carries an `index` matching the position of the original query so you can
correlate back to the input (e.g. to ack a specific broker message).
For correlation across services or resolver calls, supply
`Query(metadata={"probe_id": ...})`: every result echoes that dictionary,
including failures. Metadata accepts string-keyed dictionaries containing nested
JSON values, defaults to `{}`, and is deeply copied at query construction and
again at submission. Mutating the original dictionary cannot change the query;
mutating the query after submission cannot change an in-flight result.
Non-string keys, arbitrary objects, cycles, and non-finite numbers are rejected.
Metadata supports up to 128 nested containers, including the root dictionary.

## Result statuses

Every result has a string-backed `ResultStatus`:

| Status value | Meaning |
|---|---|
| `success` | A valid DNS response arrived, including NXDOMAIN/SERVFAIL. |
| `timeout` | The final attempt timed out after the retry policy ran. |
| `network` | A transport failure, or no nameservers configured. |
| `protocol` | An invalid or unparseable response. |
| `pool_exhausted` | A connection could not be acquired within the timeout. |
| `lame` | The target nameservers were already blacklisted; no attempt was made. |

Use `result.status.value` for the stable status string and `result.error` for
typed failure details. Status describes the **final outcome**: a successful
retry is `success`. Existing nameserver/protocol fields and final-attempt
`rtt_ms` timing are unchanged. Future releases may add statuses; distributed
consumers should explicitly handle unrecognized values.

**Migration:** `raise_on_error` has been removed. Completed per-query failures
always arrive as results through both `resolve()` and `resolve_stream()`.
Source/validation errors and callback exceptions still propagate (or source
errors go to `on_error`, when supplied). Keep `response_format="dict"` when
publishing DNS response payloads as JSON; error objects are not JSON-serializable.

The Rust API similarly adds owned JSON-object `metadata` to `Request` and
`Outcome`. `Outcome::status()` returns a non-exhaustive `OutcomeStatus`, with
matching strings via `as_str()`. Include a wildcard arm when matching it.

## Response formats

`Resolver(response_format="message")` (default) returns `dns.message.Message`
objects. `response_format="dict"` returns a plain, JSON-serializable nested
dict instead — useful for publishing results downstream without requiring
consumers to depend on `dnspython`. See the `dict` shape in `spec.md` §5.7.

## Broker usage patterns

Presolv has no dependency on Kafka, RabbitMQ, or any other broker client
library, and ships no broker-specific adapter classes.

**Pull model** (`resolve`):

```python
import presolv
import dns.message

def from_kafka(consumer):
    for msg in consumer:
        query = dns.message.from_wire(msg.value())
        yield presolv.Query(query, nameserver="8.8.8.8", protocol="udp")

resolver = presolv.Resolver(rate_limit=500)
for result in resolver.resolve(from_kafka(consumer)):
    handle(result)
    consumer.commit()  # ack after processing
```

**Push model** (`resolve_stream`, useful when offset/ack must happen exactly
when a result is produced):

```python
def handle_result(result: presolv.Result) -> None:
    publish_downstream(result)
    channel.basic_ack(delivery_tag=...)

resolver.resolve_stream(from_rabbitmq(consumer), on_result=handle_result)
```

## Security note

Presolv pools long-lived UDP sockets, so the source port is fixed per
`(nameserver, protocol)` key; spoofing resistance relies on DNS message-ID
randomness only (ports are not randomized per query, unlike a traditional
stub resolver opening a fresh socket per request). Use presolv against
operator-chosen/trusted resolvers, not over hostile networks.

## Out of scope (v1)

- DNS-over-TLS (DoT) and DNS-over-HTTPS (DoH) — `"udp"`/`"tcp"` only.
- Automatic TCP fallback on a truncated (TC-flagged) UDP response — the
  truncated response is returned as-is; resubmit with `protocol="tcp"` if
  needed.
- DNSSEC validation, response caching, an asyncio-native API, and built-in
  broker adapter classes.

## Development

```bash
python3 -m venv .venv && . .venv/bin/activate
pip install maturin pytest dnspython
maturin develop
cargo test        # Rust unit + integration tests
pytest -q         # Python test suite
```

## Publishing releases

Pushing a `v*` tag runs the wheel workflow. It builds and tests wheels on
Linux, macOS, and Windows, then publishes them together to PyPI only after
all builds succeed. Authentication uses PyPI Trusted Publishing (GitHub OIDC);
no PyPI API token or GitHub secret is required.

One-time setup:

1. In GitHub, open this repository's **Settings > Environments** and create
   an environment named `pypi`. Restrict deployment tags to `v*` and, where
   available, require a maintainer's approval before deployment.
2. Sign in to PyPI as an owner of `presolv`, then open
   [presolv's Publishing settings](https://pypi.org/manage/project/presolv/settings/publishing/).
   Add a **GitHub** trusted publisher with these exact values:

   | Field | Value |
   |---|---|
   | Owner | `inabox099` |
   | Repository | `presolv` |
   | Workflow filename | `wheels.yml` |
   | Environment name | `pypi` |

   Use only the workflow filename, not `.github/workflows/wheels.yml`.
   If the project does not exist yet, register a
   [pending publisher](https://pypi.org/manage/account/publishing/) with project
   name `presolv` and the same values.
3. Before releasing, update the version in `Cargo.toml`, `Cargo.lock`,
   `pyproject.toml`, and the native-version assertion in `python/tests/test_smoke.py`
   to the same unused PyPI version. Commit and push the changes, and wait for CI
   to pass on Linux, macOS, and Windows before creating and pushing the matching
   tag (for example, `v0.2.1`). Configure
   Trusted Publishing **before** pushing the tag.
4. Approve the `pypi` environment deployment if required, and check the
   workflow's `publish` job. PyPI does not allow overwriting an uploaded
   distribution; fixes to an already published release need a new version.

The workflow publishes wheels, not a source distribution, and does not create
a GitHub Release. See the [PyPI setup documentation](https://docs.pypi.org/trusted-publishers/adding-a-publisher/)
for details.

