Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrated to Asphalt 5 #22

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
- name: Create packages
run: python -m build
- name: Archive packages
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: dist
path: dist
Expand All @@ -36,7 +36,7 @@ jobs:
id-token: write
steps:
- name: Retrieve packages
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
- name: Upload packages
uses: pypa/gh-action-pypi-publish@release/v1

Expand Down
12 changes: 6 additions & 6 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest]
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "pypy-3.10"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "pypy-3.10"]
include:
- os: macos-latest
python-version: "3.8"
python-version: "3.9"
- os: macos-latest
python-version: "3.12"
python-version: "3.13"
- os: windows-latest
python-version: "3.8"
python-version: "3.9"
- os: windows-latest
python-version: "3.12"
python-version: "3.13"
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
Expand All @@ -32,7 +32,7 @@ jobs:
cache: pip
cache-dependency-path: pyproject.toml
- name: Install dependencies
run: pip install .[test]
run: pip install -e .[test]
- name: Test with pytest
run: coverage run -m pytest -v
- name: Generate coverage report
Expand Down
17 changes: 11 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# * Run "pre-commit install".
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
rev: v5.0.0
hooks:
- id: check-toml
- id: check-yaml
Expand All @@ -16,18 +16,23 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.5
rev: v0.8.4
hooks:
- id: ruff
args: [--fix, --show-fixes]
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.2
rev: v1.14.0
hooks:
- id: mypy
args: ["--explicit-package-bases"]
additional_dependencies:
- asphalt
- py4j
- asphalt@git+https://github.com/asphalt-framework/asphalt
- pytest

- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: rst-backticks
- id: rst-directive-colons
- id: rst-inline-touching-normal
2 changes: 1 addition & 1 deletion .readthedocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ version: 2
build:
os: ubuntu-22.04
tools:
python: "3.8"
python: "3.9"

sphinx:
configuration: docs/conf.py
Expand Down
4 changes: 3 additions & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
API reference
=============

.. py:currentmodule:: asphalt.py4j

Component
---------

.. autoclass:: asphalt.py4j.component.Py4JComponent
.. autoclass:: Py4JComponent
3 changes: 3 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx_autodoc_typehints",
"sphinx_rtd_theme",
]

templates_path = ["_templates"]
Expand All @@ -24,6 +25,8 @@

exclude_patterns = ["_build"]
pygments_style = "sphinx"
autodoc_default_options = {"members": True, "show-inheritance": True}
autodoc_inherit_docstrings = False
highlight_language = "python3"
todo_include_todos = False

Expand Down
4 changes: 1 addition & 3 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,8 @@ of the component:

components:
py4j:
py4j-remote:
type: py4j
py4j/remote:
launch_jvm: false
resource_name: remote
gateway:
host: 10.0.0.1

Expand Down
4 changes: 0 additions & 4 deletions docs/requirements.txt

This file was deleted.

5 changes: 5 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ Version history

This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.

**UNRELEASED**

- **BACKWARD INCOMPATIBLE** Bumped minimum Asphalt version to 5.0
- Dropped support for Python 3.7 and 3.8

**4.0.0** (2023-12-26)

- **BACKWARD INCOMPATIBLE** Bumped minimum Asphalt version to 4.8
Expand Down
17 changes: 9 additions & 8 deletions examples/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@
standard output.
"""

from anyio import to_thread
from asphalt.core import CLIApplicationComponent, get_resource_nowait, run_application
from py4j.java_gateway import JavaGateway

from asphalt.core import CLIApplicationComponent, Context, run_application


class ApplicationComponent(CLIApplicationComponent):
async def start(self, ctx: Context) -> None:
def __init__(self) -> None:
self.add_component("py4j")
await super().start(ctx)

async def run(self, ctx: Context) -> None:
javagw = ctx.require_resource(JavaGateway)
async with ctx.threadpool():
async def run(self) -> None:
def read_file() -> None:
f = javagw.jvm.java.io.File(__file__)
buffer = javagw.new_array(javagw.jvm.char, f.length())
reader = javagw.jvm.java.io.FileReader(f)
reader.read(buffer)
reader.close()
print(javagw.jvm.java.lang.String(buffer))

javagw = get_resource_nowait(JavaGateway)
await to_thread.run_sync(read_file)


run_application(ApplicationComponent())
run_application(ApplicationComponent)
53 changes: 29 additions & 24 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ classifiers = [
"Typing :: Typed",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
]
requires-python = ">=3.8"
requires-python = ">=3.9"
dependencies = [
"asphalt ~= 4.8",
"asphalt @ git+https://github.com/asphalt-framework/asphalt",
"py4j >= 0.10.9"
]
dynamic = ["version"]
Expand All @@ -37,9 +37,9 @@ Homepage = "https://github.com/asphalt-framework/asphalt-py4j"

[project.optional-dependencies]
test = [
"anyio >= 4.0",
"anyio[trio] >= 4.1",
"coverage >= 7",
"pytest",
"pytest >= 7",
]
doc = [
"Sphinx >= 7.0",
Expand All @@ -48,29 +48,37 @@ doc = [
]

[project.entry-points."asphalt.components"]
py4j = "asphalt.py4j.component:Py4JComponent"
py4j = "asphalt.py4j:Py4JComponent"

[tool.setuptools_scm]
version_scheme = "post-release"
local_scheme = "dirty-tag"

[tool.ruff]
select = [
[tool.ruff.lint]
extend-select = [
"ASYNC", # flake8-async
"E", "F", "W", # default Flake8
"G", # flake8-logging-format
"I", # isort
"ISC", # flake8-implicit-str-concat
"PGH", # pygrep-hooks
"RUF100", # unused noqa (yesqa)
"RUF", # Ruff-specific rules
"UP", # pyupgrade
"W", # pycodestyle warnings
]

[tool.ruff.lint.isort]
known-first-party = ["asphalt.py4j"]
known-third-party = ["asphalt.core"]

[tool.pytest.ini_options]
addopts = ["-rsfE", "--tb=short"]
testpaths = ["tests"]

[tool.mypy]
python_version = "3.8"
python_version = "3.9"
strict = true
ignore_missing_imports = true
mypy_path = ["src", "tests"]
explicit_package_bases = true
mypy_path = ["src", "tests", "examples"]

[tool.coverage.run]
source = ["asphalt.py4j"]
Expand All @@ -81,17 +89,14 @@ branch = true
show_missing = true

[tool.tox]
legacy_tox_ini = """
[tox]
envlist = py38, py39, py310, py311, pypy3
env_list = ["py39", "py310", "py311", "py312", "py313", "pypy3"]
skip_missing_interpreters = true
minversion = 4.0

