pyBiocFileCache 0.2.1__py3-none-any.whl → 0.3.0__py3-none-any.whl

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.
@@ -1,4 +1,4 @@
1
1
  # Contributors
2
2
 
3
3
  * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
4
+ * Max Hargreaves <max_hargreaves@outlook.com>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: File based cache for resources and metadata
5
5
  Home-page: https://github.com/epiviz/pyBiocFileCache
6
6
  Author: jkanche
@@ -13,13 +13,17 @@ Classifier: Programming Language :: Python
13
13
  Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
14
  License-File: LICENSE.txt
15
15
  License-File: AUTHORS.md
16
- Requires-Dist: sqlalchemy (<2.0,>=1.4)
16
+ Requires-Dist: sqlalchemy <2.1,>=2
17
17
  Requires-Dist: importlib-metadata ; python_version < "3.8"
18
18
  Provides-Extra: testing
19
19
  Requires-Dist: setuptools ; extra == 'testing'
20
20
  Requires-Dist: pytest ; extra == 'testing'
21
21
  Requires-Dist: pytest-cov ; extra == 'testing'
22
22
 
23
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
24
+ [![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
+
23
27
  # pyBiocFileCache
24
28
 
25
29
  File system based cache for resources & metadata. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache)
@@ -34,7 +38,7 @@ Package is published to [PyPI](https://pypi.org/project/pyBiocFileCache/)
34
38
  pip install pybiocfilecache
35
39
  ```
36
40
 
37
- #### Initialize a cache directory
41
+ #### Initialize a cache directory
38
42
 
39
43
  ```
40
44
  from pybiocfilecache import BiocFileCache
@@ -0,0 +1,13 @@
1
+ pybiocfilecache/BiocFileCache.py,sha256=6L7uYANBSPkb6kEX8p-VYHCLOPPn4RUIveFDktSzXrI,8130
2
+ pybiocfilecache/__init__.py,sha256=5SUhxaA5370FRyHOs5miL4WXxe2fNODbO_I6VRqDCB0,915
3
+ pybiocfilecache/_exceptions.py,sha256=347Lt1Rrt-TTzP5yEqlRM1QoaPBXB1UnZXv0GfhZmv0,374
4
+ pybiocfilecache/utils.py,sha256=NHgigiMzZ3LaQPDa2ydAH1f8ls4itZgCRbcB2qJwyjA,1783
5
+ pybiocfilecache/db/Base.py,sha256=TuMk8Eqiu8rb7QZVtUYsGbVxMekn4UDyQ4vkvuCp22k,939
6
+ pybiocfilecache/db/__init__.py,sha256=XE1DrTqLmDOM4Y4Qt3fdr6ahir5Vqug5e5v-DQexCDw,102
7
+ pybiocfilecache/db/schema.py,sha256=alr2YCfCmYb7xt8pzXqwpY-eBLNA3oR4nD8ruVzHo6E,1041
8
+ pyBiocFileCache-0.3.0.dist-info/AUTHORS.md,sha256=MMx3vll5oIcyk72Bk3N_ACfHWt5YhAlk2vBjx68m4R8,112
9
+ pyBiocFileCache-0.3.0.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
+ pyBiocFileCache-0.3.0.dist-info/METADATA,sha256=aBtQrklvKx2djCoo6ATN5D8V0ptkSyR0dLT4HfiXg6o,2535
11
+ pyBiocFileCache-0.3.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
12
+ pyBiocFileCache-0.3.0.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
+ pyBiocFileCache-0.3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.38.4)
2
+ Generator: bdist_wheel (0.43.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,10 +1,8 @@
1
- """
2
- Python Implementation of BiocFileCache
3
- """
1
+ """Python Implementation of BiocFileCache."""
4
2
 
5
- import logging
6
3
  import os
7
4
  from pathlib import Path
5
+ from time import sleep, time
8
6
  from typing import List, Optional, Union
9
7
 
10
8
  from sqlalchemy import func
@@ -13,24 +11,21 @@ from sqlalchemy.orm import Session
13
11
  from .db import create_schema
14
12
  from .db.schema import Resource
15
13
  from .utils import copy_or_move, create_tmp_dir, generate_id
14
+ from ._exceptions import NoFpathError, RnameExistsError, RpathTimeoutError
16
15
 
17
16
  __author__ = "jkanche"
18
17
  __copyright__ = "jkanche"
19
18
  __license__ = "MIT"
20
19
 
21
- _logger = logging.getLogger(__name__)
22
-
23
20
 
24
21
  class BiocFileCache:
25
- """
26
- Class to manage and cache files.
27
- """
22
+ """Class to manage and cache files."""
28
23
 
29
24
  def __init__(self, cacheDirOrPath: Union[str, Path] = create_tmp_dir()):
30
25
  """Initialize BiocFileCache.
31
26
 
32
27
  Args:
33
- cacheDirOrPath (Union[str, Path], optional): Path to cache
28
+ cacheDirOrPath (Union[str, Path], optional): Path to cache.
34
29
  directory. Defaults to tmp location, `create_tmp_dir()`.
35
30
 
36
31
  Raises:
@@ -65,54 +60,74 @@ class BiocFileCache:
65
60
  Args:
66
61
  rname (str): Name of the resource to add to cache.
67
62
  fpath (Union[str, Path]): Location of the resource.
68
- rtype (str, optional): One of `local`, `web`, or `relative`.
63
+ rtype (str, optional): One of `"local"`, `"web"`, or `"relative"`.
69
64
  Defaults to `"local"`.
70
- action (str, optional): Either `copy`, `move` or `asis`.
65
+ action (str, optional): Either `"copy"`, `"move"` or `"asis"`.
71
66
  Defaults to `"copy"`.
72
67
  ext (bool, optional): Use filepath extension when storing in cache.
73
68
  Defaults to `False`.
74
69
 
75
70
  Returns:
76
- Resource: Database record of the new resource in cache
77
- """
71
+ Resource: Database record of the new resource in cache.
78
72
 
73
+ Raises:
74
+ NoFpathError: When the `fpath` does not exist.
75
+ RnameExistsError: When the `rname` already exists in the cache.
76
+ sqlalchemy exceptions: When something is up with the cache.
77
+ """
79
78
  if isinstance(fpath, str):
80
79
  fpath = Path(fpath)
81
80
 
82
81
  if not fpath.exists():
83
- raise Exception(f"Resource at {fpath} does not exist.")
84
-
85
- existing_cache = self.get(rname)
86
- if existing_cache is not None:
87
- _logger.info(f"File with {rname} already exists, updating instead")
88
- return self.update(rname, fpath, action)
82
+ raise NoFpathError(f"Resource at {fpath} does not exist.")
89
83
 
90
84
  rid = generate_id()
91
- rpath = f"{self.cache}/{rid}.{fpath.suffix}" if ext else f"{self.cache}/{rid}"
92
-
93
- copy_or_move(str(fpath), rpath, rname, action)
85
+ rpath = f"{self.cache}/{rid}" + (f".{fpath.suffix}" if ext else "")
94
86
 
95
87
  # create new record in the database
96
88
  res = Resource(
97
- **dict(rid=rid, rname=rname, rpath=rpath, rtype=rtype, fpath=str(fpath))
89
+ **dict(
90
+ rid=rid,
91
+ rname=rname,
92
+ rpath=rpath,
93
+ rtype=rtype,
94
+ fpath=str(fpath),
95
+ )
98
96
  )
99
97
 
98
+ # If this was higher up a parallel process could have added the key to
99
+ # the cache in the meantime as the above takes a bit, so checking here
100
+ # reduces the odds of this happening
101
+ # Redirecting to update was removed as it is a scenario better handled
102
+ # by the caller.
103
+ if self.get(rname) is not None:
104
+ raise RnameExistsError("Resource already exists in cache!")
105
+
100
106
  with self.sessionLocal() as session:
101
107
  session.add(res)
102
108
  session.commit()
103
109
  session.refresh(res)
104
110
 
111
+ # In the "move" scenario if we move the file to rpath before rpath is
112
+ # part of the cache and then when trying to add it to the cache an
113
+ # exception is raised (such as if it is locked by another process) the
114
+ # data essentially disappears to rpath with no way of retrieving its
115
+ # location. Thus we add rpath to the cache first, then move the data
116
+ # into it so that the data at source does not disappear if accessing
117
+ # the cache raises an exception.
118
+ copy_or_move(str(fpath), rpath, rname, action)
119
+
105
120
  return res
106
121
 
107
122
  def query(self, query: str, field: str = "rname") -> List[Resource]:
108
123
  """Search cache for a resource.
109
124
 
110
125
  Args:
111
- query (str): query to search
126
+ query (str): query or keywords to search.
112
127
  field (str, optional): Field to search. Defaults to "rname".
113
128
 
114
129
  Returns:
115
- List[Resource]: list of matching resources from cache
130
+ List[Resource]: list of matching resources from cache.
116
131
  """
117
132
  with self.sessionLocal() as session:
118
133
  return (
@@ -129,15 +144,32 @@ class BiocFileCache:
129
144
  rname (str): The `rname` of the `Resource` to get.
130
145
 
131
146
  Returns:
132
- res (Resource, optional): The `Resource` for the `rname` if any.
147
+ (Resource, optional): The `Resource` for the `rname` if any.
133
148
  """
134
- return session.query(Resource).filter(Resource.rname == rname).first()
149
+ resource: Optional[Resource] = (
150
+ session.query(Resource).filter(Resource.rname == rname).first()
151
+ )
152
+
153
+ if resource is not None:
154
+ # `Resource` may exist but `rpath` could still be being
155
+ # moved/copied into by `add`, wait until `rpath` exists
156
+ start = time()
157
+ timeout = 30
158
+ while not Path(str(resource.rpath)).exists():
159
+ if time() - start >= timeout:
160
+ raise RpathTimeoutError(
161
+ f"For resource: '{rname}' the rpath does not exist "
162
+ f"after {timeout} seconds."
163
+ )
164
+ sleep(0.1)
165
+
166
+ return resource
135
167
 
136
168
  def get(self, rname: str) -> Optional[Resource]:
137
- """get resource by name from cache.
169
+ """Get resource by name from cache.
138
170
 
139
171
  Args:
140
- rname (str): Name of the file to search
172
+ rname (str): Name of the file to search.
141
173
 
142
174
  Returns:
143
175
  Optional[Resource]: matched resource from cache if exists.
@@ -148,14 +180,16 @@ class BiocFileCache:
148
180
  """Remove a resource from cache by name.
149
181
 
150
182
  Args:
151
- rname (str): Name of the resource to remove
183
+ rname (str): Name of the resource to remove.
152
184
  """
153
185
  with self.sessionLocal() as session:
154
- res: Resource = self._get(session, rname)
155
- session.delete(res)
156
- session.commit()
157
- # remove file
158
- Path(res.rpath).unlink()
186
+ res: Optional[Resource] = self._get(session, rname)
187
+
188
+ if res is not None:
189
+ session.delete(res)
190
+ session.commit()
191
+ # remove file
192
+ Path(res.rpath).unlink()
159
193
 
160
194
  def purge(self):
161
195
  """Remove all files from cache."""
@@ -168,12 +202,12 @@ class BiocFileCache:
168
202
  """Update a resource in cache.
169
203
 
170
204
  Args:
171
- rname (str): name of the resource in cache
205
+ rname (str): name of the resource in cache.
172
206
  fpath (Union[str, Path]): new resource to replace existing file in cache.
173
- action (str, optional): either copy of move. defaults to copy
207
+ action (str, optional): either copy of move. defaults to copy.
174
208
 
175
209
  Returns:
176
- Resource: Updated resource record in cache
210
+ Resource: Updated resource record in cache.
177
211
  """
178
212
 
179
213
  if isinstance(fpath, str):
@@ -183,13 +217,18 @@ class BiocFileCache:
183
217
  raise Exception(f"File: '{fpath}' does not exist")
184
218
 
185
219
  with self.sessionLocal() as session:
186
- res: Resource = self._get(session, rname)
187
- # copy the file to cache
188
- copy_or_move(str(fpath), str(res.rpath), rname, action)
189
- # TODO: is this needed?
190
- res.create_time = res.access_time = res.last_modified_time = func.now()
191
- session.merge(res)
192
- session.commit()
193
- session.refresh(res)
194
-
195
- return res
220
+ res = self._get(session, rname)
221
+
222
+ if res is not None:
223
+ # copy the file to cache
224
+ copy_or_move(str(fpath), str(res.rpath), rname, action)
225
+ res.access_time = res.last_modified_time = func.now()
226
+ session.merge(res)
227
+ session.commit()
228
+ session.refresh(res)
229
+ else:
230
+ # technically an error since update shouldn't be called on
231
+ # non-existent resources in cache.
232
+ # but lets just add it to the cache.
233
+ res = self.add(rname=rname, fpath=fpath, action=action)
234
+ return res
@@ -15,4 +15,11 @@ except PackageNotFoundError: # pragma: no cover
15
15
  finally:
16
16
  del version, PackageNotFoundError
17
17
 
18
- from .BiocFileCache import BiocFileCache
18
+ from .BiocFileCache import BiocFileCache as BiocFileCache
19
+
20
+ from .db.schema import Metadata as Metadata
21
+ from .db.schema import Resource as Resource
22
+
23
+ from ._exceptions import NoFpathError as NoFpathError
24
+ from ._exceptions import RnameExistsError as RnameExistsError
25
+ from ._exceptions import RpathTimeoutError as RpathTimeoutError
@@ -0,0 +1,15 @@
1
+ __author__ = "jkanche"
2
+ __copyright__ = "jkanche"
3
+ __license__ = "MIT"
4
+
5
+
6
+ class NoFpathError(Exception):
7
+ """An error for when the source file does not exist."""
8
+
9
+
10
+ class RnameExistsError(Exception):
11
+ """An error for when the key already exists in the cache."""
12
+
13
+
14
+ class RpathTimeoutError(Exception):
15
+ """An error for when the 'rpath' does not exist after a timeout."""
@@ -13,7 +13,7 @@ Base = declarative_base()
13
13
 
14
14
 
15
15
  def create_schema(cache_dir: str) -> Tuple[Engine, sessionmaker]:
16
- """Create the schema in the sqlite database
16
+ """Create the schema in the sqlite database.
17
17
 
18
18
  Args:
19
19
  cache_dir (str): Location where the cache directory
@@ -1,5 +1,6 @@
1
- from sqlalchemy import Column, Integer, String, DateTime
1
+ from sqlalchemy import Column, DateTime, Integer, String
2
2
  from sqlalchemy.sql import func
3
+
3
4
  from .Base import Base
4
5
 
5
6
  __author__ = "jkanche"
@@ -32,4 +33,3 @@ class Resource(Base):
32
33
 
33
34
  def __repr__(self):
34
35
  return "<Resource(id='%s', rname='%s')>" % (self.id, self.rname)
35
-
pybiocfilecache/utils.py CHANGED
@@ -9,7 +9,7 @@ import sys
9
9
 
10
10
 
11
11
  def create_tmp_dir() -> str:
12
- """create a temporary directory.
12
+ """Create a temporary directory.
13
13
 
14
14
  Returns:
15
15
  str: path to the directory
@@ -57,7 +57,7 @@ def copy_or_move(
57
57
 
58
58
 
59
59
  def setup_logging(loglevel):
60
- """Setup basic logging
60
+ """Setup basic logging.
61
61
 
62
62
  Args:
63
63
  loglevel (int): minimum loglevel for emitting messages
@@ -1,12 +0,0 @@
1
- pybiocfilecache/BiocFileCache.py,sha256=JNAx9PBY__xcmZc8WM8sCUrFUgyOK40bMWulIJPLV5M,6096
2
- pybiocfilecache/__init__.py,sha256=gdZzYl6g9kyM6qQRe70KSRE_F0Ahn31OWK5wdEy4Qt4,628
3
- pybiocfilecache/utils.py,sha256=HL_VagKHu2HlwT8ODID43ESOD1ERqSwDOGeQHHe8-YA,1782
4
- pybiocfilecache/db/Base.py,sha256=vfOWyRKFqPj4L4esuWb0MeCGu04xAz5bhAI1nl8IGjU,938
5
- pybiocfilecache/db/__init__.py,sha256=XE1DrTqLmDOM4Y4Qt3fdr6ahir5Vqug5e5v-DQexCDw,102
6
- pybiocfilecache/db/schema.py,sha256=FHsWCkfbUr8AwzS7zuvXCzS_cOj7uADxokiNm75yIeQ,1041
7
- pyBiocFileCache-0.2.1.dist-info/AUTHORS.md,sha256=j3yqoTV-_uShE0VwsxvcmANNhbMdudixmiBL-5cUCFo,111
8
- pyBiocFileCache-0.2.1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
9
- pyBiocFileCache-0.2.1.dist-info/METADATA,sha256=6gdUsvr2V6kkqsLdg3xU1pOpA0xtryyI8d-Jomvgx1Q,2200
10
- pyBiocFileCache-0.2.1.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
11
- pyBiocFileCache-0.2.1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
12
- pyBiocFileCache-0.2.1.dist-info/RECORD,,