diff --git a/.coveragerc b/.coveragerc index 2567706..a920d99 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,28 +1,13 @@ -# .coveragerc to control coverage.py [run] -branch = True -source = pybiocfilecache -# omit = bad_file.py - -[paths] -source = - src/ - */site-packages/ +source = src +omit = tests/* [report] -# Regexes for lines to exclude from consideration exclude_lines = - # Have to re-enable the standard pragma pragma: no cover - - # Don't complain about missing debug-only code: def __repr__ - if self\.debug - - # Don't complain if tests don't hit defensive assertion code: + if self.debug: raise AssertionError raise NotImplementedError - - # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..12eea0d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "dependencies" + + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + labels: + - "dependencies" diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml new file mode 100644 index 0000000..d638c47 --- /dev/null +++ b/.github/workflows/pre-commit.yml @@ -0,0 +1,16 @@ +name: pre-commit + +on: + pull_request: + push: + branches: [main] + +jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: pre-commit/action@v3.0.1 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 1760f1d..c94cf8a 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,55 +1,91 @@ -# This workflow will install Python dependencies, run tests and lint with a single version of Python -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions - -name: Publish to PyPI +name: Publish to PyPI and GitHub Pages on: push: tags: "*" jobs: - build: + build-and-test: + name: Build and Test runs-on: ubuntu-latest - permissions: - id-token: write - repository-projects: write - contents: write - pages: write - steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - name: Set up Python 3.11 + - name: Set up Python 3.12 uses: actions/setup-python@v5 with: - python-version: 3.11 + python-version: 3.12 + + - name: Install tox + run: python -m pip install tox - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install tox + - name: Test + run: tox -e default - - name: Test with tox - run: | - tox + - name: Build Project + run: tox -e build + + - name: Store the distribution packages + uses: actions/upload-artifact@v4 + with: + name: python-package-distributions + path: dist/ + + build-docs: + name: Build Documentation + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Set up Python 3.12 + uses: actions/setup-python@v5 + with: + python-version: 3.12 + + - name: Install tox + run: python -m pip install tox - name: Build docs - run: | - tox -e docs + run: tox -e docs - - run: touch ./docs/_build/html/.nojekyll + - name: Add .nojekyll + run: touch ./docs/_build/html/.nojekyll - - name: GH Pages Deployment - uses: JamesIves/github-pages-deploy-action@v4 + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@v5 with: - branch: gh-pages # The branch the action should deploy to. - folder: ./docs/_build/html - clean: true # Automatically remove deleted files from the deploy branch + path: ./docs/_build/html - - name: Build Project and Publish - run: | - python -m tox -e clean,build + publish-pypi: + name: Publish to PyPI + needs: build-and-test + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/p/biocframe + permissions: + id-token: write # IMPORTANT: mandatory for trusted publishing + steps: + - name: Download all the dists + uses: actions/download-artifact@v8 + with: + name: python-package-distributions + path: dist/ - # This uses the trusted publisher workflow so no token is required. - - name: Publish to PyPI + - name: Publish package to PyPI uses: pypa/gh-action-pypi-publish@release/v1 + + deploy-pages: + name: Deploy GitHub Pages + needs: build-docs + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/r-interop-tests.yml b/.github/workflows/r-interop-tests.yml new file mode 100644 index 0000000..5551c07 --- /dev/null +++ b/.github/workflows/r-interop-tests.yml @@ -0,0 +1,55 @@ +name: R and Python Interop Tests + +on: + push: + branches: + - master + - main + pull_request: + branches: + - master + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: >- + ${{ github.workflow }}-${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + r-python-roundtrip: + runs-on: ubuntu-latest + name: R (BiocFileCache) <-> Python roundtrip + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install Python dependencies + run: | + python -m pip install --upgrade pip + pip install -e ".[testing]" + + - uses: r-lib/actions/setup-r@v2 + with: + use-public-rspm: true + + - name: Install R BiocFileCache + run: | + Rscript -e ' + if (!requireNamespace("BiocManager", quietly = TRUE)) + install.packages("BiocManager", repos = "https://cloud.r-project.org") + BiocManager::install("BiocFileCache", ask = FALSE, update = FALSE) + ' + + - name: Verify R BiocFileCache is available + run: Rscript -e "library(BiocFileCache)" + + - name: Run R/Python roundtrip tests + run: pytest tests/test_r_interop.py -v diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 90aa16a..ca79fe4 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -1,33 +1,70 @@ -name: Run tests +name: Test the library on: push: - branches: [master] + branches: + - master # for legacy repos + - main pull_request: - branches: [master] + branches: + - master # for legacy repos + - main + workflow_dispatch: # Allow manually triggering the workflow + schedule: + # Run roughly every 15 days at 00:00 UTC + # (useful to check if updates on dependencies break the package) + - cron: "0 0 1,16 * *" + +permissions: + contents: read + +concurrency: + group: >- + ${{ github.workflow }}-${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true jobs: - build: - runs-on: ubuntu-latest + test: strategy: matrix: - python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] - - name: Python ${{ matrix.python-version }} + python: ["3.10", "3.11", "3.12", "3.13", "3.14"] + platform: + - ubuntu-latest + - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + name: Python ${{ matrix.python }}, ${{ matrix.platform }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - - name: Setup Python + - name: Set up Python uses: actions/setup-python@v5 with: - python-version: ${{ matrix.python-version }} - cache: "pip" + python-version: ${{ matrix.python }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install tox + - name: Install tox + run: python -m pip install tox coverage - - name: Test with tox - run: | + - name: Run tests + run: >- tox + -- -rFEx --durations 10 --color yes --cov --cov-branch --cov-report=xml # pytest args + + - name: Check for codecov token availability + id: codecov-check + shell: bash + run: | + if [ ${{ secrets.CODECOV_TOKEN }} != '' ]; then + echo "codecov=true" >> $GITHUB_OUTPUT; + else + echo "codecov=false" >> $GITHUB_OUTPUT; + fi + + - name: Upload coverage reports to Codecov with GitHub Action + uses: codecov/codecov-action@v7 + if: ${{ steps.codecov-check.outputs.codecov == 'true' }} + with: + token: ${{ secrets.CODECOV_TOKEN }} + slug: ${{ github.repository }} + flags: ${{ matrix.platform }} - py${{ matrix.python }} diff --git a/.gitignore b/.gitignore index d2d26c6..d1c8f19 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,59 @@ MANIFEST # remove cache cache + +# Byte-compiled / optimized / DLL files +__pycache__/ +*$py.class +# C extensions +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +# PyInstaller +*.manifest +*.spec +# Installer logs +pip-log.txt +pip-delete-this-directory.txt +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.cache +nosetests.xml +*.cover +*.py,cover +.hypothesis/ +cover/ +# Sphinx documentation +docs/_build/ +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +# mypy, ruff, etc +.mypy_cache/ +.ruff_cache/ +.pyre/ +# Editors +.vscode/ +.idea/ +*.swp +*.swo diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3f91485..863ce2d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -33,10 +33,12 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.15.6 + rev: v0.16.2 hooks: - - id: ruff - args: [--fix, --exit-non-zero-on-fix] + # Run the linter. + - id: ruff-check + args: [--fix, --exit-zero] + # Run the formatter. - id: ruff-format ## If like to embrace black styles even in the docs: diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 21b0814..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,23 +0,0 @@ -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -# Build documentation in the docs/ directory with Sphinx -sphinx: - configuration: docs/conf.py - -# Build documentation with MkDocs -#mkdocs: -# configuration: mkdocs.yml - -# Optionally build your docs in additional formats such as PDF -formats: - - pdf - -python: - version: 3.8 - install: - - requirements: docs/requirements.txt - - {path: ., method: pip} diff --git a/CHANGELOG.md b/CHANGELOG.md index f17a9ea..7dcf348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Version 0.8.0 + +- Upgrade to hatchit template +- Fix issues with shared caches with R and Python interfaces. Added actions to test shared cache usage. + ## Version 0.7.0 - Fixing issues with using R and Python interfaces to the same cache directory. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..02b4546 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Contributing + +Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. + +## Report Bugs +Report bugs at the issue tracker. + +## Fix Bugs +Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. + +## Implement Features +Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. + +## Submit Feedback +The best way to send feedback is to file an issue. + +If you are proposing a feature: +- Explain in detail how it would work. +- Keep the scope as narrow as possible, to make it easier to implement. +- Remember that this is a volunteer-driven project, and that contributions are welcome! diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst deleted file mode 100644 index 4b6e75a..0000000 --- a/CONTRIBUTING.rst +++ /dev/null @@ -1,353 +0,0 @@ -.. todo:: THIS IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! - - The document assumes you are using a source repository service that promotes a - contribution model similar to `GitHub's fork and pull request workflow`_. - While this is true for the majority of services (like GitHub, GitLab, - BitBucket), it might not be the case for private repositories (e.g., when - using Gerrit). - - Also notice that the code examples might refer to GitHub URLs or the text - might use GitHub specific terminology (e.g., *Pull Request* instead of *Merge - Request*). - - Please make sure to check the document having these assumptions in mind - and update things accordingly. - -.. todo:: Provide the correct links/replacements at the bottom of the document. - -.. todo:: You might want to have a look on `PyScaffold's contributor's guide`_, - - especially if your project is open source. The text should be very similar to - this template, but there are a few extra contents that you might decide to - also include, like mentioning labels of your issue tracker or automated - releases. - - -============ -Contributing -============ - -Welcome to ``pyBiocFileCache`` contributor's guide. - -This document focuses on getting any potential contributor familiarized -with the development processes, but `other kinds of contributions`_ are also -appreciated. - -If you are new to using git_ or have never collaborated in a project previously, -please have a look at `contribution-guide.org`_. Other resources are also -listed in the excellent `guide created by FreeCodeCamp`_ [#contrib1]_. - -Please notice, all users and contributors are expected to be **open, -considerate, reasonable, and respectful**. When in doubt, `Python Software -Foundation's Code of Conduct`_ is a good reference in terms of behavior -guidelines. - - -Issue Reports -============= - -If you experience bugs or general issues with ``pyBiocFileCache``, please have a look -on the `issue tracker`_. If you don't see anything useful there, please feel -free to fire an issue report. - -.. tip:: - Please don't forget to include the closed issues in your search. - Sometimes a solution was already reported, and the problem is considered - **solved**. - -New issue reports should include information about your programming environment -(e.g., operating system, Python version) and steps to reproduce the problem. -Please try also to simplify the reproduction steps to a very minimal example -that still illustrates the problem you are facing. By removing other factors, -you help us to identify the root cause of the issue. - - -Documentation Improvements -========================== - -You can help improve ``pyBiocFileCache`` docs by making them more readable and coherent, or -by adding missing information and correcting mistakes. - -``pyBiocFileCache`` documentation uses Sphinx_ as its main documentation compiler. -This means that the docs are kept in the same repository as the project code, and -that any documentation update is done in the same way was a code contribution. - -.. todo:: Don't forget to mention which markup language you are using. - - e.g., reStructuredText_ or CommonMark_ with MyST_ extensions. - -.. todo:: If your project is hosted on GitHub, you can also mention the following tip: - - .. tip:: - Please notice that the `GitHub web interface`_ provides a quick way of - propose changes in ``pyBiocFileCache``'s files. While this mechanism can - be tricky for normal code contributions, it works perfectly fine for - contributing to the docs, and can be quite handy. - - If you are interested in trying this method out, please navigate to - the ``docs`` folder in the source repository_, find which file you - would like to propose changes and click in the little pencil icon at the - top, to open `GitHub's code editor`_. Once you finish editing the file, - please write a message in the form at the bottom of the page describing - which changes have you made and what are the motivations behind them and - submit your proposal. - -When working on documentation changes in your local machine, you can -compile them using |tox|_:: - - tox -e docs - -and use Python's built-in web server for a preview in your web browser -(``http://localhost:8000``):: - - python3 -m http.server --directory 'docs/_build/html' - - -Code Contributions -================== - -.. todo:: Please include a reference or explanation about the internals of the project. - - An architecture description, design principles or at least a summary of the - main concepts will make it easy for potential contributors to get started - quickly. - -Submit an issue ---------------- - -Before you work on any non-trivial code contribution it's best to first create -a report in the `issue tracker`_ to start a discussion on the subject. -This often provides additional considerations and avoids unnecessary work. - -Create an environment ---------------------- - -Before you start coding, we recommend creating an isolated `virtual -environment`_ to avoid any problems with your installed Python packages. -This can easily be done via either |virtualenv|_:: - - virtualenv - source /bin/activate - -or Miniconda_:: - - conda create -n pyscaffold python=3 six virtualenv pytest pytest-cov - conda activate pyscaffold - -Clone the repository --------------------- - -#. Create an user account on |the repository service| if you do not already have one. -#. Fork the project repository_: click on the *Fork* button near the top of the - page. This creates a copy of the code under your account on |the repository service|. -#. Clone this copy to your local disk:: - - git clone git@github.com:YourLogin/pyBiocFileCache.git - cd pyBiocFileCache - -#. You should run:: - - pip install -U pip setuptools -e . - - to be able run ``putup --help``. - - .. todo:: if you are not using pre-commit, please remove the following item: - -#. Install |pre-commit|_:: - - pip install pre-commit - pre-commit install - - ``pyBiocFileCache`` comes with a lot of hooks configured to automatically help the - developer to check the code being written. - -Implement your changes ----------------------- - -#. Create a branch to hold your changes:: - - git checkout -b my-feature - - and start making changes. Never work on the master branch! - -#. Start your work on this branch. Don't forget to add docstrings_ to new - functions, modules and classes, especially if they are part of public APIs. - -#. Add yourself to the list of contributors in ``AUTHORS.rst``. - -#. When you’re done editing, do:: - - git add - git commit - - to record your changes in git_. - - .. todo:: if you are not using pre-commit, please remove the following item: - - Please make sure to see the validation messages from |pre-commit|_ and fix - any eventual issues. - This should automatically use flake8_/black_ to check/fix the code style - in a way that is compatible with the project. - - .. important:: Don't forget to add unit tests and documentation in case your - contribution adds an additional feature and is not just a bugfix. - - Moreover, writing a `descriptive commit message`_ is highly recommended. - In case of doubt, you can check the commit history with:: - - git log --graph --decorate --pretty=oneline --abbrev-commit --all - - to look for recurring communication patterns. - -#. Please check that your changes don't break any unit tests with:: - - tox - - (after having installed |tox|_ with ``pip install tox`` or ``pipx``). - - You can also use |tox|_ to run several other pre-configured tasks in the - repository. Try ``tox -av`` to see a list of the available checks. - -Submit your contribution ------------------------- - -#. If everything works fine, push your local branch to |the repository service| with:: - - git push -u origin my-feature - -#. Go to the web page of your fork and click |contribute button| - to send your changes for review. - - .. todo:: if you are using GitHub, you can uncomment the following paragraph - - Find more detailed information `creating a PR`_. You might also want to open - the PR as a draft first and mark it as ready for review after the feedbacks - from the continuous integration (CI) system or any required fixes. - - -Troubleshooting ---------------- - -The following tips can be used when facing problems to build or test the -package: - -#. Make sure to fetch all the tags from the upstream repository_. - The command ``git describe --abbrev=0 --tags`` should return the version you - are expecting. If you are trying to run CI scripts in a fork repository, - make sure to push all the tags. - You can also try to remove all the egg files or the complete egg folder, i.e., - ``.eggs``, as well as the ``*.egg-info`` folders in the ``src`` folder or - potentially in the root of your project. - -#. Sometimes |tox|_ misses out when new dependencies are added, especially to - ``setup.cfg`` and ``docs/requirements.txt``. If you find any problems with - missing dependencies when running a command with |tox|_, try to recreate the - ``tox`` environment using the ``-r`` flag. For example, instead of:: - - tox -e docs - - Try running:: - - tox -r -e docs - -#. Make sure to have a reliable |tox|_ installation that uses the correct - Python version (e.g., 3.7+). When in doubt you can run:: - - tox --version - # OR - which tox - - If you have trouble and are seeing weird errors upon running |tox|_, you can - also try to create a dedicated `virtual environment`_ with a |tox|_ binary - freshly installed. For example:: - - virtualenv .venv - source .venv/bin/activate - .venv/bin/pip install tox - .venv/bin/tox -e all - -#. `Pytest can drop you`_ in an interactive session in the case an error occurs. - In order to do that you need to pass a ``--pdb`` option (for example by - running ``tox -- -k --pdb``). - You can also setup breakpoints manually instead of using the ``--pdb`` option. - - -Maintainer tasks -================ - -Releases --------- - -.. todo:: This section assumes you are using PyPI to publicly release your package. - - If instead you are using a different/private package index, please update - the instructions accordingly. - -If you are part of the group of maintainers and have correct user permissions -on PyPI_, the following steps can be used to release a new version for -``pyBiocFileCache``: - -#. Make sure all unit tests are successful. -#. Tag the current commit on the main branch with a release tag, e.g., ``v1.2.3``. -#. Push the new tag to the upstream repository_, e.g., ``git push upstream v1.2.3`` -#. Clean up the ``dist`` and ``build`` folders with ``tox -e clean`` - (or ``rm -rf dist build``) - to avoid confusion with old builds and Sphinx docs. -#. Run ``tox -e build`` and check that the files in ``dist`` have - the correct version (no ``.dirty`` or git_ hash) according to the git_ tag. - Also check the sizes of the distributions, if they are too big (e.g., > - 500KB), unwanted clutter may have been accidentally included. -#. Run ``tox -e publish -- --repository pypi`` and check that everything was - uploaded to PyPI_ correctly. - - - -.. [#contrib1] Even though, these resources focus on open source projects and - communities, the general ideas behind collaborating with other developers - to collectively create software are general and can be applied to all sorts - of environments, including private companies and proprietary code bases. - - -.. <-- strart --> -.. todo:: Please review and change the following definitions: - -.. |the repository service| replace:: GitHub -.. |contribute button| replace:: "Create pull request" - -.. _repository: https://github.com//pyBiocFileCache -.. _issue tracker: https://github.com//pyBiocFileCache/issues -.. <-- end --> - - -.. |virtualenv| replace:: ``virtualenv`` -.. |pre-commit| replace:: ``pre-commit`` -.. |tox| replace:: ``tox`` - - -.. _black: https://pypi.org/project/black/ -.. _CommonMark: https://commonmark.org/ -.. _contribution-guide.org: http://www.contribution-guide.org/ -.. _creating a PR: https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request -.. _descriptive commit message: https://chris.beams.io/posts/git-commit -.. _docstrings: https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html -.. _first-contributions tutorial: https://github.com/firstcontributions/first-contributions -.. _flake8: https://flake8.pycqa.org/en/stable/ -.. _git: https://git-scm.com -.. _GitHub's fork and pull request workflow: https://guides.github.com/activities/forking/ -.. _guide created by FreeCodeCamp: https://github.com/FreeCodeCamp/how-to-contribute-to-open-source -.. _Miniconda: https://docs.conda.io/en/latest/miniconda.html -.. _MyST: https://myst-parser.readthedocs.io/en/latest/syntax/syntax.html -.. _other kinds of contributions: https://opensource.guide/how-to-contribute -.. _pre-commit: https://pre-commit.com/ -.. _PyPI: https://pypi.org/ -.. _PyScaffold's contributor's guide: https://pyscaffold.org/en/stable/contributing.html -.. _Pytest can drop you: https://docs.pytest.org/en/stable/usage.html#dropping-to-pdb-python-debugger-at-the-start-of-a-test -.. _Python Software Foundation's Code of Conduct: https://www.python.org/psf/conduct/ -.. _reStructuredText: https://www.sphinx-doc.org/en/master/usage/restructuredtext/ -.. _Sphinx: https://www.sphinx-doc.org/en/master/ -.. _tox: https://tox.readthedocs.io/en/stable/ -.. _virtual environment: https://realpython.com/python-virtual-environments-a-primer/ -.. _virtualenv: https://virtualenv.pypa.io/en/stable/ - -.. _GitHub web interface: https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/editing-files-in-your-repository -.. _GitHub's code editor: https://docs.github.com/en/github/managing-files-in-a-repository/managing-files-on-github/editing-files-in-your-repository diff --git a/README.md b/README.md index b362678..2cb706b 100644 --- a/README.md +++ b/README.md @@ -1,92 +1,4 @@ -[![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/) -[![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/) -![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg) - -# pyBiocFileCache - -`pyBiocFileCache` is a Python package that provides a robust file caching system with resource validation, cache size management, file compression, and resource tagging. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache). - -## Installation - -Install from [PyPI](https://pypi.org/project/pyBiocFileCache/), - -```bash -pip install pybiocfilecache -``` - -## Quick Start - -```python -from pybiocfilecache import BiocFileCache - -# Initialize cache -cache = BiocFileCache("path/to/cache/directory") - -# Add a file to cache -resource = cache.add("myfile", "path/to/file.txt") - -# Retrieve a file from cache -resource = cache.get("myfile") - -# Use the cached file -print(resource["rpath"]) # Path to cached file -``` - -## Advanced Usage - -### Configuration - -```python -from pybiocfilecache import BiocFileCache, CacheConfig -from datetime import timedelta -from pathlib import Path - -# Create custom configuration -config = CacheConfig( - cache_dir=Path("cache_directory"), - cleanup_interval=timedelta(days=7), -) - -# Initialize cache with configuration -cache = BiocFileCache(config=config) -``` - -### Resource Management - -```python -# Add file with tags and expiration -from datetime import datetime, timedelta - -resource = cache.add( - "myfile", - "path/to/file.txt", - tags=["data", "raw"], - expires=datetime.now() + timedelta(days=30) -) - -# List resources by tag -resources = cache.list_resources(tag="data") - -# Search resources -results = cache.search("myfile", field="rname") - -# Update resource -cache.update("myfile", "path/to/new_file.txt") - -# Remove resource -cache.remove("myfile") -``` - -### Cache Statistics and Maintenance - -```python -# Get cache statistics -stats = cache.get_stats() -print(stats) - -# Clean up expired resources -removed_count = cache.cleanup() - -# Purge entire cache -cache.purge() +```{include} ../README.md +:relative-docs: docs/ +:relative-images: ``` diff --git a/docs/best_practices.md b/docs/best_practices.md index 0a134a9..fb69e46 100644 --- a/docs/best_practices.md +++ b/docs/best_practices.md @@ -1,28 +1,49 @@ # Best Practices -1. Use context managers for cleanup: +1. Use context managers for automatic database cleanup: ```python +from pybiocfilecache import BiocFileCache + with BiocFileCache("cache_directory") as cache: cache.add("myfile", "path/to/file.txt") ``` -2. Add tags for better organization: +2. Look up resources by `rname` or `rid`, and use `wait=False` to inspect missing files without waiting: ```python -cache.add("data.csv", "data.csv", tags=["raw", "csv", "2024"]) +# Standard lookup (waits up to 30s if a file copy is in progress) +rec = cache.get("myfile") + +# Immediate lookup when checking or repairing a missing cached file +rec = cache.get(rid="BFC1", wait=False) ``` -3. Set expiration dates for temporary files: +3. Search, update, and remove resources by `rname` or `rid` (especially useful when sharing a cache with R `BiocFileCache`): ```python -cache.add("temp.txt", "temp.txt", expires=datetime.now() + timedelta(hours=1)) +matches = cache.search("myfile", field="rname", exact=False) +cache.update(rid="BFC1", fpath="path/to/new_file.txt") +cache.remove(rid="BFC1") ``` -4. Regular maintenance: +4. Set expiration dates for temporary files: ```python -# Periodically clean up expired resources +from datetime import datetime, timedelta, timezone + +cache.add( + "temp.txt", + "temp.txt", + expires=datetime.now(timezone.utc) + timedelta(hours=1), +) +``` + +5. Regular maintenance and integrity checks: +```python +# Remove expired resources cache.cleanup() -# Monitor cache size +# Verify checksums of cached files +valid, invalid = cache.verify_cache() + +# Monitor cache statistics stats = cache.get_stats() -if stats["cache_size_bytes"] > threshold: - # Take action +print(stats["total_resources"], stats["expired_resources"]) ``` diff --git a/docs/conf.py b/docs/conf.py index 38fc05a..63916b3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -72,32 +72,28 @@ "sphinx.ext.ifconfig", "sphinx.ext.mathjax", "sphinx.ext.napoleon", - "sphinx_autodoc_typehints", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] -# Configure AutoStructify -# https://recommonmark.readthedocs.io/en/latest/auto_structify.html -def setup(app): - from recommonmark.transform import AutoStructify - - params = { - "enable_auto_toc_tree": True, - "auto_toc_tree_section": "Contents", - "auto_toc_maxdepth": 2, - "enable_eval_rst": True, - "enable_math": True, - "enable_inline_math": True, - } - app.add_config_value("recommonmark_config", params, True) - app.add_transform(AutoStructify) - - # Enable markdown -extensions.append("recommonmark") +extensions.append("myst_parser") + +# Configure MyST-Parser +myst_enable_extensions = [ + "amsmath", + "colon_fence", + "deflist", + "dollarmath", + "html_image", + "linkify", + "replacements", + "smartquotes", + "substitution", + "tasklist", +] # The suffix of source filenames. source_suffix = [".rst", ".md"] @@ -109,8 +105,8 @@ def setup(app): master_doc = "index" # General information about the project. -project = "pyBiocFileCache" -copyright = "2021, jkanche" +project = "pybiocfilecache" +copyright = "2026, Jayaram Kancherla" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -121,9 +117,10 @@ def setup(app): # If you don’t need the separation provided between version and release, # just set them both to the same value. try: - from pybiocfilecache import __version__ as version -except ImportError: - version = "" + from importlib.metadata import version as get_version + version = get_version("pybiocfilecache") +except Exception: + version = "unknown" if not version or version.lower() == "unknown": version = os.getenv("READTHEDOCS_VERSION", "unknown") # automatically set by RTD @@ -170,25 +167,29 @@ def setup(app): # If this is True, todo emits a warning for each TODO entries. The default is False. todo_emit_warnings = True -autodoc_default_options = { - 'special-members': True, - 'undoc-members': False, - 'exclude-members': '__weakref__, __dict__, __str__, __module__, __annotations__' -} - -autosummary_generate = True -autosummary_imported_members = True # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = "furo" +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -html_theme_options = {"sidebar_width": "300px", "page_width": "1200px"} +html_theme_options = { + "light_css_variables": { + "color-brand-primary": "#0052cc", + "color-brand-content": "#0052cc", + }, + "dark_css_variables": { + "color-brand-primary": "#4c9aff", + "color-brand-content": "#4c9aff", + }, + "source_repository": "https://github.com/biocpy/pybiocfilecache", + "source_branch": "main", + "source_directory": "docs/", +} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] @@ -256,7 +257,7 @@ def setup(app): # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = "pyBiocFileCache-doc" +htmlhelp_basename = "pybiocfilecache-doc" # -- Options for LaTeX output ------------------------------------------------ @@ -272,7 +273,9 @@ def setup(app): # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [("index", "user_guide.tex", "pyBiocFileCache Documentation", "jkanche", "manual")] +latex_documents = [ + ("index", "user_guide.tex", "pybiocfilecache Documentation", "Jayaram Kancherla", "manual") +] # The name of an image file (relative to this directory) to place at the top of # the title page. @@ -304,8 +307,27 @@ def setup(app): "sklearn": ("https://scikit-learn.org/stable", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable", None), "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), - "setuptools": ("https://setuptools.readthedocs.io/en/stable/", None), - "pyscaffold": ("https://pyscaffold.org/en/stable", None), + "setuptools": ("https://setuptools.pypa.io/en/stable/", None), } print(f"loading configurations for {project} {version} ...", file=sys.stderr) + +# -- Biocsetup configuration ------------------------------------------------- + +# Enable execution of code chunks in markdown +extensions.remove('myst_parser') +extensions.append('myst_nb') + +# Less verbose api documentation +extensions.append('sphinx_autodoc_typehints') + +autodoc_default_options = { + "special-members": True, + "undoc-members": True, + "exclude-members": "__weakref__, __dict__, __str__, __module__", +} + +autosummary_generate = True +autosummary_imported_members = True + +html_theme = "furo" diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..fc1b213 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,4 @@ +```{include} ../CONTRIBUTING.md +:relative-docs: docs/ +:relative-images: +``` diff --git a/docs/contributing.rst b/docs/contributing.rst deleted file mode 100644 index e582053..0000000 --- a/docs/contributing.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../CONTRIBUTING.rst diff --git a/docs/license.md b/docs/license.md new file mode 100644 index 0000000..b231201 --- /dev/null +++ b/docs/license.md @@ -0,0 +1,5 @@ +# License + +```{literalinclude} ../LICENSE.txt +:language: text +``` diff --git a/docs/license.rst b/docs/license.rst deleted file mode 100644 index 3989c51..0000000 --- a/docs/license.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. _license: - -======= -License -======= - -.. include:: ../LICENSE.txt diff --git a/docs/requirements.txt b/docs/requirements.txt index e1619a4..c20cf60 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,8 +1,9 @@ furo +myst-nb # Requirements file for ReadTheDocs, check .readthedocs.yml. # To build the module reference correctly, make sure every external package # under `install_requires` in `setup.cfg` is also listed here! # sphinx_rtd_theme -recommonmark +myst-parser[linkify] sphinx>=3.2.1 sphinx-autodoc-typehints diff --git a/pyproject.toml b/pyproject.toml index 00aa968..9070850 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,27 +1,88 @@ +[project] +name = "pybiocfilecache" +dynamic = ["version"] +description = "File based cache for resources and metadata" +readme = "README.md" +authors = [ + { name = "Jayaram Kancherla", email = "jayaram.kancherla@gmail.com" }, +] +requires-python = ">=3.9" +dependencies = [ + "biocframe", + "sqlalchemy", +] +keywords = [ + "biocfilecache", + "cache", + "file-cache", + "sqlite", + "resource-management", +] +classifiers = [ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering :: Bio-Informatics", + "Topic :: Software Development :: Libraries :: Python Modules", +] + +[project.license] +file = "LICENSE.txt" + +[project.urls] +Homepage = "https://github.com/BiocPy/pybiocfilecache" +Documentation = "https://biocpy.github.io/pybiocfilecache" +Repository = "https://github.com/BiocPy/pybiocfilecache" +"Bug Tracker" = "https://github.com/BiocPy/pybiocfilecache/issues" + +[project.optional-dependencies] +testing = [ + "pytest", + "pytest-cov", + "setuptools", +] + [build-system] -# AVOID CHANGING REQUIRES: IT WILL BE UPDATED BY PYSCAFFOLD! -requires = ["setuptools>=46.1.0", "setuptools_scm[toml]>=5", "wheel"] -build-backend = "setuptools.build_meta" +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" -[tool.setuptools_scm] -# See configuration details in https://github.com/pypa/setuptools_scm -version_scheme = "no-guess-dev" +[tool.hatch.version] +source = "vcs" +fallback-version = "0.1.0" [tool.ruff] line-length = 120 src = ["src"] -exclude = ["tests"] +exclude = ["tests", "docs"] + +[tool.ruff.lint] extend-ignore = ["F821"] -[tool.ruff.pydocstyle] +[tool.ruff.lint.pydocstyle] convention = "google" +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["E402", "F401"] + [tool.ruff.format] docstring-code-format = true docstring-code-line-length = 20 -[tool.ruff.per-file-ignores] -"__init__.py" = ["E402", "F401"] +[tool.mypy] +strict = true + +[tool.pytest.ini_options] +addopts = "--cov=pybiocfilecache --cov-report term-missing" +testpaths = ["tests"] -[tool.black] -force-exclude = "__init__.py" +[tool.bandit] +exclude_dirs = ["tests"] +skips = ["B110"] diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 8e6a470..0000000 --- a/setup.cfg +++ /dev/null @@ -1,124 +0,0 @@ -# This file is used to configure your project. -# Read more about the various options under: -# https://setuptools.readthedocs.io/en/stable/userguide/declarative_config.html - -[metadata] -name = pyBiocFileCache -description = File based cache for resources and metadata -author = jkanche -author_email = jayaram.kancherla@gmail.com -license = MIT -long_description = file: README.md -long_description_content_type = text/markdown; charset=UTF-8; variant=GFM -url = https://github.com/biocpy/pyBiocFileCache -# Add here related links, for example: -project_urls = - Documentation = https://biocpy.github.io/pyBiocFileCache/ - Source = https://github.com/biocpy/pyBiocFileCache -# Changelog = https://pyscaffold.org/en/latest/changelog.html -# Tracker = https://github.com/pyscaffold/pyscaffold/issues -# Conda-Forge = https://anaconda.org/conda-forge/pyscaffold -# Download = https://pypi.org/project/PyScaffold/#files -# Twitter = https://twitter.com/PyScaffold - -# Change if running only on Windows, Mac or Linux (comma-separated) -platforms = any - -# Add here all kinds of additional classifiers as defined under -# https://pypi.org/classifiers/ -classifiers = - Development Status :: 4 - Beta - Programming Language :: Python - - -[options] -zip_safe = False -packages = find_namespace: -include_package_data = True -package_dir = - =src - -# Require a min/specific Python version (comma-separated conditions) -python_requires = >=3.9 - -# Add here dependencies of your project (line-separated), e.g. requests>=2.2,<3.0. -# Version specifiers like >=2.2,<3.0 avoid problems due to API changes in -# new major versions. This works if the required packages follow Semantic Versioning. -# For more information, check out https://semver.org/. -install_requires = - importlib-metadata; python_version<"3.8" - sqlalchemy - biocframe - -[options.packages.find] -where = src -exclude = - tests - -[options.extras_require] -# Add here additional requirements for extra features, to install with: -# `pip install pyBiocFileCache[PDF]` like: -# PDF = ReportLab; RXP - -# Add here test requirements (semicolon/line-separated) -testing = - setuptools - pytest - pytest-cov - -[options.entry_points] -# Add here console scripts like: -# console_scripts = -# script_name = pybiocfilecache.module:function -# For example: -# console_scripts = -# fibonacci = pybiocfilecache.skeleton:run -# And any other entry points, for example: -# pyscaffold.cli = -# awesome = pyscaffoldext.awesome.extension:AwesomeExtension - -[tool:pytest] -# Specify command line options as you would do when invoking pytest directly. -# e.g. --cov-report html (or xml) for html/xml output or --junitxml junit.xml -# in order to write a coverage file that can be read by Jenkins. -# CAUTION: --cov flags may prohibit setting breakpoints while debugging. -# Comment those flags to avoid this pytest issue. -addopts = - --cov pybiocfilecache --cov-report term-missing - --verbose -norecursedirs = - dist - build - .tox -testpaths = tests -# Use pytest markers to select/deselect specific tests -# markers = -# slow: mark tests as slow (deselect with '-m "not slow"') -# system: mark end-to-end system tests - -[devpi:upload] -# Options for the devpi: PyPI server and packaging tool -# VCS export must be deactivated since we are using setuptools-scm -no_vcs = 1 -formats = bdist_wheel - -[flake8] -# Some sane defaults for the code style checker flake8 -max_line_length = 88 -extend_ignore = E203, W503 -# ^ Black-compatible -# E203 and W503 have edge cases handled by black -exclude = - .tox - build - dist - .eggs - docs/conf.py - -[pyscaffold] -# PyScaffold's parameters when the project was created. -# This will be used when updating. Do not change! -version = 4.1 -package = pybiocfilecache -extensions = - markdown diff --git a/setup.py b/setup.py deleted file mode 100644 index 2525df1..0000000 --- a/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Setup file for pyBiocFileCache. Use setup.cfg to configure your project. - -This file was generated with PyScaffold 4.1. -PyScaffold helps you to put up the scaffold of your new Python project. -Learn more under: https://pyscaffold.org/ -""" - -from setuptools import setup - -if __name__ == "__main__": - try: - setup(use_scm_version={"version_scheme": "no-guess-dev"}) - except: # noqa - print( - "\n\nAn error occurred while building the project, " - "please ensure you have the most updated version of setuptools, " - "setuptools_scm and wheel with:\n" - " pip install -U setuptools setuptools_scm wheel\n\n" - ) - raise diff --git a/src/pybiocfilecache/cache.py b/src/pybiocfilecache/cache.py index 3c13bda..f85cfe5 100644 --- a/src/pybiocfilecache/cache.py +++ b/src/pybiocfilecache/cache.py @@ -1,9 +1,13 @@ +from __future__ import annotations + import logging +import shutil +from collections.abc import Iterator from contextlib import contextmanager -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path from time import sleep, time -from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union +from typing import Any, Literal from biocframe import BiocFrame from sqlalchemy import create_engine, func, text @@ -30,6 +34,19 @@ logger = logging.getLogger(__name__) +def _now() -> datetime: + """Return current UTC time as a naive datetime matching SQLite CURRENT_TIMESTAMP.""" + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def _normalize_datetime(dt: datetime | None) -> datetime | None: + """Normalize an optional datetime to naive UTC.""" + if dt is not None and dt.tzinfo is not None: + return dt.astimezone(timezone.utc).replace(tzinfo=None) + + return dt + + class BiocFileCache: """Enhanced file caching module. @@ -39,7 +56,7 @@ class BiocFileCache: - Cleanup of expired resources """ - def __init__(self, cache_dir: Optional[Union[str, Path]] = None, config: Optional[CacheConfig] = None): + def __init__(self, cache_dir: str | Path | None = None, config: CacheConfig | None = None): """Initialize cache with optional configuration. Args: @@ -63,7 +80,7 @@ def __init__(self, cache_dir: Optional[Union[str, Path]] = None, config: Optiona if db_schema_version != SCHEMA_VERSION: raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.") - self._last_cleanup = datetime.now() + self._last_cleanup = _now() def _setup_cache_dir(self) -> bool: if not self.config.cache_dir.exists(): @@ -84,6 +101,7 @@ def _setup_database(self) -> None: self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine) with self.engine.connect() as conn: + self._ensure_autoincrement(conn) result = conn.execute( text(""" SELECT value FROM metadata @@ -106,7 +124,52 @@ def _setup_database(self) -> None: return SCHEMA_VERSION - def _get_detached_resource(self, session: Session, obj: Union[Resource, Metadata]) -> Optional[dict]: + def _ensure_autoincrement(self, conn) -> None: + """Migrate legacy resource table without AUTOINCREMENT so SQLite never reuses deleted row IDs.""" + row = conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='resource'")).fetchone() + if row is None or not row[0] or "AUTOINCREMENT" in row[0].upper(): + return + + dup_count = conn.execute( + text("SELECT COUNT(*) - COUNT(DISTINCT rid) FROM resource WHERE rid IS NOT NULL") + ).scalar() + unique_clause = ", UNIQUE (rid)" if not dup_count else "" + + cols = "id, rid, rname, create_time, access_time, rpath, rtype, fpath, last_modified_time, etag, expires" + conn.execute( + text( + f""" + CREATE TABLE resource_new ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + rid TEXT, + rname TEXT, + create_time DATETIME DEFAULT (CURRENT_TIMESTAMP), + access_time DATETIME DEFAULT (CURRENT_TIMESTAMP), + rpath TEXT, + rtype TEXT, + fpath TEXT, + last_modified_time DATETIME, + etag TEXT, + expires DATETIME{unique_clause} + ) + """ + ) + ) + conn.execute(text(f"INSERT INTO resource_new ({cols}) SELECT {cols} FROM resource")) + conn.execute(text("DROP TABLE resource")) + conn.execute(text("ALTER TABLE resource_new RENAME TO resource")) + conn.execute(text("CREATE INDEX IF NOT EXISTS ix_resource_id ON resource (id)")) + conn.commit() + + def _resolve_rpath(self, rpath: str, rtype: str | None) -> Path: + """Resolve a stored resource path against cache_dir when relative.""" + path = Path(rpath) + if rtype in ("relative", "web") and not path.is_absolute(): + return self.config.cache_dir / path + + return path + + def _get_detached_resource(self, session: Session, obj: Resource | Metadata) -> dict | None: """Get a detached copy of a resource.""" if obj is None: return None @@ -114,13 +177,12 @@ def _get_detached_resource(self, session: Session, obj: Union[Resource, Metadata session.expunge(obj) obj_dict = obj.to_dict() - if isinstance(obj, Resource): - if obj_dict["rtype"] == "relative": - obj_dict["rpath"] = f"{self.config.cache_dir}/{obj_dict['rpath']}" + if isinstance(obj, Resource) and obj_dict["rtype"] in ("relative", "web"): + obj_dict["rpath"] = str(self._resolve_rpath(obj_dict["rpath"], obj_dict["rtype"])) return obj_dict - def __enter__(self) -> "BiocFileCache": + def __enter__(self) -> BiocFileCache: return self def __exit__(self, exc_type, exc_val, exc_tb) -> None: @@ -161,7 +223,7 @@ def _should_cleanup(self) -> bool: if self.config.cleanup_interval is None: return False - return datetime.now() - self._last_cleanup > self.config.cleanup_interval + return _now() - self._last_cleanup > self.config.cleanup_interval def cleanup(self) -> int: """Remove expired resources from the cache. @@ -170,27 +232,25 @@ def cleanup(self) -> int: Number of resources removed. Note: - - If `cleanup_interval` is None, this method will still run if called explicitly. + - Runs whenever called explicitly, even if `cleanup_interval` is None. - Only removes resources with non-None expiration dates. """ - if not any([self.config.cleanup_interval, self._should_cleanup()]): - return 0 # Early return if automatic cleanup is disabled - removed = 0 + now = _now() with self.get_session() as session: # Only query resources that have expiration dates expired = ( session.query(Resource) .filter( Resource.expires.isnot(None), # Only check resources with expiration - Resource.expires < datetime.now(), + Resource.expires < now, ) .all() ) for resource in expired: try: - Path(resource.rpath).unlink(missing_ok=True) + self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True) session.delete(resource) removed += 1 except Exception as e: @@ -198,15 +258,22 @@ def cleanup(self) -> int: session.commit() - self._last_cleanup = datetime.now() + self._last_cleanup = now return removed ############################### ######>> get resources <<###### ############################### - def get(self, rname: str = None, rid: str = None) -> Optional[dict]: - """Get resource by name from cache. + def get( + self, + rname: str | None = None, + rid: str | None = None, + wait: bool = True, + timeout: float = 30, + update_access_time: bool = True, + ) -> dict | None: + """Get resource by name or id from cache. Args: rname: @@ -215,39 +282,123 @@ def get(self, rname: str = None, rid: str = None) -> Optional[dict]: rid: Resource id to search by. + wait: + Whether to wait for the cached file to exist on disk. + If False, returns the registered record immediately even if + the file is missing. Defaults to True. + + timeout: + Maximum seconds to wait when `wait=True`. Defaults to 30. + + update_access_time: + Whether to update `access_time` in the database when the + cached file exists. Set to False for read-only lookups. + Defaults to True. + """ if rname is None and rid is None: raise ValueError("either 'rname' or 'rid' must be provided.") with self.get_session() as session: - if rname is not None: - resource = session.query(Resource).filter(Resource.rname == rname).first() - elif rid is not None: + if rid is not None: resource = session.query(Resource).filter(Resource.rid == rid).first() + else: + resource = session.query(Resource).filter(Resource.rname == rname).first() if resource is not None: - # Check if path exists with timeout - start = time() - timeout = 30 - while not Path(str(self.config.cache_dir / resource.rpath)).exists(): - if time() - start >= timeout: - raise TimeoutError(f"For resource: '{rname}' the rpath does not exist after {timeout} seconds.") - sleep(0.1) - - # Update access time - resource.access_time = datetime.now() - session.commit() + resolved_path = self._resolve_rpath(resource.rpath, resource.rtype) + if wait: + start = time() + while not resolved_path.exists(): + if time() - start >= timeout: + identifier = rid if rid is not None else rname + raise TimeoutError( + f"For resource: '{identifier}' the rpath does not exist after {timeout} seconds." + ) + sleep(0.1) + + if update_access_time and resolved_path.exists(): + resource.access_time = _now() + session.commit() + return self._get_detached_resource(session, resource) return None + def _add_to_session( + self, + session: Session, + rname: str, + fpath: str | Path, + rtype: Literal["local", "web", "relative"] = "relative", + action: Literal["copy", "move", "asis"] = "copy", + expires: datetime | None = None, + download: bool = True, + ext: bool = True, + ) -> tuple[Resource, Path | None]: + """Insert a resource record and store its file within an active session.""" + if session.query(Resource).filter(Resource.rname == rname).first() is not None: + raise FileExistsError(f"Resource '{rname}' already exists") + + fpath_val = Path(fpath) if rtype != "web" else fpath + tmp_dir: Path | None = None + + if rtype == "web": + outpath = download_web_file(str(fpath_val), None, download) + tmp_dir = outpath.parent + action = "copy" + else: + outpath = Path(fpath_val) + + if action == "asis": + if rtype != "local": + logger.warning("If action='asis', rtype must be 'local'.") + rtype = "local" + elif rtype == "local": + rtype = "relative" + + uuid_str = generate_uuid() + rpath = f"{uuid_str}_{outpath.name if ext else outpath.stem}" if action != "asis" else str(fpath_val) + + resource = Resource( + rid=None, + rname=rname, + rpath=str(rpath), + rtype=rtype, + fpath=str(fpath_val), + expires=_normalize_datetime(expires), + ) + + copied_target: Path | None = None + try: + session.add(resource) + session.flush() + resource.rid = generate_id(resource.id) + + target_path = self._resolve_rpath(resource.rpath, resource.rtype) + copy_or_move(outpath, target_path, rname, action, False) + if action != "asis": + copied_target = target_path + + resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm) + + return resource, copied_target + except Exception: + if copied_target is not None and copied_target.exists(): + copied_target.unlink(missing_ok=True) + + raise + finally: + if tmp_dir is not None: + shutil.rmtree(tmp_dir, ignore_errors=True) + def add( self, rname: str, - fpath: Union[str, Path], + fpath: str | Path, rtype: Literal["local", "web", "relative"] = "relative", action: Literal["copy", "move", "asis"] = "copy", - expires: Optional[datetime] = None, + expires: datetime | None = None, download: bool = True, ext: bool = True, ) -> dict: @@ -263,7 +414,7 @@ def add( rtype: Type of resource. One of ``local``, ``web``, or ``relative``. - Defaults to ``local``. + Defaults to ``relative``. action: How to handle the file ("copy", "move", or "asis"). @@ -284,80 +435,65 @@ def add( Returns: The `Resource` object added to the cache as dictionary. """ - # self._validate_rname(rname) - fpath = Path(fpath) if rtype != "web" else fpath - - if self.get(rname) is not None: - raise FileExistsError(f"Resource '{rname}' already exists") - - if rtype == "web": - outpath = download_web_file(fpath, Path(fpath).name, download) - action = "copy" - else: - outpath = Path(fpath) - - if action == "asis": - logger.warning("If action='asis', rtype must be 'local'.") - rtype = "local" - - # Generate paths and check size - rid = generate_id(size=len(self)) - uuid = generate_uuid() - rpath = f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath - - # Create resource record - resource = Resource( - rid=rid, - rname=rname, - rpath=str(rpath), - rtype=rtype, - fpath=str(fpath), - expires=expires, - ) - - # Store file and update database with self.get_session() as session: - session.add(resource) - session.commit() - try: - copy_or_move(outpath, self.config.cache_dir / rpath, rname, action, False) - - # Calculate and store checksum - resource.etag = calculate_file_hash(self.config.cache_dir / rpath, self.config.hash_algorithm) + resource, _ = self._add_to_session( + session=session, + rname=rname, + fpath=fpath, + rtype=rtype, + action=action, + expires=expires, + download=download, + ext=ext, + ) session.commit() - result = self._get_detached_resource(session, resource) - return result + return self._get_detached_resource(session, resource) + except FileExistsError: + session.rollback() + raise except Exception as e: - session.delete(resource) - session.commit() + session.rollback() raise Exception("Failed to add resource") from e - def add_batch(self, resources: List[Dict[str, Any]]) -> BiocFrame: + def add_batch(self, resources: list[dict[str, Any]]) -> BiocFrame: """Add multiple resources in a single transaction. Args: resources: List of resources to add. """ - results = [] + added_resources: list[Resource] = [] + copied_targets: list[Path] = [] with self.get_session() as session: - for resource_info in resources: - try: - resource = self.add(**resource_info) - results.append(resource) - except Exception as e: - logger.error(f"Failed to add resource: {resource_info.get('rname')}", exc_info=e) - session.rollback() - raise - return results + try: + for resource_info in resources: + resource, copied_target = self._add_to_session(session=session, **resource_info) + added_resources.append(resource) + if copied_target is not None: + copied_targets.append(copied_target) + + session.commit() + + return BiocFrame( + convert_to_columnar([self._get_detached_resource(session, r) for r in added_resources]) + ) + except Exception as e: + logger.error("Failed to add batch of resources", exc_info=e) + session.rollback() + + for target in copied_targets: + target.unlink(missing_ok=True) + + raise def update( self, - rname: str, - fpath: Union[str, Path], + rname: str | None = None, + fpath: str | Path = None, action: Literal["copy", "move", "asis"] = "copy", + rid: str | None = None, ) -> dict: """Update an existing resource. @@ -372,36 +508,62 @@ def update( Either ``copy``, ``move`` or ``asis``. Defaults to ``copy``. + rid: + Optional resource id to identify the resource. + Returns: Updated `Resource` object as dictionary. """ + if rname is None and rid is None: + raise ValueError("either 'rname' or 'rid' must be provided.") + + if fpath is None: + raise ValueError("'fpath' must be provided.") + fpath = Path(fpath) if not fpath.exists(): raise FileNotFoundError(f"File '{fpath}' does not exist") with self.get_session() as session: - resource = session.query(Resource).filter(Resource.rname == rname).first() + if rid is not None: + resource = session.query(Resource).filter(Resource.rid == rid).first() + else: + resource = session.query(Resource).filter(Resource.rname == rname).first() if resource is None: + if rname is None: + raise KeyError(f"Resource with rid '{rid}' not found") return self.add(rname=rname, fpath=fpath, action=action) - old_path = Path(resource.rpath) try: - copy_or_move(fpath, old_path, rname, action, False) + if action == "asis": + resource.rpath = str(fpath) + resource.rtype = "local" + target_path = fpath + else: + if resource.rtype == "local": + resource.rtype = "relative" + resource.rpath = f"{generate_uuid()}_{fpath.name}" + + target_path = self._resolve_rpath(resource.rpath, resource.rtype) + copy_or_move(fpath, target_path, resource.rname, action, False) - resource.last_modified_time = datetime.now() - resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm) + resource.fpath = str(fpath) + resource.last_modified_time = _now() + resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm) session.commit() + return self._get_detached_resource(session, resource) except Exception as e: session.rollback() + raise Exception("Failed to update resource") from e - def remove(self, rname: str) -> None: - """Remove a resource from cache by name. + def remove(self, rname: str | None = None, rid: str | None = None) -> None: + """Remove a resource from cache by name or id. Removes both the cached file and its database entry. @@ -409,16 +571,25 @@ def remove(self, rname: str) -> None: rname: Name to identify the resource in cache. + rid: + Resource id to identify the resource in cache. + Raises: Exception: If resource removal fails """ + if rname is None and rid is None: + raise ValueError("either 'rname' or 'rid' must be provided.") + with self.get_session() as session: - resource = session.query(Resource).filter(Resource.rname == rname).first() + if rid is not None: + resource = session.query(Resource).filter(Resource.rid == rid).first() + else: + resource = session.query(Resource).filter(Resource.rname == rname).first() if resource is not None: try: # Try to remove the file first - rpath = Path(resource.rpath) + rpath = self._resolve_rpath(resource.rpath, resource.rtype) if rpath.exists(): rpath.unlink() @@ -428,9 +599,10 @@ def remove(self, rname: str) -> None: except Exception as e: session.rollback() - raise Exception(f"Failed to remove resource '{rname}'") from e + identifier = rid if rid is not None else rname + raise Exception(f"Failed to remove resource '{identifier}'") from e - def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> BiocFrame: + def list_resources(self, rtype: str | None = None, expired: bool | None = None) -> BiocFrame: """List resources in the cache with optional filtering. Args: @@ -454,38 +626,52 @@ def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = if rtype: query = query.filter(Resource.rtype == rtype) if expired is not None: + now = _now() if expired: query = query.filter( Resource.expires.isnot(None), # Only check resources with expiration - Resource.expires < datetime.now(), + Resource.expires < now, ) else: query = query.filter( (Resource.expires.is_(None)) # Never expires - | (Resource.expires > datetime.now()) # Not yet expired + | (Resource.expires > now) # Not yet expired ) resources = query.all() return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources])) - def validate_resource(self, resource: Resource) -> bool: + def validate_resource(self, resource: Resource | dict) -> bool: """Validate resource integrity. Args: resource: - Resource to validate. + Resource ORM object or dictionary to validate. Returns: True if resource is valid, False otherwise. """ - if not resource.etag: + if isinstance(resource, dict): + etag = resource.get("etag") + rpath = resource.get("rpath") + rtype = resource.get("rtype") + rname = resource.get("rname") + else: + etag = resource.etag + rpath = resource.rpath + rtype = resource.rtype + rname = resource.rname + + if not etag: return True # No validation if no checksum try: - current_hash = calculate_file_hash(Path(resource.rpath), self.config.hash_algorithm) - return current_hash == resource.etag + resolved_path = self._resolve_rpath(rpath, rtype) + current_hash = calculate_file_hash(resolved_path, self.config.hash_algorithm) + + return current_hash == etag except Exception as e: - logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e) + logger.error(f"Failed to validate resource: {rname}", exc_info=e) return False # def export_metadata(self, path: Path) -> None: @@ -521,18 +707,20 @@ def validate_resource(self, resource: Resource) -> bool: # session.merge(resource) # session.commit() - def verify_cache(self) -> Tuple[int, int]: + def verify_cache(self) -> tuple[int, int]: """Verify integrity of all cached resources. Returns: Tuple of (valid_count, invalid_count). """ valid = invalid = 0 - for resource in self.list_resources(): - if self.validate_resource(resource): - valid += 1 - else: - invalid += 1 + with self.get_session() as session: + for resource in session.query(Resource).all(): + if self.validate_resource(resource): + valid += 1 + else: + invalid += 1 + return valid, invalid def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame: @@ -549,17 +737,21 @@ def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocF Whether to require exact match. Returns: - List of matching resources. + BiocFrame of matching resources. """ + if field not in Resource.__table__.columns: + raise ValueError(f"Invalid search field: '{field}'") + + column = getattr(Resource, field) with self.get_session() as session: if exact: - resources = session.query(Resource).filter(Resource[field] == query).all() + resources = session.query(Resource).filter(column == query).all() else: - resources = session.query(Resource).filter(Resource[field].ilike(f"%{query}%")).all() + resources = session.query(Resource).filter(column.ilike(f"%{query}%")).all() return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources])) - def get_stats(self) -> Dict[str, Any]: + def get_stats(self) -> dict[str, Any]: """Get statistics about the cache.""" with self.get_session() as session: total = session.query(Resource).count() @@ -567,7 +759,7 @@ def get_stats(self) -> Dict[str, Any]: session.query(Resource) .filter( Resource.expires.isnot(None), # Only check resources with expiration - Resource.expires < datetime.now(), + Resource.expires < _now(), ) .count() ) @@ -602,7 +794,7 @@ def purge(self, force: bool = False) -> bool: for resource in resources: try: - Path(resource.rpath).unlink(missing_ok=True) + self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True) except Exception as e: if not force: session.rollback() @@ -622,7 +814,7 @@ def purge(self, force: bool = False) -> bool: except Exception as e: logger.warning(f"Failed to remove {file}: {e}") - self._last_cleanup = datetime.now() + self._last_cleanup = _now() return True except Exception as e: diff --git a/src/pybiocfilecache/config.py b/src/pybiocfilecache/config.py index e2dc88e..15b88fd 100644 --- a/src/pybiocfilecache/config.py +++ b/src/pybiocfilecache/config.py @@ -1,7 +1,6 @@ from dataclasses import dataclass from datetime import timedelta from pathlib import Path -from typing import Optional __author__ = "Jayaram Kancherla" __copyright__ = "Jayaram Kancherla" @@ -28,6 +27,6 @@ class CacheConfig: """ cache_dir: Path - cleanup_interval: Optional[timedelta] = None # timedelta(days=30) + cleanup_interval: timedelta | None = None # timedelta(days=30) rname_pattern: str = r"^[a-zA-Z0-9_-]+$" hash_algorithm: str = "md5" diff --git a/src/pybiocfilecache/models.py b/src/pybiocfilecache/models.py index aa414f4..a69050c 100644 --- a/src/pybiocfilecache/models.py +++ b/src/pybiocfilecache/models.py @@ -62,9 +62,10 @@ class Resource(Base): """ __tablename__ = "resource" + __table_args__ = {"sqlite_autoincrement": True} id = Column(Integer, primary_key=True, index=True, autoincrement=True) - rid = Column(Text()) + rid = Column(Text(), unique=True) rname = Column(Text()) create_time = Column(DateTime, server_default=func.now()) access_time = Column(DateTime, server_default=func.now()) diff --git a/src/pybiocfilecache/py.typed b/src/pybiocfilecache/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/pybiocfilecache/utils.py b/src/pybiocfilecache/utils.py index 4295af6..49a59c8 100644 --- a/src/pybiocfilecache/utils.py +++ b/src/pybiocfilecache/utils.py @@ -7,7 +7,8 @@ import zlib from pathlib import Path from shutil import copy2, move -from typing import List, Literal +from typing import Literal +from urllib.parse import urlparse __author__ = "Jayaram Kancherla" __copyright__ = "Jayaram Kancherla" @@ -26,10 +27,9 @@ def generate_uuid() -> str: return uuid.uuid4().hex -def generate_id(size) -> str: - """Generate unique identifier.""" - size += 1 - return "BFC" + str(size) +def generate_id(row_id: int) -> str: + """Generate unique resource identifier from database row id.""" + return f"BFC{row_id}" def validate_rname(rname: str, pattern: str) -> bool: @@ -43,6 +43,7 @@ def calculate_file_hash(path: Path, algorithm: str = "md5") -> str: with open(path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) + return hasher.hexdigest() @@ -88,7 +89,13 @@ def copy_or_move( raise Exception(f"Failed to store resource '{rname}' from '{source}' to '{target}'") from e -def download_web_file(url: str, filename: str, download: bool): +def download_web_file(url: str, filename: str | None = None, download: bool = True) -> Path: + """Download a web resource into a temporary directory.""" + + if not filename: + parsed_name = Path(urlparse(str(url)).path).name + filename = parsed_name or "download" + tmp_dir = create_tmp_dir() outpath = tmp_dir / filename if download: @@ -99,7 +106,7 @@ def download_web_file(url: str, filename: str, download: bool): return outpath -def convert_to_columnar(list_of_dicts: List[dict]): +def convert_to_columnar(list_of_dicts: list[dict]): if not list_of_dicts: return {} @@ -109,4 +116,5 @@ def convert_to_columnar(list_of_dicts: List[dict]): for row in list_of_dicts: for col in column_names: result[col].append(row.get(col)) + return result diff --git a/tests/test_cache.py b/tests/test_cache.py index 93c2467..c6018c3 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -1,102 +1,124 @@ import os import shutil - -from datetime import timedelta -from pybiocfilecache import BiocFileCache, CacheConfig +import sqlite3 +import urllib.request +from datetime import datetime, timedelta, timezone from pathlib import Path + import pytest -import tempfile +from biocframe import BiocFrame + +from pybiocfilecache import BiocFileCache, CacheConfig __author__ = "jkanche" __copyright__ = "jkanche" __license__ = "MIT" -CACHE_DIR = tempfile.mkdtemp() + "/cache" +def _mock_urlretrieve(monkeypatch, content: str = "web content"): + def fake_urlretrieve(url, filename, *args, **kwargs): + Path(filename).write_text(content) + return (filename, None) -def test_create_cache(): - bfc = BiocFileCache(CACHE_DIR) - assert os.path.exists(CACHE_DIR) + monkeypatch.setattr(urllib.request, "urlretrieve", fake_urlretrieve) - bfc.check_metadata_key("schema_version") +def test_create_cache(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + assert cache_dir.exists() + assert bfc.check_metadata_key("schema_version") bfc.purge() -def test_add_get_list_operations(): - bfc = BiocFileCache(CACHE_DIR) +def test_add_get_list_operations(tmp_path, monkeypatch): + _mock_urlretrieve(monkeypatch, "stats content") + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) - rtrip = bfc.add("test1", os.getcwd() + "/tests/data/test1.txt") + bfc.add("test1", os.getcwd() + "/tests/data/test1.txt") rec1 = bfc.get("test1") assert rec1 is not None + assert Path(rec1["rpath"]).parent == cache_dir bfc.add("test2", os.getcwd() + "/tests/data/test2.txt") rec2 = bfc.get("test2") assert rec2 is not None - frec1 = open(rec1["rpath"], "r").read().strip() - assert frec1 == "test1" + assert Path(rec1["rpath"]).read_text().strip() == "test1" + assert Path(rec2["rpath"]).read_text().strip() == "test2" - frec2 = open(rec2["rpath"], "r").read().strip() - assert frec2 == "test2" - - shutil.copy(os.getcwd() + "/tests/data/test2.txt", os.getcwd() + "/tests/data/test3.txt") - bfc.add("test3_asis", os.getcwd() + "/tests/data/test3.txt", action="asis") + asis_src = tmp_path / "test3.txt" + shutil.copy(os.getcwd() + "/tests/data/test2.txt", asis_src) + bfc.add("test3_asis", asis_src, action="asis") rec3 = bfc.get("test3_asis") assert rec3 is not None - assert rec3["rpath"] == os.getcwd() + "/tests/data/test3.txt" - - frec3 = open(rec3["rpath"], "r").read().strip() - assert frec3 == "test2" + assert rec3["rpath"] == str(asis_src) + assert rec3["rtype"] == "local" + assert Path(rec3["rpath"]).read_text().strip() == "test2" rtrip = bfc.list_resources() assert len(rtrip) == 3 - downurl = "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab" + downurl = "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab?foo=bar" add_url = bfc.add(rname="download_link", fpath=downurl, rtype="web") + assert add_url["rtype"] == "web" + assert Path(add_url["rpath"]).parent == cache_dir + assert Path(add_url["rpath"]).exists() row = bfc.get(rid=add_url["rid"]) assert row["fpath"] == downurl + assert Path(row["rpath"]).read_text() == "stats content" rtrip = bfc.list_resources() assert len(rtrip) == 4 - bfc.purge() + assert bfc.purge() + assert not Path(rec1["rpath"]).exists() + assert not Path(add_url["rpath"]).exists() -def test_remove_operations(): - bfc = BiocFileCache(CACHE_DIR) +def test_remove_operations(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) bfc.add("test1", os.getcwd() + "/tests/data/test1.txt") rec1 = bfc.get("test1") assert rec1 is not None + assert Path(rec1["rpath"]).exists() bfc.add("test2", os.getcwd() + "/tests/data/test2.txt") rec2 = bfc.get("test2") assert rec2 is not None + assert Path(rec2["rpath"]).exists() bfc.remove("test1") - rec1 = bfc.get("test1") - assert rec1 is None + assert bfc.get("test1") is None + assert not Path(rec1["rpath"]).exists() + + bfc.remove(rid=rec2["rid"]) + assert bfc.get(rid=rec2["rid"]) is None + assert not Path(rec2["rpath"]).exists() bfc.purge() -def test_meta_operations(): - bfc = BiocFileCache(CACHE_DIR) + +def test_meta_operations(tmp_path, monkeypatch): + _mock_urlretrieve(monkeypatch) + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) bfc.add("test1", os.getcwd() + "/tests/data/test1.txt") - rec1 = bfc.get("test1") - assert rec1 is not None + assert bfc.get("test1") is not None with pytest.raises(Exception): bfc.add_metadata("schema_version", "something") - bfc.check_metadata_key("schema_version") - + assert bfc.check_metadata_key("schema_version") bfc.add_metadata("language", "python") downurl = "https://bioconductor.org/packages/stats/bioc/BiocFileCache/BiocFileCache_2024_stats.tab" - add_url = bfc.add(rname="download_link", fpath=downurl, rtype="web") + bfc.add(rname="download_link", fpath=downurl, rtype="web") rec = bfc.get_metadata("schema_version") assert rec["value"] == "0.99.4" @@ -109,31 +131,240 @@ def test_meta_operations(): bfc.purge() -def test_cache_with_config(): - # Create custom configuration + +def test_cache_with_config(tmp_path): + cache_dir = tmp_path / "cache" config = CacheConfig( - cache_dir=Path(CACHE_DIR), + cache_dir=cache_dir, cleanup_interval=timedelta(days=7), ) bfc = BiocFileCache(config=config) - - bfc.check_metadata_key("schema_version") + assert bfc.check_metadata_key("schema_version") bfc.add("test1", os.getcwd() + "/tests/data/test1.txt") rec1 = bfc.get("test1") assert rec1 is not None - rtrip = bfc.list_resources() - assert len(rtrip) == 1 + assert len(bfc.list_resources()) == 1 - bfc.update("test1", os.getcwd() + "/tests/data/test2.txt") - rec1 = bfc.get("test1") - assert rec1 is not None + updated = bfc.update("test1", os.getcwd() + "/tests/data/test2.txt") + assert Path(updated["rpath"]).read_text().strip() == "test2" + assert Path(rec1["rpath"]).read_text().strip() == "test2" - rtrip = bfc.list_resources() - assert len(rtrip) == 1 + assert len(bfc.list_resources()) == 1 bfc.cleanup() + bfc.purge() + + +def test_unique_monotonic_rids_after_deletions(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + src = Path(os.getcwd()) / "tests/data/test1.txt" + + r1 = bfc.add("r1", src) + r2 = bfc.add("r2", src) + r3 = bfc.add("r3", src) + assert [r1["rid"], r2["rid"], r3["rid"]] == ["BFC1", "BFC2", "BFC3"] + + # Remove middle entry and add a fourth: must not collide with BFC3 + bfc.remove("r2") + r4 = bfc.add("r4", src) + assert r4["rid"] == "BFC4" + + # Remove last entry and add a fifth: sqlite_autoincrement must prevent reuse of BFC4 + bfc.remove(rid="BFC4") + r5 = bfc.add("r5", src) + assert r5["rid"] == "BFC5" + + bfc.purge() + + +def test_get_wait_false_for_missing_file(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + rec = bfc.add("missing_test", os.getcwd() + "/tests/data/test1.txt") + cached_file = Path(rec["rpath"]) + cached_file.unlink() + assert not cached_file.exists() + + # wait=False returns immediately with the registered path so caller can repair it + immediate = bfc.get("missing_test", wait=False) + assert immediate is not None + assert immediate["rpath"] == rec["rpath"] + + # Repair the missing file + cached_file.write_text("repaired") + repaired = bfc.get("missing_test") + assert Path(repaired["rpath"]).read_text() == "repaired" + + # wait=True with short timeout raises TimeoutError with identifier + cached_file.unlink() + with pytest.raises(TimeoutError, match=rec["rid"]): + bfc.get(rid=rec["rid"], wait=True, timeout=0.1) + + bfc.purge() + + +def test_search_exact_and_partial(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + bfc.add("alpha_sample", os.getcwd() + "/tests/data/test1.txt") + bfc.add("beta_sample", os.getcwd() + "/tests/data/test2.txt") + + exact_res = bfc.search("alpha_sample", field="rname", exact=True) + assert isinstance(exact_res, BiocFrame) + assert len(exact_res) == 1 + assert exact_res.get_column("rname")[0] == "alpha_sample" + + partial_res = bfc.search("sample", field="rname", exact=False) + assert len(partial_res) == 2 + + rid_res = bfc.search("BFC2", field="rid", exact=True) + assert len(rid_res) == 1 + assert rid_res.get_column("rname")[0] == "beta_sample" + + empty_res = bfc.search("nonexistent", field="rname", exact=True) + assert len(empty_res) == 0 + + with pytest.raises(ValueError, match="Invalid search field"): + bfc.search("foo", field="not_a_column") + + bfc.purge() + + +def test_cleanup_removes_expired_without_interval(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + past = datetime.now(timezone.utc) - timedelta(hours=1) + future = datetime.now(timezone.utc) + timedelta(hours=1) + + expired_rec = bfc.add("expired_item", os.getcwd() + "/tests/data/test1.txt", expires=past) + valid_rec = bfc.add("valid_item", os.getcwd() + "/tests/data/test2.txt", expires=future) + + removed = bfc.cleanup() + assert removed == 1 + assert not Path(expired_rec["rpath"]).exists() + assert Path(valid_rec["rpath"]).exists() + assert bfc.get("expired_item", wait=False) is None + assert bfc.get("valid_item") is not None + + bfc.purge() + + +def test_verify_cache_and_validate_resource(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + r1 = bfc.add("ok", os.getcwd() + "/tests/data/test1.txt") + r2 = bfc.add("corrupt", os.getcwd() + "/tests/data/test2.txt") + + assert bfc.verify_cache() == (2, 0) + assert bfc.validate_resource(r1) is True + + Path(r2["rpath"]).write_text("tampered") + assert bfc.verify_cache() == (1, 1) + assert bfc.validate_resource(r2) is False + + bfc.purge() + + +def test_add_batch_atomicity(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + good_src = Path(os.getcwd()) / "tests/data/test1.txt" + missing_src = tmp_path / "does_not_exist.txt" + + # Successful batch returns BiocFrame + res = bfc.add_batch( + [ + {"rname": "b1", "fpath": good_src}, + {"rname": "b2", "fpath": good_src}, + ] + ) + assert isinstance(res, BiocFrame) + assert len(res) == 2 + + # Failing batch rolls back DB and deletes copied files + with pytest.raises(Exception): + bfc.add_batch( + [ + {"rname": "b3", "fpath": good_src}, + {"rname": "b4", "fpath": missing_src}, + ] + ) + + assert bfc.get("b3", wait=False) is None + assert len(bfc) == 2 + + bfc.purge() + + +def test_legacy_db_migrates_to_autoincrement(tmp_path): + cache_dir = tmp_path / "legacy_cache" + cache_dir.mkdir() + db_path = cache_dir / "BiocFileCache.sqlite" + + # Simulate a 0.7.0 database created without AUTOINCREMENT on resource.id + conn = sqlite3.connect(db_path) + conn.execute("CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT)") + conn.execute("INSERT INTO metadata (key, value) VALUES ('schema_version', '0.99.4')") + conn.execute( + """ + CREATE TABLE resource ( + id INTEGER NOT NULL, + rid TEXT, + rname TEXT, + create_time DATETIME DEFAULT (CURRENT_TIMESTAMP), + access_time DATETIME DEFAULT (CURRENT_TIMESTAMP), + rpath TEXT, + rtype TEXT, + fpath TEXT, + last_modified_time DATETIME, + etag TEXT, + expires DATETIME, + PRIMARY KEY (id) + ) + """ + ) + for idx in (1, 2, 3): + fname = f"file_{idx}.txt" + (cache_dir / fname).write_text(f"content {idx}") + conn.execute( + "INSERT INTO resource (id, rid, rname, rpath, rtype, fpath) VALUES (?, ?, ?, ?, 'relative', ?)", + (idx, f"BFC{idx}", f"r{idx}", fname, fname), + ) + conn.commit() + conn.close() + + # Reopen with 0.8.0: deleting the highest ID (BFC3) must not reuse BFC3 + bfc = BiocFileCache(cache_dir) + bfc.remove(rid="BFC3") + r4 = bfc.add("r4", Path(os.getcwd()) / "tests/data/test1.txt") + assert r4["rid"] == "BFC4" + bfc.purge() + + +def test_get_read_only_and_missing_file_access_time(tmp_path): + cache_dir = tmp_path / "cache" + bfc = BiocFileCache(cache_dir) + + rec = bfc.add("item", os.getcwd() + "/tests/data/test1.txt") + initial_access_time = rec["access_time"] + + # update_access_time=False performs a read-only lookup + ro_rec = bfc.get("item", update_access_time=False) + assert ro_rec["access_time"] == initial_access_time + + # wait=False on a missing file does not advance access_time + Path(rec["rpath"]).unlink() + missing_rec = bfc.get("item", wait=False) + assert missing_rec is not None + assert missing_rec["access_time"] == initial_access_time bfc.purge() diff --git a/tests/test_r_interop.py b/tests/test_r_interop.py new file mode 100644 index 0000000..8523a79 --- /dev/null +++ b/tests/test_r_interop.py @@ -0,0 +1,146 @@ +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +from pybiocfilecache import BiocFileCache + + +def _r_has_biocfilecache() -> bool: + if shutil.which("Rscript") is None: + return False + res = subprocess.run( + ["Rscript", "-e", "quit(status = ifelse(requireNamespace('BiocFileCache', quietly = TRUE), 0, 1))"], + capture_output=True, + text=True, + ) + return res.returncode == 0 + + +pytestmark = pytest.mark.skipif( + not _r_has_biocfilecache(), + reason="Rscript with BiocFileCache package is required for R interop tests", +) + + +def _run_r(script: str) -> subprocess.CompletedProcess: + res = subprocess.run( + ["Rscript", "-e", script], + capture_output=True, + text=True, + ) + if res.returncode != 0: + raise RuntimeError(f"Rscript failed (exit {res.returncode}):\nSTDOUT:\n{res.stdout}\nSTDERR:\n{res.stderr}") + return res + + +def test_python_then_r_roundtrip(tmp_path): + cache_dir = tmp_path / "shared_cache" + src1 = Path(os.getcwd()) / "tests/data/test1.txt" + src2 = Path(os.getcwd()) / "tests/data/test2.txt" + asis_src = tmp_path / "asis.txt" + asis_src.write_text("asis_content\n") + + # 1. Python creates cache and adds/removes resources + bfc = BiocFileCache(cache_dir) + r1 = bfc.add("py_rel1", src1) + r2 = bfc.add("py_rel2", src2) + r3 = bfc.add("py_asis", asis_src, action="asis") + assert [r1["rid"], r2["rid"], r3["rid"]] == ["BFC1", "BFC2", "BFC3"] + + bfc.remove("py_rel2") + r4 = bfc.add("py_rel3", src2) + assert r4["rid"] == "BFC4" + bfc.close() + + # 2. R opens the Python-created cache, verifies entries, adds & removes + r_src = tmp_path / "from_r.txt" + r_src.write_text("from_r_content\n") + + _run_r( + f""" + library(BiocFileCache) + bfc <- BiocFileCache("{cache_dir.as_posix()}", ask = FALSE) + info <- bfcinfo(bfc) + stopifnot(setequal(info$rid, c("BFC1", "BFC3", "BFC4"))) + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC1"), warn = FALSE)[1]) == "test1") + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC3"), warn = FALSE)[1]) == "asis_content") + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC4"), warn = FALSE)[1]) == "test2") + + new_path <- bfcadd(bfc, "r_rel1", fpath = "{r_src.as_posix()}", rtype = "relative", action = "copy") + new_rid <- names(new_path) + stopifnot(new_rid == "BFC5") + bfcremove(bfc, "BFC1") + """ + ) + + # 3. Python reads R's changes and adds another resource + bfc2 = BiocFileCache(cache_dir) + assert bfc2.get(rid="BFC1", wait=False) is None + r_added = bfc2.get(rid="BFC5") + assert r_added is not None + assert r_added["rname"] == "r_rel1" + assert Path(r_added["rpath"]).read_text().strip() == "from_r_content" + + r6 = bfc2.add("py_after_r", src1) + assert r6["rid"] == "BFC6" + bfc2.close() + + # 4. R verifies Python's new entry + _run_r( + f""" + library(BiocFileCache) + bfc <- BiocFileCache("{cache_dir.as_posix()}", ask = FALSE) + info <- bfcinfo(bfc) + stopifnot("BFC6" %in% info$rid) + stopifnot(!("BFC1" %in% info$rid)) + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC6"), warn = FALSE)[1]) == "test1") + """ + ) + + +def test_r_then_python_roundtrip(tmp_path): + cache_dir = tmp_path / "r_first_cache" + src1 = Path(os.getcwd()) / "tests/data/test1.txt" + src2 = Path(os.getcwd()) / "tests/data/test2.txt" + + # 1. R initializes cache and populates entries with a deletion + _run_r( + f""" + library(BiocFileCache) + bfc <- BiocFileCache("{cache_dir.as_posix()}", ask = FALSE) + bfcadd(bfc, "r1", fpath = "{src1.as_posix()}", rtype = "relative", action = "copy") + bfcadd(bfc, "r2", fpath = "{src2.as_posix()}", rtype = "relative", action = "copy") + bfcadd(bfc, "r3", fpath = "{src1.as_posix()}", rtype = "relative", action = "copy") + bfcremove(bfc, "BFC2") + bfcadd(bfc, "r4", fpath = "{src2.as_posix()}", rtype = "relative", action = "copy") + """ + ) + + # 2. Python reads, searches, updates, removes, and adds + bfc = BiocFileCache(cache_dir) + assert len(bfc) == 3 + assert len(bfc.search("r1", field="rname", exact=True)) == 1 + assert Path(bfc.get(rid="BFC1")["rpath"]).read_text().strip() == "test1" + assert Path(bfc.get(rid="BFC4")["rpath"]).read_text().strip() == "test2" + + p1 = bfc.add("py_from_r_cache", src1) + assert p1["rid"] == "BFC5" + + bfc.update(rid="BFC1", fpath=src2) + bfc.remove(rid="BFC3") + bfc.close() + + # 3. R verifies Python's updates and deletions + _run_r( + f""" + library(BiocFileCache) + bfc <- BiocFileCache("{cache_dir.as_posix()}", ask = FALSE) + info <- bfcinfo(bfc) + stopifnot(setequal(info$rid, c("BFC1", "BFC4", "BFC5"))) + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC1"), warn = FALSE)[1]) == "test2") + stopifnot(trimws(readLines(bfcrpath(bfc, rids = "BFC5"), warn = FALSE)[1]) == "test1") + """ + ) diff --git a/tox.ini b/tox.ini index fe005ad..b08857b 100644 --- a/tox.ini +++ b/tox.ini @@ -1,72 +1,62 @@ -# Tox configuration file -# Read more under https://tox.readthedocs.io/ -# THIS SCRIPT IS SUPPOSED TO BE AN EXAMPLE. MODIFY IT ACCORDING TO YOUR NEEDS! +# Tox configuration file using uv as the backend runner +# Read more under https://tox.wiki/ [tox] -minversion = 3.15 +minversion = 4.0 envlist = default -isolated_build = True - [testenv] description = Invoke pytest to run automated tests -setenv = - TOXINIDIR = {toxinidir} -passenv = - HOME -extras = - testing +extras = testing commands = pytest {posargs} +[testenv:typecheck] +deps = mypy +description = Run static type checking with mypy +commands = + mypy src/ + +[testenv:lint] +description = Perform static analysis and style checks +deps = ruff +skip_install = True +commands = + ruff check {posargs:.} + ruff format --check {posargs:.} [testenv:{build,clean}] description = - build: Build the package in isolation according to PEP517, see https://github.com/pypa/build - clean: Remove old distribution files and temporary build artifacts (./build and ./dist) -# NOTE: build is still experimental, please refer to the links for updates/issues -# https://setuptools.readthedocs.io/en/stable/build_meta.html#how-to-use-it -# https://github.com/pypa/pep517/issues/91 + build: Build the package + clean: Remove old distribution files +deps = build skip_install = True -changedir = {toxinidir} -deps = - build: build[virtualenv] commands = - clean: python -c 'from shutil import rmtree; rmtree("build", True); rmtree("dist", True)' - build: python -m build . -# By default `build` produces wheels, you can also explicitly use the flags `--sdist` and `--wheel` - + clean: python -c 'import shutil; [shutil.rmtree(p, True) for p in ("build", "dist", "docs/_build")]' + clean: python -c 'import pathlib, shutil; [shutil.rmtree(p, True) for p in pathlib.Path("src").glob("*.egg-info")]' + build: python -m build {posargs} [testenv:{docs,doctests,linkcheck}] description = docs: Invoke sphinx-build to build the docs doctests: Invoke sphinx-build to run doctests linkcheck: Check for broken links in the documentation +deps = + -r {toxinidir}/docs/requirements.txt setenv = DOCSDIR = {toxinidir}/docs BUILDDIR = {toxinidir}/docs/_build docs: BUILD = html doctests: BUILD = doctest linkcheck: BUILD = linkcheck -deps = - -r {toxinidir}/docs/requirements.txt - # ^ requirements.txt shared with Read The Docs commands = + sphinx-apidoc -f -o "{env:DOCSDIR}/api" src/ sphinx-build --color -b {env:BUILD} -d "{env:BUILDDIR}/doctrees" "{env:DOCSDIR}" "{env:BUILDDIR}/{env:BUILD}" {posargs} - [testenv:publish] description = Publish the package you have been developing to a package index server. - By default, it uses testpypi. If you really want to publish your package - to be publicly accessible in PyPI, use the `-- --repository pypi` option. skip_install = True -changedir = {toxinidir} -passenv = - TWINE_USERNAME - TWINE_PASSWORD - TWINE_REPOSITORY deps = twine commands = - python -m twine check dist/* - python -m twine upload {posargs:--repository testpypi} dist/* + python -m twine upload {posargs:dist/*}