pyBiocFileCache 0.5.1__py3-none-any.whl → 0.6.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,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyBiocFileCache
3
- Version: 0.5.1
3
+ Version: 0.6.0
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
@@ -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
@@ -0,0 +1,13 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=N1xJFCDFINvWxDKwO7ibPiFOJHQOTlr_IV6UrxIW8Bk,20434
3
+ pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
4
+ pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
+ pybiocfilecache/exceptions.py,sha256=8jrnctFYF7Rc1xsITtLUwKKvx8GMoKbarucyc-4f2zI,706
6
+ pybiocfilecache/models.py,sha256=inFECbprbU6W67XAkx8-Wbj3p57PdVlerb1SRvp1WlY,1943
7
+ pybiocfilecache/utils.py,sha256=lBK4BmzT6Z7XCn4j8kmhz9BPQpWT-RYfWvWC7YNtIGM,2291
8
+ pyBiocFileCache-0.6.0.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
9
+ pyBiocFileCache-0.6.0.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
+ pyBiocFileCache-0.6.0.dist-info/METADATA,sha256=xFfkcCK-paxNVnt02VWdvxO39zgUkorb5cCp8usgWG4,2947
11
+ pyBiocFileCache-0.6.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
12
+ pyBiocFileCache-0.6.0.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
+ pyBiocFileCache-0.6.0.dist-info/RECORD,,
pybiocfilecache/cache.py CHANGED
@@ -6,14 +6,14 @@ from pathlib import Path
6
6
  from time import sleep, time
7
7
  from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
8
8
 
9
- from sqlalchemy import create_engine, func
9
+ from sqlalchemy import create_engine, func, text
10
10
  from sqlalchemy.orm import Session, sessionmaker
11
11
  from sqlalchemy.pool import QueuePool
12
12
 
13
13
  from .config import CacheConfig
14
+ from .const import SCHEMA_VERSION
14
15
  from .exceptions import (
15
16
  BiocCacheError,
16
- CacheSizeLimitError,
17
17
  InvalidRnameError,
18
18
  NoFpathError,
19
19
  RnameExistsError,
@@ -25,7 +25,6 @@ from .utils import (
25
25
  copy_or_move,
26
26
  create_tmp_dir,
27
27
  generate_id,
28
- get_file_size,
29
28
  validate_rname,
30
29
  )
31
30
 
@@ -42,9 +41,7 @@ class BiocFileCache:
42
41
  Features:
43
42
  - Resource validation and integrity checking
44
43
  - Cache size management
45
- - File compression
46
- - Resource tagging
47
- - Automatic cleanup of expired resources
44
+ - Cleanup of expired resources
48
45
  """
49
46
 
50
47
  def __init__(self, cache_dir: Optional[Union[str, Path]] = None, config: Optional[CacheConfig] = None):
@@ -66,10 +63,15 @@ class BiocFileCache:
66
63
 
67
64
  self.config = config
68
65
  self._setup_cache_dir()
69
- self._setup_database()
66
+ db_schema_version = self._setup_database()
67
+
68
+ if db_schema_version != SCHEMA_VERSION:
69
+ print(db_schema_version)
70
+ raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
71
+
70
72
  self._last_cleanup = datetime.now()
71
73
 
72
- def _setup_cache_dir(self) -> None:
74
+ def _setup_cache_dir(self) -> bool:
73
75
  if not self.config.cache_dir.exists():
74
76
  self.config.cache_dir.mkdir(parents=True, exist_ok=True)
75
77
 
@@ -87,6 +89,28 @@ class BiocFileCache:
87
89
  Base.metadata.create_all(self.engine)
88
90
  self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
89
91
 
92
+ with self.engine.connect() as conn:
93
+ result = conn.execute(
94
+ text("""
95
+ SELECT value FROM metadata
96
+ WHERE key = 'schema_version'
97
+ """)
98
+ )
99
+ row = result.fetchone()
100
+
101
+ if row is not None:
102
+ return row[0]
103
+
104
+ conn.execute(
105
+ text("""
106
+ INSERT INTO metadata (key, value)
107
+ VALUES ('schema_version', :version);
108
+ """),
109
+ {"version": SCHEMA_VERSION},
110
+ )
111
+
112
+ return SCHEMA_VERSION
113
+
90
114
  def _get_detached_resource(self, session: Session, resource: Resource) -> Optional[Resource]:
91
115
  """Get a detached copy of a resource."""
92
116
  if resource is None:
@@ -118,17 +142,6 @@ class BiocFileCache:
118
142
  finally:
119
143
  session.close()
120
144
 
121
- def _check_cache_size(self, new_size: int) -> None:
122
- """Verify cache size limit won't be exceeded."""
123
- if self.config.max_size_bytes is None:
124
- return
125
-
126
- current_size = self.get_cache_size()
127
- if current_size + new_size > self.config.max_size_bytes:
128
- raise CacheSizeLimitError(
129
- f"Adding {new_size} bytes would exceed cache limit of " f"{self.config.max_size_bytes} bytes"
130
- )
131
-
132
145
  def _validate_rname(self, rname: str) -> None:
133
146
  """Validate resource name format."""
134
147
  if not validate_rname(rname, self.config.rname_pattern):
@@ -218,7 +231,6 @@ class BiocFileCache:
218
231
  fpath: Union[str, Path],
219
232
  rtype: Literal["local", "web", "relative"] = "local",
220
233
  action: Literal["copy", "move", "asis"] = "copy",
221
- tags: Optional[List[str]] = None,
222
234
  expires: Optional[datetime] = None,
223
235
  ext: bool = False,
224
236
  ) -> Resource:
