Skip to content

Commit 067ba3c

Browse files
authored
Link extensions against a library shipped by another installed package (#95)
* Link extensions against a library shipped by another installed package A library artifact may name an installed Python package with python-package instead of a manifest. hatch-rs takes the library from that package's lib/ and headers from include/, links the consumer against it, and adds an rpath to the sibling package in bundled mode. In external mode the package is ignored and the library resolves as before, so a conda recipe builds unchanged. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> * Suppress the fixture's cross-package import for ty Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --------- Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com>
1 parent a6d532a commit 067ba3c

9 files changed

Lines changed: 309 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,27 @@ library. Header, symbol, and validation-command checks still run against the
265265
external file, and the artifact manifest records it with role
266266
`external-library`.
267267

268+
A library that another installed wheel ships is declared with `python-package`
269+
instead of `manifest`: hatch-rs locates that package in the build environment
270+
(so the producer must be a build dependency) and takes the library from its
271+
`lib/` and the headers from its `include/`. In `bundled` mode the extension
272+
gets an rpath to the sibling package (`$ORIGIN/../fsspec_rs/lib` below), on
273+
the assumption that both wheels install into one site-packages; on Windows
274+
the consumer package imports the producer first so its `lib/` is on the DLL
275+
search path. In `external` mode the package is ignored and the library is
276+
resolved as above, which is what a conda recipe wants.
277+
278+
```toml
279+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
280+
name = "fsspec"
281+
python-package = "fsspec_rs"
282+
283+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
284+
name = "fsspec_kafka"
285+
destination = "fsspec_kafka/{python_extension_name}"
286+
links = ["fsspec"]
287+
```
288+
268289
### ABI validation and artifact metadata
269290

270291
`cdylib` artifacts can validate the copied C ABI library before the wheel is

‎hatch_rs/structs.py‎

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from ctypes import CDLL
66
from dataclasses import dataclass
77
from glob import glob
8+
from importlib.util import find_spec
89
from json import dumps, loads
910
from os import environ
1011
from os.path import relpath
@@ -93,6 +94,7 @@ class ExternalLibrary:
9394
library_dir: Path
9495
include_dir: Path | None
9596
link_name: str
97+
package: str | None = None
9698

9799

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

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

740753
@dataclass(frozen=True)
741754
class PlannedArtifact:
@@ -1171,9 +1184,10 @@ def generate(self):
11711184
self._linked_names = self._linked_library_names(artifacts)
11721185
self._external_libraries = {}
11731186
for artifact in artifacts:
1174-
if artifact.name in self._linked_names and self._resolved_library_source in ("static", "direct"):
1187+
library = artifact.python_package is not None or artifact.name in self._linked_names
1188+
if library and self._resolved_library_source in ("static", "direct"):
11751189
continue
1176-
if artifact.name in self._linked_names and self._resolved_library_source == "external":
1190+
if library and (artifact.python_package is not None or self._resolved_library_source == "external"):
11771191
planned_artifact = self._plan_external_library(artifact, global_target=global_target)
11781192
elif self._is_generated_artifact(artifact):
11791193
planned_artifact = self._build_command_artifact_plan(artifact, global_target=global_target)
@@ -1242,13 +1256,13 @@ def _library_env(self, artifact: RustArtifactConfig, resolved_target: ResolvedTa
12421256
environment = {}
12431257
for link in artifact.links:
12441258
key = sub(r"[^A-Za-z0-9]", "_", link).upper()
1245-
if self._resolved_library_source == "bundled":
1246-
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target))
1247-
elif self._resolved_library_source == "external":
1248-
external = self._external_libraries[link]
1259+
external = self._external_libraries.get(link)
1260+
if external is not None:
12491261
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(external.library_dir)
12501262
if external.include_dir is not None:
12511263
environment[f"HATCH_RS_LIBRARY_{key}_INCLUDE_DIR"] = str(external.include_dir)
1264+
elif self._resolved_library_source == "bundled":
1265+
environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target))
12521266
return environment
12531267