[testenv]
extras = test
commands = python -m pytest {posargs}
[tool.tox.env_run_base]
commands = [["python", "-m", "pytest", { replace = "posargs", extend = true }]]
package = "editable"
extras = ["test"]

[testenv:docs]
extras = doc
commands = sphinx-build -W -n docs build/sphinx {posargs}
"""
[tool.tox.env.docs]
commands = [["sphinx-build", "-W", "-n", "docs", "build/sphinx", { replace = "posargs", extend = true }]]
extras = ["doc"]
10 changes: 10 additions & 0 deletions src/asphalt/py4j/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Any

from ._component import Py4JComponent as Py4JComponent

# Re-export imports, so they look like they live directly in this package
key: str
value: Any
for key, value in list(locals().items()):
if getattr(value, "__module__", "").startswith(f"{__name__}."):
value.__module__ = __name__
33 changes: 9 additions & 24 deletions src/asphalt/py4j/component.py → src/asphalt/py4j/_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@
import logging
import os
import re
from collections.abc import AsyncGenerator
from collections.abc import Iterable
from importlib import import_module
from typing import Any, Iterable, cast
from typing import Any, cast

from asphalt.core import Component, add_resource

from asphalt.core import Component, Context, context_teardown
from py4j.java_gateway import (
CallbackServerParameters,
GatewayParameters,
JavaGateway,
launch_gateway,
)

logger = logging.getLogger(__name__)
logger = logging.getLogger("asphalt.py4j")
package_re = re.compile(r"\{(.+?)\}")


class Py4JComponent(Component):
"""
Creates a :class:`~py4j.java_gateway.JavaGateway` resource.

:param resource_name: name of the Java gateway resource to be published
:param launch_jvm: ``True`` to spawn a Java Virtual Machine in a subprocess and
connect to it, ``False`` to connect to an existing Py4J enabled JVM
:param gateway: either a :class:`~py4j.java_gateway.GatewayParameters` object or
Expand All @@ -37,14 +37,12 @@ class path

def __init__(
self,
resource_name: str = "default",
launch_jvm: bool = True,
gateway: GatewayParameters | dict[str, Any] | None = None,
callback_server: CallbackServerParameters | dict[str, Any] | bool = False,
javaopts: Iterable[str] = (),
classpath: Iterable[str] = "",
):
self.resource_name = resource_name
self.launch_jvm = launch_jvm
classpath = (
classpath if isinstance(classpath, str) else os.pathsep.join(classpath)
Expand Down Expand Up @@ -85,8 +83,7 @@ def __init__(
else:
self.callback_server_params = callback_server

@context_teardown
async def start(self, ctx: Context) -> AsyncGenerator[None, Exception | None]:
async def start(self) -> None:
if self.launch_jvm:
self.gateway_params.port = launch_gateway(
classpath=self.classpath, javaopts=self.javaopts
Expand All @@ -96,19 +93,7 @@ async def start(self, ctx: Context) -> AsyncGenerator[None, Exception | None]:
gateway_parameters=self.gateway_params,
callback_server_parameters=self.callback_server_params,
)
ctx.add_resource(gateway, self.resource_name)
logger.info(
"Configured Py4J gateway (%s; address=%s, port=%d)",
self.resource_name,
self.gateway_params.address,
self.gateway_params.port,
add_resource(
gateway,
teardown_callback=gateway.shutdown if self.launch_jvm else gateway.close,
)

yield

if self.launch_jvm:
gateway.shutdown()
else:
gateway.close()

logger.info("Py4J gateway (%s) shut down", self.resource_name)
Empty file added src/asphalt/py4j/py.typed
Empty file.
6 changes: 0 additions & 6 deletions tests/conftest.py

This file was deleted.

Loading
Loading