@@ -240,9 +252,6 @@ class BiocFileCache:
240
252
  How to handle the file ("copy", "move", or "asis").
241
253
  Defaults to ``copy``.
242
254
 
243
- tags:
244
- Optional list of tags for categorization.
245
-
246
255
  expires:
247
256
  Optional expiration datetime.
248
257
  If None, resource never expires.
@@ -267,8 +276,6 @@ class BiocFileCache:
267
276
  rid = generate_id()
268
277
  rpath = self.config.cache_dir / f"{rid}{fpath.suffix if ext else ''}" if action != "asis" else fpath
269
278
 
270
- self._check_cache_size(get_file_size(fpath))
271
-
272
279
  # Create resource record
273
280
  resource = Resource(
274
281
  rid=rid,
@@ -276,9 +283,7 @@ class BiocFileCache:
276
283
  rpath=str(rpath),
277
284
  rtype=rtype,
278
285
  fpath=str(fpath),
279
- tags=",".join(tags) if tags else None,
280
286
  expires=expires,
281
- size_bytes=get_file_size(fpath),
282
287
  )
283
288
 
284
289
  # Store file and update database
@@ -287,7 +292,7 @@ class BiocFileCache:
287
292
  session.commit()
288
293
 
289
294
  try:
290
- copy_or_move(fpath, rpath, rname, action, self.config.compression)
295
+ copy_or_move(fpath, rpath, rname, action, False)
291
296
 
292
297
  # Calculate and store checksum
293
298
  resource.etag = calculate_file_hash(rpath, self.config.hash_algorithm)
@@ -324,7 +329,6 @@ class BiocFileCache:
324
329
  rname: str,
325
330
  fpath: Union[str, Path],
326
331
  action: Literal["copy", "move", "asis"] = "copy",
327
- tags: Optional[List[str]] = None,
328
332
  ) -> Resource:
329
333
  """Update an existing resource.
330
334
 
@@ -339,9 +343,6 @@ class BiocFileCache:
339
343
  Either ``copy``, ``move`` or ``asis``.
340
344
  Defaults to ``copy``.
341
345
 
342
- tags:
343
- Optional new list of tags.
344
-
345
346
  Returns:
346
347
  Updated `Resource` object.
347
348
 
@@ -358,14 +359,10 @@ class BiocFileCache:
358
359
 
359
360
  old_path = Path(resource.rpath)
360
361
  try:
361
- copy_or_move(fpath, old_path, rname, action, self.config.compression)
362
+ copy_or_move(fpath, old_path, rname, action, False)
362
363
 
363
364
  resource.last_modified_time = datetime.now()
364
365
  resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm)
365
- resource.size_bytes = get_file_size(old_path)
366
-
367
- if tags is not None:
368
- resource.tags = ",".join(tags)
369
366
 
370
367
  session.commit()
371
368
  return self._get_detached_resource(session, resource)
@@ -404,14 +401,10 @@ class BiocFileCache:
404
401
  session.rollback()
405
402
  raise BiocCacheError(f"Failed to remove resource '{rname}'") from e
406
403
 
407
- def list_resources(
408
- self, tag: Optional[str] = None, rtype: Optional[str] = None, expired: Optional[bool] = None
409
- ) -> List[Resource]:
404
+ def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
410
405
  """List resources in the cache with optional filtering.