12541268
def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> list[str]:
@@ -1263,8 +1277,10 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res
12631277
args.extend(("-C", f"link-arg=-Wl,-soname,{shared_library}"))
12641278
if mode in ("static", "direct"):
12651279
return args
1280+
origin = "$ORIGIN" if platform == "linux" else "@loader_path"
12661281
for link in artifact.links:
1267-
if mode == "bundled":
1282+
external = self._external_libraries.get(link)
1283+
if external is None:
12681284
library_dir = self._bundled_library_dir(link, resolved_target)
12691285
link_name = f"{link}.dll" if platform == "win32" else link
12701286
args.extend(("-L", f"native={library_dir}", "-l", f"dylib={link_name}"))
@@ -1273,12 +1289,14 @@ def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: Res
12731289
self._destination_directory(self._artifact_by_name(link), resolved_target),
12741290
self._destination_directory(artifact, resolved_target),
12751291
)
1276-
origin = "$ORIGIN" if platform == "linux" else "@loader_path"
12771292
rpath = origin if relative == "." else f"{origin}/{Path(relative).as_posix()}"
12781293
args.extend(("-C", f"link-arg=-Wl,-rpath,{rpath}"))
12791294
else:
1280-
external = self._external_libraries[link]
12811295
args.extend(("-L", f"native={external.library_dir}", "-l", f"dylib={external.link_name}"))
1296+
if external.package is not None and platform in ("linux", "darwin"):
1297+
# both packages sit in one site-packages, so the rpath walks from the extension to the sibling package
1298+
relative = relpath(Path(*external.package.split(".")) / "lib", self._destination_directory(artifact, resolved_target))
1299+
args.extend(("-C", f"link-arg=-Wl,-rpath,{origin}/{Path(relative).as_posix()}"))
12821300
return args
12831301

12841302
def _pkg_config_variable(self, artifact: RustArtifactConfig, variable: str) -> Path:
@@ -1298,9 +1316,16 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s
12981316
name = self._artifact_name(artifact)
12991317
label = self._artifact_label(artifact)
13001318
root = environ.get("HATCH_RS_LIBRARY_ROOT") or (str(artifact.library_root) if artifact.library_root is not None else None)
1319+
package = artifact.python_package if self._resolved_library_source == "bundled" else None
13011320
if root:
13021321
prefix = _resolve_path(root, base=Path(self.path))
13031322
library_dir, include_dir = prefix / "lib", prefix / "include"
1323+
elif package:
1324+
spec = find_spec(package)
1325+
if spec is None or not spec.submodule_search_locations:
1326+
raise ValueError(f"Artifact '{label}' package '{package}' is not installed in the build environment.")
1327+
prefix = Path(next(iter(spec.submodule_search_locations)))
1328+
library_dir, include_dir = prefix / "lib", prefix / "include"
13041329
elif artifact.pkg_config:
13051330
library_dir = self._pkg_config_variable(artifact, "libdir")
13061331
include_dir = self._pkg_config_variable(artifact, "includedir")
@@ -1333,6 +1358,7 @@ def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: s
13331358
library_dir=library_dir,
13341359
include_dir=include_dir if include_dir.is_dir() else None,
13351360
link_name=link_name,
1361+
package=package,
13361362
)
13371363

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

‎hatch_rs/tests/test_project_python_extension_package_library/Cargo.lock‎

Lines changed: 14 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
[package]
2+
name = "package_link_extension_py"
3+
version = "0.1.0"
4+
edition = "2021"
5+
publish = false
6+
7+
[lib]
8+
name = "package_link_extension"
9+
path = "src/lib.rs"
10+
crate-type = ["cdylib"]
11+
12+
[dependencies]
13+
c_abi_library = { path = "../test_project_python_extension_c_abi_library/rust", optional = true }
14+
15+
[features]
16+
default = ["capi"]
17+
capi = []
18+
direct = ["dep:c_abi_library"]
19+
20+
[profile.release]
21+
panic = "abort"
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from __future__ import annotations
2+
3+
from ctypes import CDLL, c_int
4+
from pathlib import Path
5+
from sys import platform
6+
7+
# The producer package adds its lib/ directory to the DLL search path on Windows and,
8+
# elsewhere, loads the library this extension links by its SONAME or install name.
9+
import c_abi_bundle_project # ty: ignore[import-not-found]
10+
11+
_PACKAGE_DIR = Path(__file__).resolve().parent
12+
_EXTENSION_SUFFIX = ".pyd" if platform == "win32" else ".so"
13+
14+
_EXTENSION = CDLL(str(_PACKAGE_DIR / f"package_link_extension{_EXTENSION_SUFFIX}"))
15+
_EXTENSION.package_link_extension_library_answer.restype = c_int
16+
17+
18+
def library_answer() -> int:
19+
"""The other package's library answer, reached through this extension."""
20+
return int(_EXTENSION.package_link_extension_library_answer())
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
[build-system]
2+
requires = ["hatchling>=1.20"]
3+
build-backend = "hatchling.build"
4+
5+
[project]
6+
name = "hatch-rs-test-project-python-extension-package-library"
7+
description = "Python extension linking a C ABI library shipped by another installed package"
8+
version = "0.1.0"
9+
requires-python = ">=3.9"
10+
dependencies = [
11+
"hatchling>=1.20",
12+
"hatch-rs",
13+
]
14+
15+
[tool.hatch.build]
16+
artifacts = [
17+
"package_link_project/*.dll",
18+
"package_link_project/*.dylib",
19+
"package_link_project/*.pyd",
20+
"package_link_project/*.so",
21+
"package_link_project/lib/*.json",
22+
]
23+
24+
[tool.hatch.build.sources]
25+
src = "/"
26+
27+
[tool.hatch.build.targets.sdist]
28+
packages = ["package_link_project"]
29+
30+
[tool.hatch.build.targets.wheel]
31+
packages = ["package_link_project"]
32+
33+
[tool.hatch.build.hooks.hatch-rs]
34+
verbose = true
35+
path = "."
36+
module = "package_link_project"
37+
target-dir = "isolated"
38+
artifact-manifest = true
39+
40+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
41+
name = "c_abi_library"
42+
python-package = "c_abi_bundle_project"
43+
44+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
45+
name = "package_link_extension"
46+
manifest = "Cargo.toml"
47+
destination = "package_link_project/{python_extension_name}"
48+
links = ["c_abi_library"]
49+
50+
[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features]
51+
bundled = ["capi"]
52+
external = ["capi"]
53+
static = ["direct"]
54+
direct = ["direct"]
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#[cfg(feature = "capi")]
2+
extern "C" {
3+
fn c_abi_library_answer() -> i32;
4+
}
5+
6+
#[cfg(feature = "direct")]
7+
use c_abi_library::c_abi_library_answer;
8+
9+
#[no_mangle]
10+
pub extern "C" fn package_link_extension_library_answer() -> i32 {
11+
unsafe { c_abi_library_answer() }
12+
}

