pyBiocFileCache 0.5.2.dev1__tar.gz → 0.6.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. pybiocfilecache-0.6.1/.github/workflows/publish-pypi.yml +52 -0
  2. pybiocfilecache-0.6.1/.github/workflows/run-tests.yml +33 -0
  3. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/.gitignore +3 -0
  4. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/CHANGELOG.md +16 -0
  5. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/PKG-INFO +3 -4
  6. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/README.md +1 -3
  7. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/changelog.md +16 -0
  8. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/conf.py +9 -0
  9. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/readme.md +1 -3
  10. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/requirements.txt +1 -0
  11. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/pyproject.toml +4 -0
  12. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/setup.cfg +1 -0
  13. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/PKG-INFO +3 -4
  14. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/SOURCES.txt +3 -5
  15. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/cache.py +74 -113
  16. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/config.py +0 -9
  17. pybiocfilecache-0.6.1/src/pybiocfilecache/const.py +1 -0
  18. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/models.py +7 -15
  19. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/utils.py +7 -1
  20. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/tests/test_cache.py +1 -1
  21. pybiocfilecache-0.5.2.dev1/.github/workflows/pypi-publish.yml +0 -51
  22. pybiocfilecache-0.5.2.dev1/.github/workflows/pypi-test.yml +0 -40
  23. pybiocfilecache-0.5.2.dev1/src/pybiocfilecache/migrations/__init__.py +0 -1
  24. pybiocfilecache-0.5.2.dev1/src/pybiocfilecache/migrations/migration.py +0 -139
  25. pybiocfilecache-0.5.2.dev1/src/pybiocfilecache/migrations/migrationV0_5_0.py +0 -102
  26. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/.coveragerc +0 -0
  27. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/.pre-commit-config.yaml +0 -0
  28. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/.readthedocs.yml +0 -0
  29. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/AUTHORS.md +0 -0
  30. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/CONTRIBUTING.rst +0 -0
  31. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/LICENSE.txt +0 -0
  32. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/Makefile +0 -0
  33. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/_static/.gitignore +0 -0
  34. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/authors.md +0 -0
  35. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/best_practices.md +0 -0
  36. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/contributing.rst +0 -0
  37. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/index.md +0 -0
  38. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/docs/license.rst +0 -0
  39. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/setup.py +0 -0
  40. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/dependency_links.txt +0 -0
  41. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/not-zip-safe +0 -0
  42. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/requires.txt +0 -0
  43. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pyBiocFileCache.egg-info/top_level.txt +0 -0
  44. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/__init__.py +0 -0
  45. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/src/pybiocfilecache/exceptions.py +0 -0
  46. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/tests/conftest.py +0 -0
  47. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/tests/data/test1.txt +0 -0
  48. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/tests/data/test2.txt +0 -0
  49. {pybiocfilecache-0.5.2.dev1 → pybiocfilecache-0.6.1}/tox.ini +0 -0
@@ -0,0 +1,52 @@
1
+ # This workflow will install Python dependencies, run tests and lint with a single version of Python
2
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3
+
4
+ name: Publish to PyPI
5
+
6
+ on:
7
+ push:
8
+ tags: "*"
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+
17
+ - name: Set up Python 3.11
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: 3.11
21
+
22
+ - name: Install dependencies
23
+ run: |
24
+ python -m pip install --upgrade pip
25
+ pip install tox
26
+
27
+ - name: Test with tox
28
+ run: |
29
+ tox
30
+
31
+ - name: Build docs
32
+ run: |
33
+ tox -e docs
34
+
35
+ - run: touch ./docs/_build/html/.nojekyll
36
+
37
+ - name: GH Pages Deployment
38
+ uses: JamesIves/github-pages-deploy-action@v4
39
+ with:
40
+ branch: gh-pages # The branch the action should deploy to.
41
+ folder: ./docs/_build/html
42
+ clean: true # Automatically remove deleted files from the deploy branch
43
+
44
+ - name: Build Project and Publish
45
+ run: |
46
+ python -m tox -e clean,build
47
+
48
+ - name: Publish package
49
+ uses: pypa/gh-action-pypi-publish@v1.12.2
50
+ with:
51
+ user: __token__
52
+ password: ${{ secrets.PYPI_PASSWORD }}
@@ -0,0 +1,33 @@
1
+ name: Run tests
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+ branches: [master]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
15
+
16
+ name: Python ${{ matrix.python-version }}
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+
20
+ - name: Setup Python
21
+ uses: actions/setup-python@v5
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+ cache: "pip"
25
+
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install tox
30
+
31
+ - name: Test with tox
32
+ run: |
33
+ tox
@@ -51,3 +51,6 @@ MANIFEST
51
51
  # Per-project virtualenvs
52
52
  .venv*/
53
53
  .conda*/
54
+
55
+ # remove cache
56
+ cache
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## Version 0.6.1
4
+
5
+ - Generate rid's that match with R's cache.
6
+ - remove rname pattern checks.
7
+ - Rename GitHub actions for consistency with the rest of the packages.
8
+
9
+ ## Version 0.6.0
10
+
11
+ - Reverting schema changes that break compatibility with the R/BiocFileCache implementation.
12
+ - Added support for Python 3.13
13
+
14
+ ## Version 0.5.5
15
+
16
+ - chore: Remove Python 3.8 (EOL).
17
+ - precommit: Replace docformatter with ruff's formatter.
18
+
3
19
  ## Version 0.5.0