411
406
 
412
407
  Args:
413
- tag:
414
- Filter resources by tag.
415
408
 
416
409
  rtype:
417
410
  Filter resources by type.
@@ -429,8 +422,6 @@ class BiocFileCache:
429
422
  with self.get_session() as session:
430
423
  query = session.query(Resource)
431
424
 
432
- if tag:
433
- query = query.filter(Resource.tags.like(f"%{tag}%"))
434
425
  if rtype:
435
426
  query = query.filter(Resource.rtype == rtype)
436
427
  if expired is not None:
@@ -468,11 +459,6 @@ class BiocFileCache:
468
459
  logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e)
469
460
  return False
470
461
 
471
- def get_cache_size(self) -> int:
472
- """Get total size of cached files in bytes."""
473
- with self.get_session() as session:
474
- return session.query(func.sum(Resource.size_bytes)).scalar() or 0
475
-
476
462
  def export_metadata(self, path: Path) -> None:
477
463
  """Export cache metadata to JSON file."""
478
464
  data = {
@@ -480,14 +466,11 @@ class BiocFileCache:
480
466
  {
481
467
  "rname": r.rname,
482
468
  "rtype": r.rtype,
483
- "tags": r.tags,
484
469
  "expires": r.expires.isoformat() if r.expires else None,
485
470
  "etag": r.etag,
486
- "size_bytes": r.size_bytes,
487
471
  }
488
472
  for r in self.list_resources()
489
473
  ],
490
- "cache_size": self.get_cache_size(),
491
474
  "export_time": datetime.now().isoformat(),
492
475
  }
493
476
 
@@ -503,7 +486,6 @@ class BiocFileCache:
503
486
  for resource_data in data["resources"]:
504
487
  resource = self._get(session, resource_data["rname"])
505
488
  if resource:
506
- resource.tags = resource_data["tags"]
507
489
  resource.expires = (
508
490
  datetime.fromisoformat(resource_data["expires"]) if resource_data["expires"] else None
509
491
  )
@@ -532,7 +514,7 @@ class BiocFileCache:
532
514
  Search string.
533
515
 
534
516
  field:
535
- Resource field to search ("rname", "rtype", "tags", etc.).
517
+ Resource field to search ("rname", "rtype", etc.).
536
518
 
537
519
  exact:
538
520
  Whether to require exact match.
@@ -565,7 +547,6 @@ class BiocFileCache:
565
547
  return {
566
548
  "total_resources": total,
567
549
  "expired_resources": expired,
568
- "cache_size_bytes": self.get_cache_size(),
569
550
  "resource_types": types,
570
551
  "last_cleanup": self._last_cleanup.isoformat(),
571
552
  "cleanup_enabled": self.config.cleanup_interval is not None,
pybiocfilecache/config.py CHANGED
@@ -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
pybiocfilecache/models.py CHANGED
@@ -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
76
  return f"<Resource(id='{self.id}', rname='{self.rname}')>"
@@ -1,13 +0,0 @@
1
- pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
- pybiocfilecache/cache.py,sha256=YOCur7R7209WBI6JEW3Q9VzD7ymu7Wj2DDLGEMFCeDo,21395
3
- pybiocfilecache/config.py,sha256=hfknpMCzNk6wt84lTvbfH3Z0g66u_-2Fer3AftgDJBA,1040
4
- pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
- pybiocfilecache/exceptions.py,sha256=8jrnctFYF7Rc1xsITtLUwKKvx8GMoKbarucyc-4f2zI,706
6
- pybiocfilecache/models.py,sha256=A6BIrT78qqURxJoDvBjkDRBFV5cLdi3WKxreSCPB9tw,2125
7
- pybiocfilecache/utils.py,sha256=lBK4BmzT6Z7XCn4j8kmhz9BPQpWT-RYfWvWC7YNtIGM,2291
8
- pyBiocFileCache-0.5.1.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
9
- pyBiocFileCache-0.5.1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
10
- pyBiocFileCache-0.5.1.dist-info/METADATA,sha256=N1hNP2VEuDt-u2maLQW9b5qmS7llNtkKgGUusWNpolU,2991
11
- pyBiocFileCache-0.5.1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
12
- pyBiocFileCache-0.5.1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
13
- pyBiocFileCache-0.5.1.dist-info/RECORD,,