pyBiocFileCache 0.5.2.dev1__py3-none-any.whl → 0.6.1__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.
- {pyBiocFileCache-0.5.2.dev1.dist-info → pyBiocFileCache-0.6.1.dist-info}/METADATA +3 -4
- pyBiocFileCache-0.6.1.dist-info/RECORD +13 -0
- {pyBiocFileCache-0.5.2.dev1.dist-info → pyBiocFileCache-0.6.1.dist-info}/WHEEL +1 -1
- pybiocfilecache/cache.py +74 -113
- pybiocfilecache/config.py +0 -9
- pybiocfilecache/const.py +1 -0
- pybiocfilecache/models.py +7 -15
- pybiocfilecache/utils.py +7 -1
- pyBiocFileCache-0.5.2.dev1.dist-info/RECORD +0 -15
- pybiocfilecache/migrations/__init__.py +0 -1
- pybiocfilecache/migrations/migration.py +0 -139
- pybiocfilecache/migrations/migrationV0_5_0.py +0 -102
- {pyBiocFileCache-0.5.2.dev1.dist-info → pyBiocFileCache-0.6.1.dist-info}/AUTHORS.md +0 -0
- {pyBiocFileCache-0.5.2.dev1.dist-info → pyBiocFileCache-0.6.1.dist-info}/LICENSE.txt +0 -0
- {pyBiocFileCache-0.5.2.dev1.dist-info → pyBiocFileCache-0.6.1.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: pyBiocFileCache
|
|
3
|
-
Version: 0.
|
|
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
|
[](https://pyscaffold.org/)
|
|
24
25
|
[](https://pypi.org/project/pyBiocFileCache/)
|
|
25
|
-

|
|
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
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
|
|
2
|
+
pybiocfilecache/cache.py,sha256=cBPQYW4EW5ACRvbWotYJaDkzJpNZhvPC2hPlFd9mAO4,20641
|
|
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=oEQaLB9haWtSnm8DybMoMf8INZ4czxs7jriHv61YCb8,1945
|
|
7
|
+
pybiocfilecache/utils.py,sha256=a2sUcnWzu8F0nwdmun8Ke0hj0-bFJ5JF-Z1tq9NT0NM,2406
|
|
8
|
+
pyBiocFileCache-0.6.1.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
|
|
9
|
+
pyBiocFileCache-0.6.1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
|
|
10
|
+
pyBiocFileCache-0.6.1.dist-info/METADATA,sha256=KhKuU1Dbho0go2sWVpVrrm2WHTDPFn_doktKrqNRdO8,2947
|
|
11
|
+
pyBiocFileCache-0.6.1.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
|
|
12
|
+
pyBiocFileCache-0.6.1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
|
|
13
|
+
pyBiocFileCache-0.6.1.dist-info/RECORD,,
|
pybiocfilecache/cache.py
CHANGED
|
@@ -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
|
-
-
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
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) ->
|
|
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,
|
|
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,
|
|
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
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
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",
|
|
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()
|
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/const.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
SCHEMA_VERSION = "0.99.4"
|
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()
|
|
71
|
-
rname = Column(Text()
|
|
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(
|
|
76
|
+
return f"<Resource(rid='{self.rid}', rname='{self.rname}')>"
|
pybiocfilecache/utils.py
CHANGED
|
@@ -22,11 +22,17 @@ def create_tmp_dir() -> Path:
|
|
|
22
22
|
return Path(tempfile.mkdtemp())
|
|
23
23
|
|
|
24
24
|
|
|
25
|
-
def
|
|
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))
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
|
|
2
|
-
pybiocfilecache/cache.py,sha256=Ij8-3-_4sTWLlSmXRqyIZXIZpNqKL2_j1u14EVS261w,22135
|
|
3
|
-
pybiocfilecache/config.py,sha256=hfknpMCzNk6wt84lTvbfH3Z0g66u_-2Fer3AftgDJBA,1040
|
|
4
|
-
pybiocfilecache/exceptions.py,sha256=8jrnctFYF7Rc1xsITtLUwKKvx8GMoKbarucyc-4f2zI,706
|
|
5
|
-
pybiocfilecache/models.py,sha256=A6BIrT78qqURxJoDvBjkDRBFV5cLdi3WKxreSCPB9tw,2125
|
|
6
|
-
pybiocfilecache/utils.py,sha256=lBK4BmzT6Z7XCn4j8kmhz9BPQpWT-RYfWvWC7YNtIGM,2291
|
|
7
|
-
pybiocfilecache/migrations/__init__.py,sha256=hGgAPQfmQKqZgGtEaB0FaHqDL3weTAPDTjewpUpZuEE,32
|
|
8
|
-
pybiocfilecache/migrations/migration.py,sha256=v9YEcOH9-x-6FLM_P1yXg-0506zZ98TdCCPuu4QPulE,4693
|
|
9
|
-
pybiocfilecache/migrations/migrationV0_5_0.py,sha256=yRoGmCmGQxAo7eZ3SLd64kCwovXWgU77NkxBMhzKVVA,3044
|
|
10
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
|
|
11
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
|
|
12
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/METADATA,sha256=kKv4GJRDnkS8sD7Floh5r1OrpBySIUtjQoj3GvoeC8Y,2996
|
|
13
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
|
14
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
|
|
15
|
-
pyBiocFileCache-0.5.2.dev1.dist-info/RECORD,,
|
|
@@ -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
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|