4
20
 
5
21
  - SQLAlchemy session management
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.5.2.dev1
3
+ Version: 0.6.1
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -10,6 +10,7 @@ Project-URL: Documentation, https://pyscaffold.org/
10
10
  Platform: any
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Programming Language :: Python
13
+ Requires-Python: >=3.9
13
14
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
15
  License-File: LICENSE.txt
15
16
  License-File: AUTHORS.md
@@ -22,7 +23,7 @@ Requires-Dist: pytest-cov; extra == "testing"
22
23
 
23
24
  [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
25
  [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
25
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
26
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
26
27
 
27
28
  # pyBiocFileCache
28
29
 
@@ -66,9 +67,7 @@ from pathlib import Path
66
67
  # Create custom configuration
67
68
  config = CacheConfig(
68
69
  cache_dir=Path("cache_directory"),
69
- max_size_bytes=1024 * 1024 * 1024, # 1GB
70
70
  cleanup_interval=timedelta(days=7),
71
- compression=True
72
71
  )
73
72
 
74
73
  # Initialize cache with configuration
@@ -1,6 +1,6 @@
1
1
  [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
2
2
  [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
3
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
3
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
4
4
 
5
5
  # pyBiocFileCache
6
6
 
@@ -44,9 +44,7 @@ from pathlib import Path
44
44
  # Create custom configuration
45
45
  config = CacheConfig(
46
46
  cache_dir=Path("cache_directory"),
47
- max_size_bytes=1024 * 1024 * 1024, # 1GB
48
47
  cleanup_interval=timedelta(days=7),
49
- compression=True
50
48
  )
51
49
 
52
50
  # Initialize cache with configuration
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## Version 0.6.1
4
+
5
+ - Generate rid's that match with R's cache.
6
+ - remove rname pattern checks.
7
+ - Rename GitHub actions for consistency with the rest of the packages.
8
+
9
+ ## Version 0.6.0
10
+
11
+ - Reverting schema changes that break compatibility with the R/BiocFileCache implementation.
12
+ - Added support for Python 3.13
13
+
14
+ ## Version 0.5.5
15
+
16
+ - chore: Remove Python 3.8 (EOL).
17
+ - precommit: Replace docformatter with ruff's formatter.
18
+
3
19
  ## Version 0.5.0
4
20
 
5
21
  - SQLAlchemy session management
@@ -72,6 +72,7 @@ extensions = [
72
72
  "sphinx.ext.ifconfig",
73
73
  "sphinx.ext.mathjax",
74
74
  "sphinx.ext.napoleon",
75
+ "sphinx_autodoc_typehints",
75
76
  ]
76
77
 
77
78
  # Add any paths that contain templates here, relative to this directory.
@@ -169,6 +170,14 @@ pygments_style = "sphinx"
169
170
  # If this is True, todo emits a warning for each TODO entries. The default is False.
170
171
  todo_emit_warnings = True
171
172
 
173
+ autodoc_default_options = {
174
+ 'special-members': True,
175
+ 'undoc-members': False,
176
+ 'exclude-members': '__weakref__, __dict__, __str__, __module__, __annotations__'
177
+ }
178
+
179
+ autosummary_generate = True
180
+ autosummary_imported_members = True
172
181
 
173
182
  # -- Options for HTML output -------------------------------------------------
174
183
 
@@ -1,6 +1,6 @@
1
1
  [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
2
2
  [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
3
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
3
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
4
4
 
5
5
  # pyBiocFileCache
6
6
 
@@ -44,9 +44,7 @@ from pathlib import Path
44
44
  # Create custom configuration
45
45
  config = CacheConfig(
46
46
  cache_dir=Path("cache_directory"),
47
- max_size_bytes=1024 * 1024 * 1024, # 1GB
48
47
  cleanup_interval=timedelta(days=7),
49
- compression=True
50
48
  )
51
49
 
52
50
  # Initialize cache with configuration
@@ -5,3 +5,4 @@ furo
5
5
  # sphinx_rtd_theme
6
6
  recommonmark
7
7
  sphinx>=3.2.1
8
+ sphinx-autodoc-typehints
@@ -16,6 +16,10 @@ extend-ignore = ["F821"]
16
16
  [tool.ruff.pydocstyle]
17
17
  convention = "google"
18
18
 
19
+ [tool.ruff.format]
20
+ docstring-code-format = true
21
+ docstring-code-line-length = 20
22
+
19
23
  [tool.ruff.per-file-ignores]
20
24
  "__init__.py" = ["E402", "F401"]
21
25
 
@@ -20,6 +20,7 @@ packages = find_namespace:
20
20
  include_package_data = True
21
21
  package_dir =
22
22
  =src
23
+ python_requires = >=3.9
23
24
  install_requires =
24
25
  importlib-metadata; python_version<"3.8"
25
26
  sqlalchemy
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.5.2.dev1
3
+ Version: 0.6.1
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -10,6 +10,7 @@ Project-URL: Documentation, https://pyscaffold.org/
10
10
  Platform: any
11
11
  Classifier: Development Status :: 4 - Beta
12
12
  Classifier: Programming Language :: Python
13
+ Requires-Python: >=3.9
13
14
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
15
  License-File: LICENSE.txt
15
16
  License-File: AUTHORS.md
@@ -22,7 +23,7 @@ Requires-Dist: pytest-cov; extra == "testing"
22
23
 
23
24
  [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
25
  [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
25
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/pypi-test.yml/badge.svg)
26
+ ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
26
27
 
27
28
  # pyBiocFileCache
28
29
 
@@ -66,9 +67,7 @@ from pathlib import Path
66
67
  # Create custom configuration
67
68
  config = CacheConfig(
68
69
  cache_dir=Path("cache_directory"),
69
- max_size_bytes=1024 * 1024 * 1024, # 1GB
70
70
  cleanup_interval=timedelta(days=7),
71
- compression=True
72
71
  )
73
72
 
74
73
  # Initialize cache with configuration
@@ -11,8 +11,8 @@ pyproject.toml
11
11
  setup.cfg
12
12
  setup.py
13
13
  tox.ini
14
- .github/workflows/pypi-publish.yml
15
- .github/workflows/pypi-test.yml
14
+ .github/workflows/publish-pypi.yml
15
+ .github/workflows/run-tests.yml
16
16
  docs/Makefile
17
17
  docs/authors.md
18
18
  docs/best_practices.md
@@ -33,12 +33,10 @@ src/pyBiocFileCache.egg-info/top_level.txt
33
33
  src/pybiocfilecache/__init__.py
34
34
  src/pybiocfilecache/cache.py
35
35
  src/pybiocfilecache/config.py
36
+ src/pybiocfilecache/const.py
36
37
  src/pybiocfilecache/exceptions.py
37
38
  src/pybiocfilecache/models.py
38
39
  src/pybiocfilecache/utils.py
39
- src/pybiocfilecache/migrations/__init__.py
40
- src/pybiocfilecache/migrations/migration.py
41
- src/pybiocfilecache/migrations/migrationV0_5_0.py
42
40
  tests/conftest.py
43
41
  tests/test_cache.py
44
42
  tests/data/test1.txt
@@ -1,4 +1,3 @@
1
- import json
2
1
  import logging
3
2
  from contextlib import contextmanager
4
3
  from datetime import datetime
@@ -6,27 +5,25 @@ from pathlib import Path
6
5
  from time import sleep, time
7
6
  from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
8
7
 
9
- from sqlalchemy import create_engine, func
8
+ from sqlalchemy import create_engine, func, text
10
9
  from sqlalchemy.orm import Session, sessionmaker
11
10
  from sqlalchemy.pool import QueuePool
12
11
 
13
12
  from .config import CacheConfig
13
+ from .const import SCHEMA_VERSION
14
14
  from .exceptions import (
15
15
  BiocCacheError,
16
- CacheSizeLimitError,
17
16
  InvalidRnameError,
18
17
  NoFpathError,
19
18
  RnameExistsError,
20
19
  RpathTimeoutError,
21
20
  )
22
- from .migrations import Migrator
23
21
  from .models import Base, Resource
24
22
  from .utils import (
25
23
  calculate_file_hash,
26
24
  copy_or_move,
27
25
  create_tmp_dir,
28
26
  generate_id,
29
- get_file_size,
30
27
  validate_rname,
31
28
  )
32
29
 
@@ -43,9 +40,7 @@ class BiocFileCache:
43
40
  Features:
44
41
  - Resource validation and integrity checking
45
42
  - Cache size management
46
- - File compression
47
- - Resource tagging
48
- - Automatic cleanup of expired resources
43
+ - Cleanup of expired resources
49
44
  """
50
45
 
51
46
  def __init__(self, cache_dir: Optional[Union[str, Path]] = None, config: Optional[CacheConfig] = None):
@@ -67,33 +62,15 @@ class BiocFileCache:
67
62
 
68
63
  self.config = config
69
64
  self._setup_cache_dir()
70
- self._setup_database()
71
- self._last_cleanup = datetime.now()
72
-
73
- # Initialize migrator
74
- self.migrator = Migrator(self.engine)
75
-
76
- # Run migrations
77
- try:
78
- self.migrator.migrate()
79
- except Exception as e:
80
- logger.error(f"Failed to run migrations: {e}")
81
- raise
65
+ db_schema_version = self._setup_database()
82
66
 
83
- def get_schema_version(self) -> str:
84
- """Get current schema version."""
85
- return self.migrator.get_current_version()
67
+ if db_schema_version != SCHEMA_VERSION:
68
+ print(db_schema_version)
69
+ raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
86
70
 
87
- def migrate_schema(self, target_version: Optional[str] = None) -> None:
88
- """Migrate schema to specified version.
89
-
90
- Args:
91
- target_version: Version to migrate to.
92
- If None, migrates to latest version.
93
- """
94
- self.migrator.migrate(target_version)
71
+ self._last_cleanup = datetime.now()
95
72
 
96
- def _setup_cache_dir(self) -> None:
73
+ def _setup_cache_dir(self) -> bool:
97
74
  if not self.config.cache_dir.exists():
98
75
  self.config.cache_dir.mkdir(parents=True, exist_ok=True)
99
76
 
@@ -111,6 +88,29 @@ class BiocFileCache:
111
88
  Base.metadata.create_all(self.engine)
112
89
  self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
113
90
 
91
+ with self.engine.connect() as conn:
92
+ result = conn.execute(
93
+ text("""
94
+ SELECT value FROM metadata
95
+ WHERE key = 'schema_version'
96
+ """)
97
+ )
98
+ row = result.fetchone()
99
+
100
+ if row is not None:
101
+ return row[0]
102
+
103
+ conn.execute(
104
+ text("""
105
+ INSERT INTO metadata (key, value)
106
+ VALUES ('schema_version', :version);
107
+ """),
108
+ {"version": SCHEMA_VERSION},
109
+ )
110
+ conn.commit()
111
+
112
+ return SCHEMA_VERSION
113
+
114
114
  def _get_detached_resource(self, session: Session, resource: Resource) -> Optional[Resource]:
115
115
  """Get a detached copy of a resource."""
116
116
  if resource is None:
@@ -142,17 +142,6 @@ class BiocFileCache:
142
142
  finally:
143
143
  session.close()
144
144
 
145
- def _check_cache_size(self, new_size: int) -> None:
146
- """Verify cache size limit won't be exceeded."""
147
- if self.config.max_size_bytes is None:
148
- return
149
-
150
- current_size = self.get_cache_size()
151
- if current_size + new_size > self.config.max_size_bytes:
152
- raise CacheSizeLimitError(
153
- f"Adding {new_size} bytes would exceed cache limit of " f"{self.config.max_size_bytes} bytes"
154
- )
155
-
156
145
  def _validate_rname(self, rname: str) -> None:
157
146
  """Validate resource name format."""
158
147
  if not validate_rname(rname, self.config.rname_pattern):
@@ -242,7 +231,6 @@ class BiocFileCache:
242
231
  fpath: Union[str, Path],
243
232
  rtype: Literal["local", "web", "relative"] = "local",
244
233
  action: Literal["copy", "move", "asis"] = "copy",
245
- tags: Optional[List[str]] = None,
246
234
  expires: Optional[datetime] = None,
247
235
  ext: bool = False,
248
236
  ) -> Resource:
@@ -264,9 +252,6 @@ class BiocFileCache:
264
252
  How to handle the file ("copy", "move", or "asis").
265
253
  Defaults to ``copy``.
266
254
 
267
- tags:
268
- Optional list of tags for categorization.
269
-
270
255
  expires:
271
256
  Optional expiration datetime.
272
257
  If None, resource never expires.
@@ -278,7 +263,7 @@ class BiocFileCache:
278
263
  Returns:
279
264
  The `Resource` object added to the cache.
280
265
  """
281
- self._validate_rname(rname)
266
+ # self._validate_rname(rname)
282
267
  fpath = Path(fpath)
283
268
 
284
269
  if not fpath.exists():
@@ -288,11 +273,9 @@ class BiocFileCache:
288
273
  raise RnameExistsError(f"Resource '{rname}' already exists")
289
274
 
290
275
  # Generate paths and check size
291
- rid = generate_id()
276
+ rid = generate_id(size=len(self))
292
277
  rpath = self.config.cache_dir / f"{rid}{fpath.suffix if ext else ''}" if action != "asis" else fpath
293
278
 
294
- self._check_cache_size(get_file_size(fpath))
295
-
296
279
  # Create resource record
297
280
  resource = Resource(
298
281
  rid=rid,
@@ -300,9 +283,7 @@ class BiocFileCache:
300
283
  rpath=str(rpath),
301
284
  rtype=rtype,
302
285
  fpath=str(fpath),
303
- tags=",".join(tags) if tags else None,
304
286
  expires=expires,
305
- size_bytes=get_file_size(fpath),
306
287
  )
307
288
 
308
289
  # Store file and update database
@@ -311,7 +292,7 @@ class BiocFileCache:
311
292
  session.commit()
312
293
 
313
294
  try:
314
- copy_or_move(fpath, rpath, rname, action, self.config.compression)
295
+ copy_or_move(fpath, rpath, rname, action, False)
315
296
 
316
297
  # Calculate and store checksum
317
298
  resource.etag = calculate_file_hash(rpath, self.config.hash_algorithm)
@@ -348,7 +329,6 @@ class BiocFileCache:
348
329
  rname: str,
349
330
  fpath: Union[str, Path],
350
331
  action: Literal["copy", "move", "asis"] = "copy",
351
- tags: Optional[List[str]] = None,
352
332
  ) -> Resource:
353
333
  """Update an existing resource.
354
334
 
@@ -363,9 +343,6 @@ class BiocFileCache:
363
343
  Either ``copy``, ``move`` or ``asis``.
364
344
  Defaults to ``copy``.
365
345
 
366
- tags:
367
- Optional new list of tags.
368
-
369
346
  Returns:
370
347
  Updated `Resource` object.
371
348
 
@@ -382,14 +359,10 @@ class BiocFileCache:
382
359
 
383
360
  old_path = Path(resource.rpath)
384
361
  try:
385
- copy_or_move(fpath, old_path, rname, action, self.config.compression)
362
+ copy_or_move(fpath, old_path, rname, action, False)
386
363
 
387
364
  resource.last_modified_time = datetime.now()
388
365
  resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm)
389
- resource.size_bytes = get_file_size(old_path)
390
-
391
- if tags is not None:
392
- resource.tags = ",".join(tags)
393
366
 
394
367
  session.commit()
395
368
  return self._get_detached_resource(session, resource)
@@ -428,14 +401,10 @@ class BiocFileCache:
428
401
  session.rollback()
429
402
  raise BiocCacheError(f"Failed to remove resource '{rname}'") from e
430
403
 
431
- def list_resources(
432
- self, tag: Optional[str] = None, rtype: Optional[str] = None, expired: Optional[bool] = None
433
- ) -> List[Resource]:
404
+ def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
434
405
  """List resources in the cache with optional filtering.
435
406
 
436
407
  Args:
437
- tag:
438
- Filter resources by tag.
439
408
 
440
409
  rtype:
441
410
  Filter resources by type.
@@ -453,8 +422,6 @@ class BiocFileCache:
453
422
  with self.get_session() as session:
454
423
  query = session.query(Resource)
455
424
 
456
- if tag:
457
- query = query.filter(Resource.tags.like(f"%{tag}%"))
458
425
  if rtype:
459
426
  query = query.filter(Resource.rtype == rtype)
460
427
  if expired is not None:
@@ -492,47 +459,38 @@ class BiocFileCache:
492
459
  logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e)
493
460
  return False
494
461
 
495
- def get_cache_size(self) -> int:
496
- """Get total size of cached files in bytes."""
497
- with self.get_session() as session:
498
- return session.query(func.sum(Resource.size_bytes)).scalar() or 0
499
-
500
- def export_metadata(self, path: Path) -> None:
501
- """Export cache metadata to JSON file."""
502
- data = {
503
- "resources": [
504
- {
505
- "rname": r.rname,
506
- "rtype": r.rtype,
507
- "tags": r.tags,
508
- "expires": r.expires.isoformat() if r.expires else None,
509
- "etag": r.etag,
510
- "size_bytes": r.size_bytes,
511
- }
512
- for r in self.list_resources()
513
- ],
514
- "cache_size": self.get_cache_size(),
515
- "export_time": datetime.now().isoformat(),
516
- }
517
-
518
- with open(path, "w") as f:
519
- json.dump(data, f, indent=2)
520
-
521
- def import_metadata(self, path: Path) -> None:
522
- """Import cache metadata from JSON file."""
523
- with open(path) as f:
524
- data = json.load(f)
525
-
526
- with self.get_session() as session:
527
- for resource_data in data["resources"]:
528
- resource = self._get(session, resource_data["rname"])
529
- if resource:
530
- resource.tags = resource_data["tags"]
531
- resource.expires = (
532
- datetime.fromisoformat(resource_data["expires"]) if resource_data["expires"] else None
533
- )
534
- session.merge(resource)
535
- session.commit()
462
+ # def export_metadata(self, path: Path) -> None:
463
+ # """Export cache metadata to JSON file."""
464
+ # data = {
465
+ # "resources": [
466
+ # {
467
+ # "rname": r.rname,
468
+ # "rtype": r.rtype,
469
+ # "expires": r.expires.isoformat() if r.expires else None,
470
+ # "etag": r.etag,
471
+ # }
472
+ # for r in self.list_resources()
473
+ # ],
474
+ # "export_time": datetime.now().isoformat(),
475
+ # }
476
+
477
+ # with open(path, "w") as f:
478
+ # json.dump(data, f, indent=2)
479
+
480
+ # def import_metadata(self, path: Path) -> None:
481
+ # """Import cache metadata from JSON file."""
482
+ # with open(path) as f:
483
+ # data = json.load(f)
484
+
485
+ # with self.get_session() as session:
486
+ # for resource_data in data["resources"]:
487
+ # resource = self._get(session, resource_data["rname"])
488
+ # if resource:
489
+ # resource.expires = (
490
+ # datetime.fromisoformat(resource_data["expires"]) if resource_data["expires"] else None
491
+ # )
492
+ # session.merge(resource)
493
+ # session.commit()
536
494
 
537
495
  def verify_cache(self) -> Tuple[int, int]:
538
496
  """Verify integrity of all cached resources.
@@ -556,7 +514,7 @@ class BiocFileCache:
556
514
  Search string.
557
515
 
558
516
  field:
559
- Resource field to search ("rname", "rtype", "tags", etc.).
517
+ Resource field to search ("rname", "rtype", etc.).
560
518
 
561
519
  exact:
562
520
  Whether to require exact match.
@@ -589,7 +547,6 @@ class BiocFileCache:
589
547
  return {
590
548
  "total_resources": total,
591
549
  "expired_resources": expired,
592
- "cache_size_bytes": self.get_cache_size(),
593
550
  "resource_types": types,
594
551
  "last_cleanup": self._last_cleanup.isoformat(),
595
552
  "cleanup_enabled": self.config.cleanup_interval is not None,
@@ -655,3 +612,7 @@ class BiocFileCache:
655
612
  logger.warning(f"Failed to remove {file}: {file_e}")
656
613
 
657
614
  return False
615
+
616
+ def __len__(self):
617
+ with self.get_session() as session:
618
+ return session.query(Resource).count()
@@ -16,10 +16,6 @@ class CacheConfig:
16
16
  cache_dir:
17
17
  Directory to store cached files.
18
18
 
19
- max_size_bytes:
20
- Maximum total size of cache.
21
- None for unlimited.
22
-
23
19
  cleanup_interval:
24
20
  How often to run expired resource cleanup.
25
21
  None for no cleanup.
@@ -29,14 +25,9 @@ class CacheConfig:
29
25
 
30
26
  hash_algorithm:
31
27
  Algorithm to use for file checksums.
32
-
33
- compression:
34
- Whether to compress cached files.
35
28
  """
36
29
 
37
30
  cache_dir: Path
38
- max_size_bytes: Optional[int] = None
39
31
  cleanup_interval: Optional[timedelta] = None # timedelta(days=30)
40
32
  rname_pattern: str = r"^[a-zA-Z0-9_-]+$"
41
33
  hash_algorithm: str = "md5"
42
- compression: bool = False
@@ -0,0 +1 @@
1
+ SCHEMA_VERSION = "0.99.4"
@@ -13,7 +13,7 @@ class Metadata(Base):
13
13
 
14
14
  __tablename__ = "metadata"
15
15
 
16
- key = Column(Text(), primary_key=True, index=True)
16
+ key = Column(Text(), primary_key=True, index=True, unique=True)
17
17
  value = Column(Text())
18
18
 
19
19
  def __repr__(self) -> str:
@@ -56,29 +56,21 @@ class Resource(Base):
56
56
 
57
57
  expires:
58
58
  When the resource should be considered expired.
59
-
60
- tags:
61
- Optional comma-separated tags for categorization.
62
-
63
- size_bytes:
64
- Size of the resource in bytes.
65
59
  """
66
60
 
67
61
  __tablename__ = "resource"
68
62
 
69
63
  id = Column(Integer, primary_key=True, index=True, autoincrement=True)
70
- rid = Column(Text(), index=True)
71
- rname = Column(Text(), index=True, unique=True)
64
+ rid = Column(Text())
65
+ rname = Column(Text())
72
66
  create_time = Column(DateTime, server_default=func.now())
73
67
  access_time = Column(DateTime, server_default=func.now())
74
68
  rpath = Column(Text())
75
69
  rtype = Column(Text())
76
70
  fpath = Column(Text())
77
- last_modified_time = Column(DateTime, onupdate=func.now())
78
- etag = Column(Text())
79
- expires = Column(DateTime)
80
- tags = Column(Text())
81
- size_bytes = Column(Integer)
71
+ last_modified_time = Column(DateTime, onupdate=func.now(), default=None)
72
+ etag = Column(Text(), default=None)
73
+ expires = Column(DateTime, default=None)
82
74
 
83
75
  def __repr__(self) -> str:
84
- return f"<Resource(id='{self.id}', rname='{self.rname}')>"
76
+ return f"<Resource(rid='{self.rid}', rname='{self.rname}')>"
@@ -22,11 +22,17 @@ def create_tmp_dir() -> Path:
22
22
  return Path(tempfile.mkdtemp())
23
23
 
24
24
 
25
- def generate_id() -> str:
25
+ def generate_uuid() -> str:
26
26
  """Generate unique identifier."""
27
27
  return uuid.uuid4().hex
28
28
 
29
29
 
30
+ def generate_id(size) -> str:
31
+ """Generate unique identifier."""
32
+ size += 1
33
+ return "BFC" + str(size)
34
+
35
+
30
36
  def validate_rname(rname: str, pattern: str) -> bool:
31
37
  """Validate resource name format."""
32
38
  return bool(re.match(pattern, rname))
@@ -17,7 +17,7 @@ def test_create_cache():
17
17
  bfc.purge()
18
18
 
19
19
 
20
- def test_add_get_operations():
20
+ def test_add_get_list_operations():
21
21
  bfc = BiocFileCache(CACHE_DIR)
22
22
 
23
23
  rtrip = bfc.add("test1", os.getcwd() + "/tests/data/test1.txt")
@@ -1,51 +0,0 @@
1
- # This workflow will install Python dependencies, run tests and lint with a single version of Python
2
- # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3
-
4
- name: Publish to PyPI
5
-
6
- on:
7
- push:
8
- tags: "*"
9
-
10
- jobs:
11
- build:
12
-
13
- runs-on: ubuntu-latest
14
-
15
- steps:
16
- - uses: actions/checkout@v2
17
- - name: Set up Python 3.9
18
- uses: actions/setup-python@v2
19
- with:
20
- python-version: 3.9
21
- - name: Install dependencies
22
- run: |
23
- python -m pip install --upgrade pip
24
- pip install flake8 pytest tox
25
- # - name: Lint with flake8
26
- # run: |
27
- # # stop the build if there are Python syntax errors or undefined names
28
- # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
29
- # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
30
- # # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
31
- - name: Test with tox
32
- run: |
33
- tox
34
- - name: Build docs
35
- run: |
36
- tox -e docs
37
- - run: touch ./docs/_build/html/.nojekyll
38
- - name: GH Pages Deployment
39
- uses: JamesIves/github-pages-deploy-action@4.1.3
40
- with:
41
- branch: gh-pages # The branch the action should deploy to.
42
- folder: ./docs/_build/html
43
- clean: true # Automatically remove deleted files from the deploy branch
44
- - name: Build Project and Publish
45
- run: |
46
- python -m tox -e clean,build
47
- - name: Publish package
48
- uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
49
- with:
50
- user: __token__
51
- password: ${{ secrets.PYPI_PASSWORD }}
@@ -1,40 +0,0 @@
1
- # This workflow will install Python dependencies, run tests and lint with a single version of Python
2
- # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3
-
4
- name: Test the library
5
-
6
- on:
7
- push:
8
- branches: [ master ]
9
- pull_request:
10
- branches: [ master ]
11
-
12
- jobs:
13
- build:
14
-
15
- runs-on: ubuntu-latest
16
- strategy:
17
- matrix:
18
- python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12' ]
19
-
20
- name: Python ${{ matrix.python-version }}
21
- steps:
22
- - uses: actions/checkout@v2
23
- - name: Setup Python
24
- uses: actions/setup-python@v2
25
- with:
26
- python-version: ${{ matrix.python-version }}
27
- cache: 'pip'
28
- - name: Install dependencies
29
- run: |
30
- python -m pip install --upgrade pip
31
- pip install flake8 pytest tox
32
- # - name: Lint with flake8
33
- # run: |
34
- # # stop the build if there are Python syntax errors or undefined names
35
- # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
36
- # # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
37
- # # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
38
- - name: Test with tox
39
- run: |
40
- tox
@@ -1 +0,0 @@
1
- from .migration import Migrator
@@ -1,139 +0,0 @@
1
- import logging
2
- from typing import Optional
3
-
4
- from sqlalchemy import text
5
- from sqlalchemy.engine import Engine
6
-
7
- __author__ = "Jayaram Kancherla"
8
- __copyright__ = "Jayaram Kancherla"
9
- __license__ = "MIT"
10
-
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- class Migration:
16
- """Base class for migrations."""
17
-
18
- version: str
19
- description: str
20
-
21
- @staticmethod
22
- def up(engine: Engine) -> None:
23
- """Upgrade to this version."""
24
- raise NotImplementedError
25
-
26
- @staticmethod
27
- def down(engine: Engine) -> None:
28
- """Downgrade from this version."""
29
- raise NotImplementedError
30
-
31
-
32
- class Migrator:
33
- """Handles database schema migrations."""
34
-
35
- def __init__(self, engine: Engine):
36
- from .migrationV0_5_0 import MigrationV0_5_0
37
-
38
- self.engine = engine
39
- self.migrations = [MigrationV0_5_0]
40
-
41
- def _detect_version_from_structure(self) -> str:
42
- """Detect schema version by examining table structure."""
43
- with self.engine.connect() as conn:
44
- # Check table structure
45
- columns = conn.execute(
46
- text("""
47
- PRAGMA table_info(resource);
48
- """)
49
- ).fetchall()
50
- column_names = {col[1] for col in columns}
51
-
52
- # Check for columns that indicate version
53
- # if "is_compressed" in column_names:
54
- # return "0.5.0"
55
- if "tags" in column_names and "size_bytes" in column_names:
56
- return "0.5.0"
57
- else:
58
- return "0.4.1"
59
-
60
- def get_current_version(self) -> Optional[str]:
61
- """Get current schema version from database.
62
-
63
- Will attempt to detect version if `schema_version` is not in metadata.
64
- """
65
- with self.engine.connect() as conn:
66
- result = conn.execute(
67
- text("""
68
- SELECT value FROM metadata
69
- WHERE key = 'schema_version'
70
- """)
71
- )
72
- row = result.fetchone()
73
-
74
- if row is not None:
75
- return row[0]
76
-
77
- detected_version = self._detect_version_from_structure()
78
- conn.execute(
79
- text("""
80
- INSERT INTO metadata (key, value)
81
- VALUES ('schema_version', :version);
82
- """),
83
- {"version": detected_version},
84
- )
85
-
86
- return detected_version
87
-
88
- def migrate(self, target_version: Optional[str] = None) -> None:
89
- """Migrate schema to target version.
90
-
91
- Args:
92
- target_version:
93
- Version to migrate to.
94
- If None, migrates to latest version.
95
- """
96
- try:
97
- current = self.get_current_version()
98
- latest_version = self.migrations[-1].version
99
- target_version = target_version or latest_version
100
-
101
- if current == target_version:
102
- logger.info("Already at target version")
103
- return
104
-
105
- if current == "0.4.1" and target_version == "0.5.0":
106
- logger.info("Upgrading from 0.4.1 to 0.5.0")
107
- self.migrations[0].up(self.engine)
108
- elif current == "0.5.0" and target_version == "0.4.1":
109
- logger.info("Downgrading from 0.5.0 to 0.4.1")
110
- self.migrations[0].down(self.engine)
111
- else:
112
- raise ValueError(f"Unsupported migration path: {current} -> {target_version}")
113
-
114
- except Exception as e:
115
- logger.error(f"Migration failed: {e}")
116
- raise
117
-
118
- # When we have multiple migrations
119
- # current_idx = next((i for i, m in enumerate(self.migrations) if m.version == current), None)
120
- # target_idx = next((i for i, m in enumerate(self.migrations) if m.version == target_version), None)
121
-
122
- # if current_idx is None:
123
- # raise ValueError(f"Unknown current version: {current}")
124
- # if target_idx is None:
125
- # raise ValueError(f"Unknown target version: {target_version}")
126
-
127
- # if current_idx < target_idx:
128
- # # Upgrade
129
- # for migration in self.migrations[current_idx : target_idx + 1]:
130
- # logger.info(f"Upgrading to {migration.version}")
131
- # migration.up(self.engine)
132
- # elif current_idx > target_idx:
133
- # # Downgrade
134
- # for migration in reversed(self.migrations[target_idx + 1 : current_idx + 1]):
135
- # logger.info(f"Downgrading from {migration.version}")
136
- # migration.down(self.engine)
137
-
138
- def __repr__(self) -> str:
139
- return f"Migrator(current_version={self.get_current_version()})"
@@ -1,102 +0,0 @@
1
- from sqlalchemy import text
2
- from sqlalchemy.engine import Engine
3
-
4
- from .migration import Migration
5
-
6
- __author__ = "Jayaram Kancherla"
7
- __copyright__ = "Jayaram Kancherla"
8
- __license__ = "MIT"
9
-
10
-
11
- class MigrationV0_5_0(Migration):
12
- """Migration from v0.4.1 to 0.5.0."""
13
-
14
- version = "0.5.0"
15
- description = "Add tags, size_bytes, compression flag, and update indexes"
16
-
17
- @staticmethod
18
- def up(engine: Engine) -> None:
19
- """Upgrade from v0.4.1 to v0.5.0."""
20
- with engine.begin() as conn:
21
- # Add new columns
22
- conn.execute(
23
- text("""
24
- ALTER TABLE resource
25
- ADD COLUMN tags TEXT;
26
- """)
27
- )
28
- conn.execute(
29
- text("""
30
- ALTER TABLE resource
31
- ADD COLUMN size_bytes INTEGER;
32
- """)
33
- )
34
- # conn.execute(
35
- # text("""
36
- # ALTER TABLE resource
37
- # ADD COLUMN is_compressed BOOLEAN DEFAULT FALSE;
38
- # """)
39
- # )
40
-
41
- # Calculate size_bytes for existing resources
42
- conn.execute(
43
- text("""
44
- UPDATE resource
45
- SET size_bytes = (
46
- SELECT length(readfile(rpath))
47
- FROM resource r2
48
- WHERE r2.id = resource.id
49
- )
50
- WHERE EXISTS (
51
- SELECT 1
52
- FROM resource r3
53
- WHERE r3.id = resource.id
54
- AND r3.rpath IS NOT NULL
55
- );
56
- """)
57
- )
58
-
59
- # Add indexes
60
- conn.execute(
61
- text("""
62
- CREATE UNIQUE INDEX IF NOT EXISTS ix_resource_rname
63
- ON resource(rname);
64
- """)
65
- )
66
- conn.execute(
67
- text("""
68
- CREATE INDEX IF NOT EXISTS ix_resource_rid
69
- ON resource(rid);
70
- """)
71
- )
72
-
73
- # Update metadata
74
- conn.execute(
75
- text("""
76
- UPDATE metadata
77
- SET value = '0.5.0'
78
- WHERE key = 'schema_version';
79
- """)
80
- )
81
-
82
- @staticmethod
83
- def down(engine: Engine) -> None:
84
- """Downgrade from v0.5.0 to 0.4.1."""
85
- with engine.begin() as conn:
86
- # Remove indexes
87
- conn.execute(text("DROP INDEX IF EXISTS ix_resource_rname;"))
88
- conn.execute(text("DROP INDEX IF EXISTS ix_resource_rid;"))
89
-
90
- # Remove columns
91
- # conn.execute(text("ALTER TABLE resource DROP COLUMN is_compressed;"))
92
- conn.execute(text("ALTER TABLE resource DROP COLUMN size_bytes;"))
93
- conn.execute(text("ALTER TABLE resource DROP COLUMN tags;"))
94
-
95
- # Update metadata
96
- conn.execute(
97
- text("""
98
- UPDATE metadata
99
- SET value = '0.4.1'
100
- WHERE key = 'schema_version';
101
- """)
102
- )