From 9bb89c1d0615ac3a162686a698d8c5be17958503 Mon Sep 17 00:00:00 2001 From: masklinn Date: Mon, 15 Jul 2024 21:22:17 +0200 Subject: [PATCH] pyo3 bindings Advantages ========== - Can do the entire loading in one shot in pure rust from a python iterable. - Work using rust semantics. - Really just works. - Only requires a pyi for type declarations (?). Drawbacks ========= - Likely slower than cffi for pypy, but unlikely to be slower than the slog of pure python. - Graal don't work in tox. --- .github/workflows/pychecks.yaml | 41 ++++++ .github/workflows/pyo3-wheels.yml | 198 +++++++++++++++++++++++++++++ .github/workflows/rust.yml | 11 +- .gitignore | 2 + Cargo.toml | 2 +- ua-parser-py/Cargo.toml | 13 ++ ua-parser-py/pyproject.toml | 15 +++ ua-parser-py/src/lib.rs | 202 ++++++++++++++++++++++++++++++ ua-parser-py/tests/test_device.py | 53 ++++++++ ua-parser-py/tests/test_os.py | 63 ++++++++++ ua-parser-py/tests/test_ua.py | 64 ++++++++++ ua-parser-py/tox.ini | 29 +++++ ua-parser-py/ua_parser_rs.pyi | 59 +++++++++ 13 files changed, 745 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/pychecks.yaml create mode 100644 .github/workflows/pyo3-wheels.yml create mode 100644 ua-parser-py/Cargo.toml create mode 100644 ua-parser-py/pyproject.toml create mode 100644 ua-parser-py/src/lib.rs create mode 100644 ua-parser-py/tests/test_device.py create mode 100644 ua-parser-py/tests/test_os.py create mode 100644 ua-parser-py/tests/test_ua.py create mode 100644 ua-parser-py/tox.ini create mode 100644 ua-parser-py/ua_parser_rs.pyi diff --git a/.github/workflows/pychecks.yaml b/.github/workflows/pychecks.yaml new file mode 100644 index 0000000..e59f6ab --- /dev/null +++ b/.github/workflows/pychecks.yaml @@ -0,0 +1,41 @@ +name: py checks + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +jobs: + checks: + runs-on: ubuntu-latest + steps: + - name: Checkout working copy + uses: actions/checkout@v4 + - name: ruff check + uses: chartboost/ruff-action@v1 + with: + args: check + - name: ruff format + if: always() + uses: chartboost/ruff-action@v1 + with: + args: format --diff + - name: Set up Python + id: setup_python + if: always() + uses: actions/setup-python@v5 + with: + python-version: "3.x" + - name: Install mypy + id: install_mypy + if: ${{ always() && steps.setup_python.conclusion == 'success' }} + run: | + python -mpip install --upgrade pip + python -mpip install mypy pytest types-PyYaml + - name: mypy + if: ${{ always() && steps.install_mypy.conclusion == 'success' }} + run: mypy --strict . diff --git a/.github/workflows/pyo3-wheels.yml b/.github/workflows/pyo3-wheels.yml new file mode 100644 index 0000000..578fafa --- /dev/null +++ b/.github/workflows/pyo3-wheels.yml @@ -0,0 +1,198 @@ +# This file is autogenerated by maturin v1.7.4 +# To update, run +# +# maturin generate-ci --zig github +# +name: Wheels and Tests + +on: + push: + branches: [ main ] + tags: [ "*" ] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + wheels: + strategy: + matrix: + python-version: + - "3.x" + - "pypy-3.10" + - "graalpy-24" + arch: + - x86_64 + - aarch64 + platform: + - linux + - musllinux + - windows + - macos + + exclude: + - platform: windows + arch: aarch64 + - platform: windows + python-version: graalpy-24 + + include: + - platform: linux + manylinux: auto + - platform: musllinux + manylinux: musllinux_1_2 + + - args: --release --out dist -m ua-parser-py/Cargo.toml -i python + - platform: linux + args: --release --out dist -m ua-parser-py/Cargo.toml -i python --zig + - platform: musllinux + args: --release --out dist -m ua-parser-py/Cargo.toml + + - runs: ubuntu-latest + - platform: windows + runs: windows-latest + - platform: macos + runs: macos-latest + + runs-on: ${{ matrix.runs }} + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Build wheels + uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.arch }} + args: ${{ matrix.args }} + sccache: 'true' + manylinux: ${{ matrix.manylinux }} + - name: Upload wheels + uses: actions/upload-artifact@v4 + with: + name: wheels-${{ matrix.platform }}-${{ matrix.arch }}-${{ matrix.python-version }} + path: dist/* + + sdist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build sdist + uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist -m ua-parser-py/Cargo.toml + - name: Upload sdist + uses: actions/upload-artifact@v4 + with: + name: wheels-sdist + path: dist + + release: + name: Release + runs-on: ubuntu-latest + if: ${{ startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch' }} + needs: [wheels, sdist] + permissions: + # Use to sign the release artifacts + id-token: write + # Used to upload release artifacts + contents: write + # Used to generate artifact attestation + attestations: write + steps: + - uses: actions/download-artifact@v4 + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v1 + with: + subject-path: 'wheels-*/*' + - name: Publish to PyPI + if: "startsWith(github.ref, 'refs/tags/')" + uses: PyO3/maturin-action@v1 + env: + MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }} + with: + command: upload + args: --non-interactive --skip-existing wheels-*/* + + tests: + needs: wheels + + strategy: + fail-fast: false + matrix: + python-version: + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + - "pypy-3.10" + - "graalpy-24" + platform: + - linux + # probably requires a custom image of some sort + # - musllinux + - windows + - macos + + exclude: + - platform: windows + python-version: graalpy-24 + + include: + # would probably need to run qemu inside the thing to full + # test the archs... + - arch: x86_64 + - platform: macos + arch: aarch64 + + - wheel: "3.x" + - python-version: "pypy-3.10" + wheel: "pypy-3.10" + - python-version: "graalpy-24" + wheel: "graalpy-24" + + - runs: ubuntu-latest + - platform: windows + runs: windows-latest + - platform: macos + runs: macos-latest + + runs-on: ${{ matrix.runs }} + + steps: + - name: Checkout working copy + uses: actions/checkout@v4 + with: + submodules: true + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + - name: Retrieve wheel + uses: actions/download-artifact@v4 + with: + name: wheels-${{ matrix.platform }}-${{ matrix.arch }}-${{ matrix.wheel }} + path: dist + - name: Update pip + run: python -mpip install --upgrade pip + - name: Maybe install libyaml-dev + if: matrix.runs == 'ubuntu-latest' + run: | + # if binary wheels are not available for the current + # package install libyaml-dev so we can install pyyaml + # from source + if ! pip download --only-binary :all: pyyaml > /dev/null 2>&1; then + sudo apt install libyaml-dev + fi + - name: Install test dependencies + run: python -mpip install pytest pyyaml + - name: Install wheel + run: pip install --find-links dist ua_parser_rs + - name: Run tests + run: pytest -v -Werror -ra ua-parser-py diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index e22aeaa..25a53a3 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,25 +1,24 @@ name: Rust on: - push: - branches: [ "main" ] pull_request: - branches: [ "main" ] + push: + branches: + - main env: CARGO_TERM_COLOR: always jobs: checks: - runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: true - - name: Build - run: cargo build --verbose + - name: Check + run: cargo check - name: Format run: cargo fmt --check - name: clippy diff --git a/.gitignore b/.gitignore index 2ce191f..bffc5eb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ Cargo.lock *.dSYM/ regex-filtered/re2/flake.lock regex-filtered/re2/bench +.tox/ +__pycache__ diff --git a/Cargo.toml b/Cargo.toml index e857923..c9976a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["regex-filtered", "ua-parser"] +members = ["regex-filtered", "ua-parser", "ua-parser-py"] resolver = "2" [profile.release] diff --git a/ua-parser-py/Cargo.toml b/ua-parser-py/Cargo.toml new file mode 100644 index 0000000..6a3c645 --- /dev/null +++ b/ua-parser-py/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "ua_parser_rs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +name = "ua_parser_rs" +crate-type = ["cdylib"] + +[dependencies] +pyo3 = { version = "0.22", features = ["extension-module", "abi3", "abi3-py38"] } +ua-parser = { version = "0.2.0", path = "../ua-parser" } diff --git a/ua-parser-py/pyproject.toml b/ua-parser-py/pyproject.toml new file mode 100644 index 0000000..2640a16 --- /dev/null +++ b/ua-parser-py/pyproject.toml @@ -0,0 +1,15 @@ +[build-system] +requires = ["maturin>=1.5,<2.0"] +build-backend = "maturin" + +[project] +name = "ua_parser_rs" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Rust", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dynamic = ["version"] +[tool.maturin] +features = ["pyo3/extension-module"] diff --git a/ua-parser-py/src/lib.rs b/ua-parser-py/src/lib.rs new file mode 100644 index 0000000..0951c58 --- /dev/null +++ b/ua-parser-py/src/lib.rs @@ -0,0 +1,202 @@ +/// An uap-python Resolver is a callable which returns a PartialResult +/// (~a triplet of optional user_agent, os, and domain). A resolver +/// has lists of matchers for user agents, os, and devices taken in as +/// a Matchers (a 3-uple of lists of matchers). +/// +/// A matcher is a callable with a `pattern` and a `flags` properties. +/// But matchers also have additional properties for the replacement +/// information. +/// +/// In uap-rs, that's the ua_parser::Extractor doing that, kinda, but +/// it takes a struct from regexes.yaml and parses them in, so +/// probably better leaving that to the Python side and instead +/// exposing individual extractors with convenient interfaces. +/// +/// An Extractor is built off of a series of Parsers, which we could +/// get directly from the python side matchers *if those kept the +/// string as `regex` -> swap pattern and regex in the matcher (/ +/// rename pattern), and maybe expose regex_flag? +/// +/// May not matter as much because pyo3 natively can't piggyback +/// FromPyObject onto Deserialize, this requires the pythonize crate +/// and that seems a bit much for a measly 3 structs... Still, would +/// probably be a good idea for uap-python's matchers to retain the +/// structure of regexes.yaml parsers. Would have been nice to rename +/// them to Parsers as well but that's still very confusing given the +/// global Parser object, unless *that* gets renamed to Extractor on +/// the python side, or something. +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use std::borrow::Cow::{self, Owned}; + +type UAParser = ( + String, + Option, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct UserAgentExtractor(ua_parser::user_agent::Extractor<'static>); +#[pyclass(frozen)] +struct UserAgent { + #[pyo3(get)] + family: String, + #[pyo3(get)] + major: Option, + #[pyo3(get)] + minor: Option, + #[pyo3(get)] + patch: Option, + #[pyo3(get)] + patch_minor: Option, +} +#[pymethods] +impl UserAgentExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::user_agent::{Builder, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: UAParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + family_replacement: p.1.map(Owned), + v1_replacement: p.2.map(Owned), + v2_replacement: p.3.map(Owned), + v3_replacement: p.4.map(Owned), + v4_replacement: p.5.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| UserAgent { + family: v.family.into_owned(), + major: v.major.map(|s| s.to_string()), + minor: v.minor.map(|s| s.to_string()), + patch: v.patch.map(|s| s.to_string()), + patch_minor: v.patch_minor.map(|s| s.to_string()), + })) + } +} + +type OSParser = ( + String, + Option, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct OSExtractor(ua_parser::os::Extractor<'static>); +#[pyclass(frozen)] +struct OS { + #[pyo3(get)] + family: String, + #[pyo3(get)] + major: Option, + #[pyo3(get)] + minor: Option, + #[pyo3(get)] + patch: Option, + #[pyo3(get)] + patch_minor: Option, +} +#[pymethods] +impl OSExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::os::{Builder, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: OSParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + os_replacement: p.1.map(Owned), + os_v1_replacement: p.2.map(Owned), + os_v2_replacement: p.3.map(Owned), + os_v3_replacement: p.4.map(Owned), + os_v4_replacement: p.5.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| OS { + family: v.os.into_owned(), + major: v.major.map(Cow::into_owned), + minor: v.minor.map(Cow::into_owned), + patch: v.patch.map(Cow::into_owned), + patch_minor: v.patch_minor.map(Cow::into_owned), + })) + } +} + +type DeviceParser = ( + String, + Option, + Option, + Option, + Option, +); +#[pyclass(frozen)] +struct DeviceExtractor(ua_parser::device::Extractor<'static>); +#[pyclass(frozen)] +struct Device { + #[pyo3(get)] + family: String, + #[pyo3(get)] + brand: Option, + #[pyo3(get)] + model: Option, +} +#[pymethods] +impl DeviceExtractor { + #[new] + fn new(it: &Bound) -> PyResult { + use ua_parser::device::{Builder, Flag, Parser}; + it.iter()? + .try_fold(Builder::new(), |s, p| { + let p: DeviceParser = p?.extract()?; + s.push(Parser { + regex: Owned(p.0), + regex_flag: if p.1.as_deref() == Some("i") { + Some(Flag::IgnoreCase) + } else { + None + }, + device_replacement: p.2.map(Owned), + brand_replacement: p.3.map(Owned), + model_replacement: p.4.map(Owned), + }) + .map_err(|e| PyValueError::new_err(e.to_string())) + })? + .build() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Self) + } + fn extract(&self, s: &str) -> PyResult> { + Ok(self.0.extract(s).map(|v| Device { + family: v.device.into_owned(), + brand: v.brand.map(Cow::into_owned), + model: v.model.map(Cow::into_owned), + })) + } +} + +#[pymodule] +fn ua_parser_rs(m: &Bound) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + Ok(()) +} diff --git a/ua-parser-py/tests/test_device.py b/ua-parser-py/tests/test_device.py new file mode 100644 index 0000000..cc1e5aa --- /dev/null +++ b/ua-parser-py/tests/test_device.py @@ -0,0 +1,53 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + +MISSING_UA = {"family": "Other", "brand": None, "model": None} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_device.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_device(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.DeviceExtractor( + ( + t["regex"], + t.get("regex_flag"), + t.get("device_replacement"), + t.get("brand_replacement"), + t.get("model_replacement"), + ) + for t in contents["device_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + assert result == get_reference(test_case) diff --git a/ua-parser-py/tests/test_os.py b/ua-parser-py/tests/test_os.py new file mode 100644 index 0000000..2c92382 --- /dev/null +++ b/ua-parser-py/tests/test_os.py @@ -0,0 +1,63 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + + +MISSING_UA = { + "family": "Other", + "major": None, + "minor": None, + "patch": None, + "patch_minor": None, +} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_os.yaml", + CORE_DIR / "test_resources" / "additional_os_tests.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_os(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.OSExtractor( + ( + t["regex"], + t.get("os_replacement"), + t.get("os_v1_replacement"), + t.get("os_v2_replacement"), + t.get("os_v3_replacement"), + t.get("os_v4_replacement"), + ) + for t in contents["os_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + print(test_case) + assert result == get_reference(test_case) diff --git a/ua-parser-py/tests/test_ua.py b/ua-parser-py/tests/test_ua.py new file mode 100644 index 0000000..d0128dc --- /dev/null +++ b/ua-parser-py/tests/test_ua.py @@ -0,0 +1,64 @@ +import pathlib +import operator + +import pytest + +try: + from yaml import CSafeLoader as SafeLoader, load +except ImportError: + from yaml import SafeLoader, load # type: ignore + +import ua_parser_rs + + +CORE_DIR = pathlib.Path(__file__).resolve().parents[2] / "ua-parser" / "uap-core" + + +MISSING_UA = { + "family": "Other", + "major": None, + "minor": None, + "patch": None, +} # , "patch_minor": None} +get_reference = operator.itemgetter(*MISSING_UA) +get_result = operator.attrgetter(*MISSING_UA) + + +@pytest.mark.parametrize( + "test_file", + [ + CORE_DIR / "tests" / "test_ua.yaml", + CORE_DIR / "test_resources" / "firefox_user_agent_strings.yaml", + CORE_DIR / "test_resources" / "pgts_browser_list.yaml", + CORE_DIR / "test_resources" / "opera_mini_user_agent_strings.yaml", + CORE_DIR / "test_resources" / "podcasting_user_agent_strings.yaml", + ], + ids=operator.attrgetter("name"), +) +def test_ua(test_file: pathlib.Path) -> None: + with (CORE_DIR / "regexes.yaml").open("rb") as f: + contents = load(f, Loader=SafeLoader) + + parser = ua_parser_rs.UserAgentExtractor( + ( + t["regex"], + t.get("family_replacement"), + t.get("v1_replacement"), + t.get("v2_replacement"), + t.get("v3_replacement"), + t.get("v4_replacement"), + ) + for t in contents["user_agent_parsers"] + ) + + with test_file.open("rb") as f: + contents = load(f, Loader=SafeLoader) + + for test_case in contents["test_cases"]: + r = parser.extract(test_case["user_agent_string"]) + if r: + result = get_result(r) + else: + result = get_reference(MISSING_UA) + + assert result == get_reference(test_case) diff --git a/ua-parser-py/tox.ini b/ua-parser-py/tox.ini new file mode 100644 index 0000000..ad09f15 --- /dev/null +++ b/ua-parser-py/tox.ini @@ -0,0 +1,29 @@ +[tox] +env_list = py{39,310,311,312}, pypy3.10#, graalpy + , typecheck, format, lint +skip_missing_interpreters = true + +[testenv] +package = wheel +deps = + pytest + pyyaml +commands = pytest -Werror tests {posargs} + +[testenv:lint] +package = skip +deps = ruff +commands = ruff check {posargs} + +[testenv:format] +package = skip +deps = ruff +commands = ruff format {posargs:--diff} + +[testenv:typecheck] +package = skip +deps = + mypy + pytest + types-PyYaml +commands = mypy --strict {posargs:} . diff --git a/ua-parser-py/ua_parser_rs.pyi b/ua-parser-py/ua_parser_rs.pyi new file mode 100644 index 0000000..5b39f02 --- /dev/null +++ b/ua-parser-py/ua_parser_rs.pyi @@ -0,0 +1,59 @@ +from collections.abc import Iterable +from typing import Literal, Protocol + +UAParser = tuple[ + str, + str | None, + str | None, + str | None, + str | None, + str | None, +] + +class UserAgent(Protocol): + family: str + major: str | None + minor: str | None + patch: str | None + patch_minor: str | None + +class UserAgentExtractor: + def __init__(self, it: Iterable[UAParser], /) -> None: ... + def extract(self, s: str, /) -> UserAgent | None: ... + +OSParser = tuple[ + str, + str | None, + str | None, + str | None, + str | None, + str | None, +] + +class OS(Protocol): + family: str + major: str | None + minor: str | None + patch: str | None + patch_minor: str | None + +class OSExtractor: + def __init__(self, it: Iterable[OSParser], /) -> None: ... + def extract(self, s: str, /) -> OS | None: ... + +DeviceParser = tuple[ + str, + Literal["i"] | None, + str | None, + str | None, + str | None, +] + +class Device(Protocol): + family: str + brand: str | None + model: str | None + +class DeviceExtractor: + def __init__(self, it: Iterable[DeviceParser], /) -> None: ... + def extract(self, s: str, /) -> Device | None: ...