Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,27 @@ library. Header, symbol, and validation-command checks still run against the
external file, and the artifact manifest records it with role
`external-library`.

A library that another installed wheel ships is declared with `python-package`
instead of `manifest`: hatch-rs locates that package in the build environment
(so the producer must be a build dependency) and takes the library from its
`lib/` and the headers from its `include/`. In `bundled` mode the extension
gets an rpath to the sibling package (`$ORIGIN/../fsspec_rs/lib` below), on
the assumption that both wheels install into one site-packages; on Windows
the consumer package imports the producer first so its `lib/` is on the DLL
search path. In `external` mode the package is ignored and the library is
resolved as above, which is what a conda recipe wants.

```toml
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
name = "fsspec"
python-package = "fsspec_rs"

[[tool.hatch.build.hooks.hatch-rs.artifacts]]
name = "fsspec_kafka"
destination = "fsspec_kafka/{python_extension_name}"
links = ["fsspec"]
```

### ABI validation and artifact metadata

`cdylib` artifacts can validate the copied C ABI library before the wheel is
Expand Down
44 changes: 35 additions & 9 deletions hatch_rs/structs.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from ctypes import CDLL
from dataclasses import dataclass
from glob import glob
from importlib.util import find_spec
from json import dumps, loads
from os import environ
from os.path import relpath
Expand Down Expand Up @@ -93,6 +94,7 @@ class ExternalLibrary:
library_dir: Path
include_dir: Path | None
link_name: str
package: str | None = None


WINDOWS_TARGETS = {
Expand Down Expand Up @@ -650,6 +652,11 @@ class RustArtifactConfig(BaseModel):
library_root: Path | None = Field(
default=None, alias="library-root", description="Prefix with lib/ and include/ for this library in external mode."
)
python_package: str | None = Field(
default=None,
alias="python-package",
description="Installed Python package shipping this library under lib/ and include/; linked from there instead of built.",
)
import_library_destination: str | None = Field(
default=None,
alias="import-library-destination",
Expand Down Expand Up @@ -736,6 +743,12 @@ def validate_header_symbol_prefix(self) -> RustArtifactConfig:
raise ValueError(f"Artifact '{self.name}' must set expected-headers when using header-symbol-prefix.")
return self

@model_validator(mode="after")
def validate_python_package(self) -> RustArtifactConfig:
if self.python_package is not None and (not self.name or self.manifest is not None or self.destination is not None):
raise ValueError(f"Artifact '{self.name}' with python-package must set name and no manifest or destination.")
return self


@dataclass(frozen=True)
class PlannedArtifact:
Expand Down Expand Up @@ -1171,9 +1184,10 @@ def generate(self):
self._linked_names = self._linked_library_names(artifacts)
self._external_libraries = {}
for artifact in artifacts:
if artifact.name in self._linked_names and self._resolved_library_source in ("static", "direct"):
library = artifact.python_package is not None or artifact.name in self._linked_names
if library and self._resolved_library_source in ("static", "direct"):
continue
if artifact.name in self._linked_names and self._resolved_library_source == "external":
if library and (artifact.python_package is not None or self._resolved_library_source == "external"):
planned_artifact = self._plan_external_library(artifact, global_target=global_target)
elif self._is_generated_artifact(artifact):
planned_artifact = self._build_command_artifact_plan(artifact, global_target=global_target)
Expand Down Expand Up @@ -1242,13 +1256,13 @@ def _library_env(self, artifact: RustArtifactConfig, resolved_target: ResolvedTa
environment = {}
for link in artifact.links:
key = sub(r"[^A-Za-z0-9]", "_", link).upper()
if self._resolved_library_source == "bundled":
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target))
elif self._resolved_library_source == "external":
external = self._external_libraries[link]
external = self._external_libraries.get(link)
if external is not None:
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(external.library_dir)
if external.include_dir is not None:
environment[f"HATCH_RS_LIBRARY_{key}_INCLUDE_DIR"] = str(external.include_dir)
elif self._resolved_library_source == "bundled":
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target))
return environment