‎hatch_rs/tests/test_projects.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from os import environ, listdir, pathsep
44
from os.path import dirname
55
from pathlib import Path
6-
from shutil import copy2, rmtree, which
6+
from shutil import copy2, copytree, rmtree, which
77
from subprocess import PIPE, STDOUT, check_call, run
88
from sys import executable, modules, path, platform, version_info
99
from zipfile import ZipFile
@@ -337,6 +337,42 @@ def test_python_extension_links_external_c_abi_library(self, tmp_path):
337337
env["DYLD_LIBRARY_PATH" if platform == "darwin" else "LD_LIBRARY_PATH"] = str(prefix / "lib")
338338
_assert_c_abi_answers(env, shared=False)
339339

340+
def test_python_extension_links_library_from_installed_package(self, tmp_path):
341+
"""A second package links the library the first one ships, as fsspec-kafka does with fsspec-rs."""
342+
consumer_root = Path("hatch_rs/tests") / "test_project_python_extension_package_library"
343+
consumer_package = consumer_root / "package_link_project"
344+
rmtree(consumer_root / "dist", ignore_errors=True)
345+
rmtree(consumer_package / "lib", ignore_errors=True)
346+
for artifact in consumer_package.glob("package_link_extension*"):
347+
artifact.unlink()
348+
_clean_c_abi_project()
349+
check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=C_ABI_PROJECT, env=_subprocess_env())
350+
351+
# the producer is importable in the build environment, as an installed build dependency would be
352+
env = _subprocess_env()
353+
env["PYTHONPATH"] = f"{C_ABI_PROJECT.resolve()}{pathsep}{env['PYTHONPATH']}"
354+
check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=consumer_root, env=env)
355+
356+
extension_name = "package_link_extension.pyd" if platform == "win32" else "package_link_extension.so"
357+
assert (consumer_package / extension_name).exists()
358+
assert list((consumer_package / "lib").iterdir()) == [consumer_package / "lib" / "hatch-rs-artifacts.json"]
359+
records = loads((consumer_package / "lib" / "hatch-rs-artifacts.json").read_text())["artifacts"]
360+
library = [record for record in records if record["name"] == "c_abi_library"]
361+
assert [record["role"] for record in library] == ["external-library"]
362+
assert Path(library[0]["source"]).is_relative_to(C_ABI_PACKAGE.resolve())
363+
assert "c_abi_library_answer" not in exported_symbols(consumer_package / extension_name)
364+
365+
# install both packages side by side and call through to the producer's library
366+
site = tmp_path / "site"
367+
copytree(C_ABI_PACKAGE, site / "c_abi_bundle_project")
368+
copytree(consumer_package, site / "package_link_project")
369+
env["PYTHONPATH"] = str(site)
370+
check_call([executable, "-c", "import package_link_project as m; assert m.library_answer() == 7"], cwd=tmp_path, env=env)
371+
if platform != "win32":
372+
# the rpath alone finds the sibling package's library, without the producer being imported first
373+
code = f"from ctypes import CDLL; assert CDLL({str(site / 'package_link_project' / extension_name)!r}).package_link_extension_library_answer() == 7"
374+
check_call([executable, "-c", code], cwd=tmp_path, env=env)
375+
340376
def test_python_extension_compiles_c_abi_library_in_direct_mode(self):
341377
_clean_c_abi_project()
342378
env = _subprocess_env()

0 commit comments

Comments
 (0)