def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> list[str]:
Expand All @@ -1263,8 +1277,10 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res
args.extend(("-C", f"link-arg=-Wl,-soname,{shared_library}"))
if mode in ("static", "direct"):
return args
origin = "$ORIGIN" if platform == "linux" else "@loader_path"
for link in artifact.links:
if mode == "bundled":
external = self._external_libraries.get(link)
if external is None:
library_dir = self._bundled_library_dir(link, resolved_target)
link_name = f"{link}.dll" if platform == "win32" else link
args.extend(("-L", f"native={library_dir}", "-l", f"dylib={link_name}"))
Expand All @@ -1273,12 +1289,14 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res
self._destination_directory(self._artifact_by_name(link), resolved_target),
self._destination_directory(artifact, resolved_target),
)
origin = "$ORIGIN" if platform == "linux" else "@loader_path"
rpath = origin if relative == "." else f"{origin}/{Path(relative).as_posix()}"
args.extend(("-C", f"link-arg=-Wl,-rpath,{rpath}"))
else:
external = self._external_libraries[link]
args.extend(("-L", f"native={external.library_dir}", "-l", f"dylib={external.link_name}"))
if external.package is not None and platform in ("linux", "darwin"):
# both packages sit in one site-packages, so the rpath walks from the extension to the sibling package
relative = relpath(Path(*external.package.split(".")) / "lib", self._destination_directory(artifact, resolved_target))
args.extend(("-C", f"link-arg=-Wl,-rpath,{origin}/{Path(relative).as_posix()}"))
return args

def _pkg_config_variable(self, artifact: RustArtifactConfig, variable: str) -> Path:
Expand All @@ -1298,9 +1316,16 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s
name = self._artifact_name(artifact)
label = self._artifact_label(artifact)
root = environ.get("HATCH_RS_LIBRARY_ROOT") or (str(artifact.library_root) if artifact.library_root is not None else None)
package = artifact.python_package if self._resolved_library_source == "bundled" else None
if root:
prefix = _resolve_path(root, base=Path(self.path))
library_dir, include_dir = prefix / "lib", prefix / "include"
elif package:
spec = find_spec(package)
if spec is None or not spec.submodule_search_locations:
raise ValueError(f"Artifact '{label}' package '{package}' is not installed in the build environment.")
prefix = Path(next(iter(spec.submodule_search_locations)))
library_dir, include_dir = prefix / "lib", prefix / "include"
elif artifact.pkg_config:
library_dir = self._pkg_config_variable(artifact, "libdir")
include_dir = self._pkg_config_variable(artifact, "includedir")
Expand Down Expand Up @@ -1333,6 +1358,7 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s
library_dir=library_dir,
include_dir=include_dir if include_dir.is_dir() else None,
link_name=link_name,
package=package,
)

def _plan_external_library(self, artifact: RustArtifactConfig, *, global_target: str | None) -> PlannedArtifact:
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "package_link_extension_py"
version = "0.1.0"
edition = "2021"
publish = false

[lib]
name = "package_link_extension"
path = "src/lib.rs"
crate-type = ["cdylib"]

[dependencies]
c_abi_library = { path = "../test_project_python_extension_c_abi_library/rust", optional = true }

[features]
default = ["capi"]
capi = []
direct = ["dep:c_abi_library"]

[profile.release]
panic = "abort"
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from __future__ import annotations

from ctypes import CDLL, c_int
from pathlib import Path
from sys import platform

# The producer package adds its lib/ directory to the DLL search path on Windows and,
# elsewhere, loads the library this extension links by its SONAME or install name.
import c_abi_bundle_project # ty: ignore[import-not-found]

_PACKAGE_DIR = Path(__file__).resolve().parent
_EXTENSION_SUFFIX = ".pyd" if platform == "win32" else ".so"

_EXTENSION = CDLL(str(_PACKAGE_DIR / f"package_link_extension{_EXTENSION_SUFFIX}"))
_EXTENSION.package_link_extension_library_answer.restype = c_int


def library_answer() -> int:
"""The other package's library answer, reached through this extension."""
return int(_EXTENSION.package_link_extension_library_answer())
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
[build-system]
requires = ["hatchling>=1.20"]
build-backend = "hatchling.build"

[project]
name = "hatch-rs-test-project-python-extension-package-library"
description = "Python extension linking a C ABI library shipped by another installed package"
version = "0.1.0"
requires-python = ">=3.9"
dependencies = [
"hatchling>=1.20",
"hatch-rs",
]

[tool.hatch.build]
artifacts = [
"package_link_project/*.dll",
"package_link_project/*.dylib",
"package_link_project/*.pyd",
"package_link_project/*.so",
"package_link_project/lib/*.json",
]

[tool.hatch.build.sources]
src = "/"

[tool.hatch.build.targets.sdist]
packages = ["package_link_project"]

[tool.hatch.build.targets.wheel]
packages = ["package_link_project"]

[tool.hatch.build.hooks.hatch-rs]
verbose = true
path = "."
module = "package_link_project"
target-dir = "isolated"
artifact-manifest = true

[[tool.hatch.build.hooks.hatch-rs.artifacts]]
name = "c_abi_library"
python-package = "c_abi_bundle_project"

[[tool.hatch.build.hooks.hatch-rs.artifacts]]
name = "package_link_extension"
manifest = "Cargo.toml"
destination = "package_link_project/{python_extension_name}"
links = ["c_abi_library"]

[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features]
bundled = ["capi"]
external = ["capi"]
static = ["direct"]
direct = ["direct"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#[cfg(feature = "capi")]
extern "C" {
fn c_abi_library_answer() -> i32;
}

#[cfg(feature = "direct")]
use c_abi_library::c_abi_library_answer;

#[no_mangle]
pub extern "C" fn package_link_extension_library_answer() -> i32 {
unsafe { c_abi_library_answer() }
}
38 changes: 37 additions & 1 deletion hatch_rs/tests/test_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from os import environ, listdir, pathsep
from os.path import dirname
from pathlib import Path
from shutil import copy2, rmtree, which
from shutil import copy2, copytree, rmtree, which
from subprocess import PIPE, STDOUT, check_call, run
from sys import executable, modules, path, platform, version_info
from zipfile import ZipFile
Expand Down Expand Up @@ -337,6 +337,42 @@ def test_python_extension_links_external_c_abi_library(self, tmp_path):
env["DYLD_LIBRARY_PATH" if platform == "darwin" else "LD_LIBRARY_PATH"] = str(prefix / "lib")
_assert_c_abi_answers(env, shared=False)

def test_python_extension_links_library_from_installed_package(self, tmp_path):
"""A second package links the library the first one ships, as fsspec-kafka does with fsspec-rs."""
consumer_root = Path("hatch_rs/tests") / "test_project_python_extension_package_library"
consumer_package = consumer_root / "package_link_project"
rmtree(consumer_root / "dist", ignore_errors=True)
rmtree(consumer_package / "lib", ignore_errors=True)
for artifact in consumer_package.glob("package_link_extension*"):
artifact.unlink()
_clean_c_abi_project()
check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=C_ABI_PROJECT, env=_subprocess_env())

# the producer is importable in the build environment, as an installed build dependency would be
env = _subprocess_env()
env["PYTHONPATH"] = f"{C_ABI_PROJECT.resolve()}{pathsep}{env['PYTHONPATH']}"
check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=consumer_root, env=env)

extension_name = "package_link_extension.pyd" if platform == "win32" else "package_link_extension.so"
assert (consumer_package / extension_name).exists()
assert list((consumer_package / "lib").iterdir()) == [consumer_package / "lib" / "hatch-rs-artifacts.json"]
records = loads((consumer_package / "lib" / "hatch-rs-artifacts.json").read_text())["artifacts"]
library = [record for record in records if record["name"] == "c_abi_library"]
assert [record["role"] for record in library] == ["external-library"]
assert Path(library[0]["source"]).is_relative_to(C_ABI_PACKAGE.resolve())
assert "c_abi_library_answer" not in exported_symbols(consumer_package / extension_name)

# install both packages side by side and call through to the producer's library
site = tmp_path / "site"
copytree(C_ABI_PACKAGE, site / "c_abi_bundle_project")
copytree(consumer_package, site / "package_link_project")
env["PYTHONPATH"] = str(site)
check_call([executable, "-c", "import package_link_project as m; assert m.library_answer() == 7"], cwd=tmp_path, env=env)
if platform != "win32":
# the rpath alone finds the sibling package's library, without the producer being imported first
code = f"from ctypes import CDLL; assert CDLL({str(site / 'package_link_project' / extension_name)!r}).package_link_extension_library_answer() == 7"
check_call([executable, "-c", code], cwd=tmp_path, env=env)

def test_python_extension_compiles_c_abi_library_in_direct_mode(self):
_clean_c_abi_project()
env = _subprocess_env()
Expand Down
Loading
Loading