pyBiocFileCache 0.6.2__py3-none-any.whl → 0.8.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.
pybiocfilecache/cache.py CHANGED
@@ -1,10 +1,15 @@
1
+ from __future__ import annotations
2
+
1
3
  import logging
4
+ import shutil
5
+ from collections.abc import Iterator
2
6
  from contextlib import contextmanager
3
- from datetime import datetime
7
+ from datetime import datetime, timezone
4
8
  from pathlib import Path
5
9
  from time import sleep, time
6
- from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
10
+ from typing import Any, Literal
7
11
 
12
+ from biocframe import BiocFrame
8
13
  from sqlalchemy import create_engine, func, text
9
14
  from sqlalchemy.orm import Session, sessionmaker
10
15
  from sqlalchemy.pool import QueuePool
@@ -14,6 +19,7 @@ from .const import SCHEMA_VERSION
14
19
  from .models import Base, Metadata, Resource
15
20
  from .utils import (
16
21
  calculate_file_hash,
22
+ convert_to_columnar,
17
23
  copy_or_move,
18
24
  create_tmp_dir,
19
25
  download_web_file,
@@ -28,6 +34,19 @@ __license__ = "MIT"
28
34
  logger = logging.getLogger(__name__)
29
35
 
30
36
 
37
+ def _now() -> datetime:
38
+ """Return current UTC time as a naive datetime matching SQLite CURRENT_TIMESTAMP."""
39
+ return datetime.now(timezone.utc).replace(tzinfo=None)
40
+
41
+
42
+ def _normalize_datetime(dt: datetime | None) -> datetime | None:
43
+ """Normalize an optional datetime to naive UTC."""
44
+ if dt is not None and dt.tzinfo is not None:
45
+ return dt.astimezone(timezone.utc).replace(tzinfo=None)
46
+
47
+ return dt
48
+
49
+
31
50
  class BiocFileCache:
32
51
  """Enhanced file caching module.
33
52
 
@@ -37,7 +56,7 @@ class BiocFileCache:
37
56
  - Cleanup of expired resources
38
57
  """
39
58
 
40
- def __init__(self, cache_dir: Optional[Union[str, Path]] = None, config: Optional[CacheConfig] = None):
59
+ def __init__(self, cache_dir: str | Path | None = None, config: CacheConfig | None = None):
41
60
  """Initialize cache with optional configuration.
42
61
 
43
62
  Args:
@@ -61,7 +80,7 @@ class BiocFileCache:
61
80
  if db_schema_version != SCHEMA_VERSION:
62
81
  raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
63
82
 
64
- self._last_cleanup = datetime.now()
83
+ self._last_cleanup = _now()
65
84
 
66
85
  def _setup_cache_dir(self) -> bool:
67
86
  if not self.config.cache_dir.exists():
@@ -82,6 +101,7 @@ class BiocFileCache:
82
101
  self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
83
102
 
84
103
  with self.engine.connect() as conn:
104
+ self._ensure_autoincrement(conn)
85
105
  result = conn.execute(
86
106
  text("""
87
107
  SELECT value FROM metadata
@@ -104,17 +124,65 @@ class BiocFileCache:
104
124
 
105
125
  return SCHEMA_VERSION
106
126
 
107
- def _get_detached_resource(
108
- self, session: Session, obj: Union[Resource, Metadata]
109
- ) -> Optional[Union[Resource, Metadata]]:
127
+ def _ensure_autoincrement(self, conn) -> None:
128
+ """Migrate legacy resource table without AUTOINCREMENT so SQLite never reuses deleted row IDs."""
129
+ row = conn.execute(text("SELECT sql FROM sqlite_master WHERE type='table' AND name='resource'")).fetchone()
130
+ if row is None or not row[0] or "AUTOINCREMENT" in row[0].upper():
131
+ return
132
+
133
+ dup_count = conn.execute(
134
+ text("SELECT COUNT(*) - COUNT(DISTINCT rid) FROM resource WHERE rid IS NOT NULL")
135
+ ).scalar()
136
+ unique_clause = ", UNIQUE (rid)" if not dup_count else ""
137
+
138
+ cols = "id, rid, rname, create_time, access_time, rpath, rtype, fpath, last_modified_time, etag, expires"
139
+ conn.execute(
140
+ text(
141
+ f"""
142
+ CREATE TABLE resource_new (
143
+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
144
+ rid TEXT,
145
+ rname TEXT,
146
+ create_time DATETIME DEFAULT (CURRENT_TIMESTAMP),
147
+ access_time DATETIME DEFAULT (CURRENT_TIMESTAMP),
148
+ rpath TEXT,
149
+ rtype TEXT,
150
+ fpath TEXT,
151
+ last_modified_time DATETIME,
152
+ etag TEXT,
153
+ expires DATETIME{unique_clause}
154
+ )
155
+ """
156
+ )
157
+ )
158
+ conn.execute(text(f"INSERT INTO resource_new ({cols}) SELECT {cols} FROM resource"))
159
+ conn.execute(text("DROP TABLE resource"))
160
+ conn.execute(text("ALTER TABLE resource_new RENAME TO resource"))
161
+ conn.execute(text("CREATE INDEX IF NOT EXISTS ix_resource_id ON resource (id)"))
162
+ conn.commit()
163
+
164
+ def _resolve_rpath(self, rpath: str, rtype: str | None) -> Path:
165
+ """Resolve a stored resource path against cache_dir when relative."""
166
+ path = Path(rpath)
167
+ if rtype in ("relative", "web") and not path.is_absolute():
168
+ return self.config.cache_dir / path
169
+
170
+ return path
171
+
172
+ def _get_detached_resource(self, session: Session, obj: Resource | Metadata) -> dict | None:
110
173
  """Get a detached copy of a resource."""
111
174
  if obj is None:
112
175
  return None
113
176
  session.refresh(obj)
114
177
  session.expunge(obj)
115
- return obj
178
+ obj_dict = obj.to_dict()
116
179
 
117
- def __enter__(self) -> "BiocFileCache":
180
+ if isinstance(obj, Resource) and obj_dict["rtype"] in ("relative", "web"):
181
+ obj_dict["rpath"] = str(self._resolve_rpath(obj_dict["rpath"], obj_dict["rtype"]))
182
+
183
+ return obj_dict
184
+
185
+ def __enter__(self) -> BiocFileCache:
118
186
  return self
119
187
 
120
188
  def __exit__(self, exc_type, exc_val, exc_tb) -> None:
@@ -137,6 +205,10 @@ class BiocFileCache:
137
205
  finally:
138
206
  session.close()
139
207
 
208
+ #########################
209
+ ######>> cleanup <<######
210
+ #########################
211
+
140
212
  # def _validate_rname(self, rname: str) -> None:
141
213
  # """Validate resource name format."""
142
214
  # if not validate_rname(rname, self.config.rname_pattern):
@@ -151,7 +223,7 @@ class BiocFileCache:
151
223
  if self.config.cleanup_interval is None:
152
224
  return False
153
225
 
154
- return datetime.now() - self._last_cleanup > self.config.cleanup_interval
226
+ return _now() - self._last_cleanup > self.config.cleanup_interval
155
227
 
156
228
  def cleanup(self) -> int:
157
229
  """Remove expired resources from the cache.
@@ -160,27 +232,25 @@ class BiocFileCache:
160
232
  Number of resources removed.
161
233
 
162
234
  Note:
163
- - If `cleanup_interval` is None, this method will still run if called explicitly.
235
+ - Runs whenever called explicitly, even if `cleanup_interval` is None.
164
236
  - Only removes resources with non-None expiration dates.
165
237
  """
166
- if not any([self.config.cleanup_interval, self._should_cleanup()]):
167
- return 0 # Early return if automatic cleanup is disabled
168
-
169
238
  removed = 0
239
+ now = _now()
170
240
  with self.get_session() as session:
171
241
  # Only query resources that have expiration dates
172
242
  expired = (
173
243
  session.query(Resource)
174
244
  .filter(
175
245
  Resource.expires.isnot(None), # Only check resources with expiration
176
- Resource.expires < datetime.now(),
246
+ Resource.expires < now,
177
247
  )
178
248
  .all()
179
249
  )
180
250
 
181
251
  for resource in expired:
182
252
  try:
183
- Path(resource.rpath).unlink(missing_ok=True)
253
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
184
254
  session.delete(resource)
185
255
  removed += 1
186
256
  except Exception as e:
@@ -188,11 +258,22 @@ class BiocFileCache:
188
258
 
189
259
  session.commit()
190
260
 
191
- self._last_cleanup = datetime.now()
261
+ self._last_cleanup = now
192
262
  return removed
193
263
 
194
- def get(self, rname: str = None, rid: str = None) -> Optional[Resource]:
195
- """Get resource by name from cache.
264
+ ###############################
265
+ ######>> get resources <<######
266
+ ###############################
267
+
268
+ def get(
269
+ self,
270
+ rname: str | None = None,
271
+ rid: str | None = None,
272
+ wait: bool = True,
273
+ timeout: float = 30,
274
+ update_access_time: bool = True,
275
+ ) -> dict | None:
276
+ """Get resource by name or id from cache.
196
277
 
197
278
  Args:
198
279
  rname:
@@ -201,44 +282,126 @@ class BiocFileCache:
201
282
  rid:
202
283
  Resource id to search by.
203
284
 
285
+ wait:
286
+ Whether to wait for the cached file to exist on disk.
287
+ If False, returns the registered record immediately even if
288
+ the file is missing. Defaults to True.
289
+
290
+ timeout:
291
+ Maximum seconds to wait when `wait=True`. Defaults to 30.
292
+
293
+ update_access_time:
294
+ Whether to update `access_time` in the database when the
295
+ cached file exists. Set to False for read-only lookups.
296
+ Defaults to True.
297
+
204
298
  """
205
299
  if rname is None and rid is None:
206
300
  raise ValueError("either 'rname' or 'rid' must be provided.")
207
301
 
208
302
  with self.get_session() as session:
209
- if rname is not None:
210
- resource = session.query(Resource).filter(Resource.rname == rname).first()
211
- elif rid is not None:
303
+ if rid is not None:
212
304
  resource = session.query(Resource).filter(Resource.rid == rid).first()
305
+ else:
306
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
213
307
 
214
308
  if resource is not None:
215
- # Check if path exists with timeout
216
- start = time()
217
- timeout = 30
218
- while not Path(str(resource.rpath)).exists():
219
- if time() - start >= timeout:
220
- raise TimeoutError(
221
- f"For resource: '{rname}' the rpath does not exist " f"after {timeout} seconds."
222
- )
223
- sleep(0.1)
224
-
225
- # Update access time
226
- resource.access_time = datetime.now()
227
- session.commit()
309
+ resolved_path = self._resolve_rpath(resource.rpath, resource.rtype)
310
+ if wait:
311
+ start = time()
312
+ while not resolved_path.exists():
313
+ if time() - start >= timeout:
314
+ identifier = rid if rid is not None else rname
315
+ raise TimeoutError(
316
+ f"For resource: '{identifier}' the rpath does not exist after {timeout} seconds."
317
+ )
318
+ sleep(0.1)
319
+
320
+ if update_access_time and resolved_path.exists():
321
+ resource.access_time = _now()
322
+ session.commit()
323
+
228
324
  return self._get_detached_resource(session, resource)
229
325
 
230
326
  return None
231
327
 
328
+ def _add_to_session(
329
+ self,
330
+ session: Session,
331
+ rname: str,
332
+ fpath: str | Path,
333
+ rtype: Literal["local", "web", "relative"] = "relative",
334
+ action: Literal["copy", "move", "asis"] = "copy",
335
+ expires: datetime | None = None,
336
+ download: bool = True,
337
+ ext: bool = True,
338
+ ) -> tuple[Resource, Path | None]:
339
+ """Insert a resource record and store its file within an active session."""
340
+ if session.query(Resource).filter(Resource.rname == rname).first() is not None:
341
+ raise FileExistsError(f"Resource '{rname}' already exists")
342
+
343
+ fpath_val = Path(fpath) if rtype != "web" else fpath
344
+ tmp_dir: Path | None = None
345
+
346
+ if rtype == "web":
347
+ outpath = download_web_file(str(fpath_val), None, download)
348
+ tmp_dir = outpath.parent
349
+ action = "copy"
350
+ else:
351
+ outpath = Path(fpath_val)
352
+
353
+ if action == "asis":
354
+ if rtype != "local":
355
+ logger.warning("If action='asis', rtype must be 'local'.")
356
+ rtype = "local"
357
+ elif rtype == "local":
358
+ rtype = "relative"
359
+
360
+ uuid_str = generate_uuid()
361
+ rpath = f"{uuid_str}_{outpath.name if ext else outpath.stem}" if action != "asis" else str(fpath_val)
362
+
363
+ resource = Resource(
364
+ rid=None,
365
+ rname=rname,
366
+ rpath=str(rpath),
367
+ rtype=rtype,
368
+ fpath=str(fpath_val),
369
+ expires=_normalize_datetime(expires),
370
+ )
371
+
372
+ copied_target: Path | None = None
373
+ try:
374
+ session.add(resource)
375
+ session.flush()
376
+ resource.rid = generate_id(resource.id)
377
+
378
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
379
+ copy_or_move(outpath, target_path, rname, action, False)
380
+ if action != "asis":
381
+ copied_target = target_path
382
+
383
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
384
+
385
+ return resource, copied_target
386
+ except Exception:
387
+ if copied_target is not None and copied_target.exists():
388
+ copied_target.unlink(missing_ok=True)
389
+
390
+ raise
391
+ finally:
392
+ if tmp_dir is not None:
393
+ shutil.rmtree(tmp_dir, ignore_errors=True)
394
+
232
395
  def add(
233
396
  self,
234
397
  rname: str,
235
- fpath: Union[str, Path],
398
+ fpath: str | Path,
236
399
  rtype: Literal["local", "web", "relative"] = "relative",
237
400
  action: Literal["copy", "move", "asis"] = "copy",
238
- expires: Optional[datetime] = None,
401
+ expires: datetime | None = None,
239
402
  download: bool = True,
240
403
  ext: bool = True,
241
- ) -> Resource:
404
+ ) -> dict:
242
405
  """Add a resource to the cache.
243
406
 
244
407
  Args:
@@ -251,7 +414,7 @@ class BiocFileCache:
251
414
  rtype:
252
415
  Type of resource.
253
416
  One of ``local``, ``web``, or ``relative``.
254
- Defaults to ``local``.
417
+ Defaults to ``relative``.
255
418
 
256
419
  action:
257
420
  How to handle the file ("copy", "move", or "asis").
@@ -270,83 +433,68 @@ class BiocFileCache:
270
433
  Defaults to `True`.
271
434
 
272
435
  Returns:
273
- The `Resource` object added to the cache.
436
+ The `Resource` object added to the cache as dictionary.
274
437
  """
275
- # self._validate_rname(rname)
276
- fpath = Path(fpath) if rtype != "web" else fpath
277
-
278
- if self.get(rname) is not None:
279
- raise FileExistsError(f"Resource '{rname}' already exists")
280
-
281
- if rtype == "web":
282
- outpath = download_web_file(fpath, Path(fpath).name, download)
283
- action = "copy"
284
- else:
285
- outpath = Path(fpath)
286
-
287
- if action == "asis":
288
- logger.warning("If action='asis', rtype must be 'local'.")
289
- rtype = "local"
290
-
291
- # Generate paths and check size
292
- rid = generate_id(size=len(self))
293
- uuid = generate_uuid()
294
- rpath = self.config.cache_dir / f"{uuid}_{outpath.name if ext else outpath.stem}" if action != "asis" else fpath
295
-
296
- # Create resource record
297
- resource = Resource(
298
- rid=rid,
299
- rname=rname,
300
- rpath=str(rpath),
301
- rtype=rtype,
302
- fpath=str(fpath),
303
- expires=expires,
304
- )
305
-
306
- # Store file and update database
307
438
  with self.get_session() as session:
308
- session.add(resource)
309
- session.commit()
310
-
311
439
  try:
312
- copy_or_move(outpath, rpath, rname, action, False)
313
-
314
- # Calculate and store checksum
315
- resource.etag = calculate_file_hash(rpath, self.config.hash_algorithm)
440
+ resource, _ = self._add_to_session(
441
+ session=session,
442
+ rname=rname,
443
+ fpath=fpath,
444
+ rtype=rtype,
445
+ action=action,
446
+ expires=expires,
447
+ download=download,
448
+ ext=ext,
449
+ )
316
450
  session.commit()
317
- result = self._get_detached_resource(session, resource)
318
- return result
319
451
 
452
+ return self._get_detached_resource(session, resource)
453
+ except FileExistsError:
454
+ session.rollback()
455
+ raise
320
456
  except Exception as e:
321
- session.delete(resource)
322
- session.commit()
457
+ session.rollback()
323
458
  raise Exception("Failed to add resource") from e
324
459
 
325
- def add_batch(self, resources: List[Dict[str, Any]]) -> List[Resource]:
460
+ def add_batch(self, resources: list[dict[str, Any]]) -> BiocFrame:
326
461
  """Add multiple resources in a single transaction.
327
462
 
328
463
  Args:
329
464
  resources:
330
465
  List of resources to add.
331
466
  """
332
- results = []
467
+ added_resources: list[Resource] = []
468
+ copied_targets: list[Path] = []
333
469
  with self.get_session() as session:
334
- for resource_info in resources:
335
- try:
336
- resource = self.add(**resource_info)
337
- results.append(resource)
338
- except Exception as e:
339
- logger.error(f"Failed to add resource: {resource_info.get('rname')}", exc_info=e)
340
- session.rollback()
341
- raise
342
- return results
470
+ try:
471
+ for resource_info in resources:
472
+ resource, copied_target = self._add_to_session(session=session, **resource_info)
473
+ added_resources.append(resource)
474
+ if copied_target is not None:
475
+ copied_targets.append(copied_target)
476
+
477
+ session.commit()
478
+
479
+ return BiocFrame(
480
+ convert_to_columnar([self._get_detached_resource(session, r) for r in added_resources])
481
+ )
482
+ except Exception as e:
483
+ logger.error("Failed to add batch of resources", exc_info=e)
484
+ session.rollback()
485
+
486
+ for target in copied_targets:
487
+ target.unlink(missing_ok=True)
488
+
489
+ raise
343
490
 
344
491
  def update(
345
492
  self,
346
- rname: str,
347
- fpath: Union[str, Path],
493
+ rname: str | None = None,
494
+ fpath: str | Path = None,
348
495
  action: Literal["copy", "move", "asis"] = "copy",
349
- ) -> Resource:
496
+ rid: str | None = None,
497
+ ) -> dict:
350
498
  """Update an existing resource.
351
499
 
352
500
  Args:
@@ -360,36 +508,62 @@ class BiocFileCache:
360
508
  Either ``copy``, ``move`` or ``asis``.
361
509
  Defaults to ``copy``.
362
510
 
511
+ rid:
512
+ Optional resource id to identify the resource.
513
+
363
514
  Returns:
364
- Updated `Resource` object.
515
+ Updated `Resource` object as dictionary.
365
516
 
366
517
  """
518
+ if rname is None and rid is None:
519
+ raise ValueError("either 'rname' or 'rid' must be provided.")
520
+
521
+ if fpath is None:
522
+ raise ValueError("'fpath' must be provided.")
523
+
367
524
  fpath = Path(fpath)
368
525
  if not fpath.exists():
369
526
  raise FileNotFoundError(f"File '{fpath}' does not exist")
370
527
 
371
528
  with self.get_session() as session:
372
- resource = session.query(Resource).filter(Resource.rname == rname).first()
529
+ if rid is not None:
530
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
531
+ else:
532
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
373
533
 
374
534
  if resource is None:
535
+ if rname is None:
536
+ raise KeyError(f"Resource with rid '{rid}' not found")
375
537
  return self.add(rname=rname, fpath=fpath, action=action)
376
538
 
377
- old_path = Path(resource.rpath)
378
539
  try:
379
- copy_or_move(fpath, old_path, rname, action, False)
540
+ if action == "asis":
541
+ resource.rpath = str(fpath)
542
+ resource.rtype = "local"
543
+ target_path = fpath
544
+ else:
545
+ if resource.rtype == "local":
546
+ resource.rtype = "relative"
547
+ resource.rpath = f"{generate_uuid()}_{fpath.name}"
380
548
 
381
- resource.last_modified_time = datetime.now()
382
- resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm)
549
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
550
+ copy_or_move(fpath, target_path, resource.rname, action, False)
551
+
552
+ resource.fpath = str(fpath)
553
+ resource.last_modified_time = _now()
554
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
383
555
 
384
556
  session.commit()
557
+
385
558
  return self._get_detached_resource(session, resource)
386
559
 
387
560
  except Exception as e:
388
561
  session.rollback()
562
+
389
563
  raise Exception("Failed to update resource") from e
390
564
 
391
- def remove(self, rname: str) -> None:
392
- """Remove a resource from cache by name.
565
+ def remove(self, rname: str | None = None, rid: str | None = None) -> None:
566
+ """Remove a resource from cache by name or id.
393
567
 
394
568
  Removes both the cached file and its database entry.
395
569
 
@@ -397,16 +571,25 @@ class BiocFileCache:
397
571
  rname:
398
572
  Name to identify the resource in cache.
399
573
 
574
+ rid:
575
+ Resource id to identify the resource in cache.
576
+
400
577
  Raises:
401
578
  Exception: If resource removal fails
402
579
  """
580
+ if rname is None and rid is None:
581
+ raise ValueError("either 'rname' or 'rid' must be provided.")
582
+
403
583
  with self.get_session() as session:
404
- resource = session.query(Resource).filter(Resource.rname == rname).first()
584
+ if rid is not None:
585
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
586
+ else:
587
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
405
588
 
406
589
  if resource is not None:
407
590
  try:
408
591
  # Try to remove the file first
409
- rpath = Path(resource.rpath)
592
+ rpath = self._resolve_rpath(resource.rpath, resource.rtype)
410
593
  if rpath.exists():
411
594
  rpath.unlink()
412
595
 
@@ -416,9 +599,10 @@ class BiocFileCache:
416
599
 
417
600
  except Exception as e:
418
601
  session.rollback()
419
- raise Exception(f"Failed to remove resource '{rname}'") from e
602
+ identifier = rid if rid is not None else rname
603
+ raise Exception(f"Failed to remove resource '{identifier}'") from e
420
604
 
421
- def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
605
+ def list_resources(self, rtype: str | None = None, expired: bool | None = None) -> BiocFrame:
422
606
  """List resources in the cache with optional filtering.
423
607
 
424
608
  Args:
@@ -434,7 +618,7 @@ class BiocFileCache:
434
618
  Note: Resources with no expiration are always considered non-expired.
435
619
 
436
620
  Returns:
437
- List of Resource objects matching the filters
621
+ List of Resource objects matching the filters.
438
622
  """
439
623
  with self.get_session() as session:
440
624
  query = session.query(Resource)
@@ -442,38 +626,52 @@ class BiocFileCache:
442
626
  if rtype:
443
627
  query = query.filter(Resource.rtype == rtype)
444
628
  if expired is not None:
629
+ now = _now()
445
630
  if expired:
446
631
  query = query.filter(
447
632
  Resource.expires.isnot(None), # Only check resources with expiration
448
- Resource.expires < datetime.now(),
633
+ Resource.expires < now,
449
634
  )
450
635
  else:
451
636
  query = query.filter(
452
637
  (Resource.expires.is_(None)) # Never expires
453
- | (Resource.expires > datetime.now()) # Not yet expired
638
+ | (Resource.expires > now) # Not yet expired
454
639
  )
455
640
 
456
641
  resources = query.all()
457
- return [self._get_detached_resource(session, r) for r in resources]
642
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
458
643
 
459
- def validate_resource(self, resource: Resource) -> bool:
644
+ def validate_resource(self, resource: Resource | dict) -> bool:
460
645
  """Validate resource integrity.
461
646
 
462
647
  Args:
463
648
  resource:
464
- Resource to validate.
649
+ Resource ORM object or dictionary to validate.
465
650
 
466
651
  Returns:
467
652
  True if resource is valid, False otherwise.
468
653
  """
469
- if not resource.etag:
654
+ if isinstance(resource, dict):
655
+ etag = resource.get("etag")
656
+ rpath = resource.get("rpath")
657
+ rtype = resource.get("rtype")
658
+ rname = resource.get("rname")
659
+ else:
660
+ etag = resource.etag
661
+ rpath = resource.rpath
662
+ rtype = resource.rtype
663
+ rname = resource.rname
664
+
665
+ if not etag:
470
666
  return True # No validation if no checksum
471
667
 
472
668
  try:
473
- current_hash = calculate_file_hash(Path(resource.rpath), self.config.hash_algorithm)
474
- return current_hash == resource.etag
669
+ resolved_path = self._resolve_rpath(rpath, rtype)
670
+ current_hash = calculate_file_hash(resolved_path, self.config.hash_algorithm)
671
+
672
+ return current_hash == etag
475
673
  except Exception as e:
476
- logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e)
674
+ logger.error(f"Failed to validate resource: {rname}", exc_info=e)
477
675
  return False
478
676
 
479
677
  # def export_metadata(self, path: Path) -> None:
@@ -509,21 +707,23 @@ class BiocFileCache:
509
707
  # session.merge(resource)
510
708
  # session.commit()
511
709
 
512
- def verify_cache(self) -> Tuple[int, int]:
710
+ def verify_cache(self) -> tuple[int, int]:
513
711
  """Verify integrity of all cached resources.
514
712
 
515
713
  Returns:
516
714
  Tuple of (valid_count, invalid_count).
517
715
  """
518
716
  valid = invalid = 0
519
- for resource in self.list_resources():
520
- if self.validate_resource(resource):
521
- valid += 1
522
- else:
523
- invalid += 1
717
+ with self.get_session() as session:
718
+ for resource in session.query(Resource).all():
719
+ if self.validate_resource(resource):
720
+ valid += 1
721
+ else:
722
+ invalid += 1
723
+
524
724
  return valid, invalid
525
725
 
526
- def search(self, query: str, field: str = "rname", exact: bool = False) -> List[Resource]:
726
+ def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame:
527
727
  """Search for resources by field value.
528
728
 
529
729
  Args:
@@ -537,17 +737,21 @@ class BiocFileCache:
537
737
  Whether to require exact match.
538
738
 
539
739
  Returns:
540
- List of matching resources.
740
+ BiocFrame of matching resources.
541
741
  """
742
+ if field not in Resource.__table__.columns:
743
+ raise ValueError(f"Invalid search field: '{field}'")
744
+
745
+ column = getattr(Resource, field)
542
746
  with self.get_session() as session:
543
747
  if exact:
544
- resources = session.query(Resource).filter(Resource[field] == query).all()
748
+ resources = session.query(Resource).filter(column == query).all()
545
749
  else:
546
- resources = session.query(Resource).filter(Resource[field].ilike(f"%{query}%")).all()
750
+ resources = session.query(Resource).filter(column.ilike(f"%{query}%")).all()
547
751
 
548
- return [self._get_detached_resource(session, r) for r in resources]
752
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
549
753
 
550
- def get_stats(self) -> Dict[str, Any]:
754
+ def get_stats(self) -> dict[str, Any]:
551
755
  """Get statistics about the cache."""
552
756
  with self.get_session() as session:
553
757
  total = session.query(Resource).count()
@@ -555,7 +759,7 @@ class BiocFileCache:
555
759
  session.query(Resource)
556
760
  .filter(
557
761
  Resource.expires.isnot(None), # Only check resources with expiration
558
- Resource.expires < datetime.now(),
762
+ Resource.expires < _now(),
559
763
  )
560
764
  .count()
561
765
  )
@@ -590,7 +794,7 @@ class BiocFileCache:
590
794
 
591
795
  for resource in resources:
592
796
  try:
593
- Path(resource.rpath).unlink(missing_ok=True)
797
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
594
798
  except Exception as e:
595
799
  if not force:
596
800
  session.rollback()
@@ -610,7 +814,7 @@ class BiocFileCache:
610
814
  except Exception as e:
611
815
  logger.warning(f"Failed to remove {file}: {e}")
612
816
 
613
- self._last_cleanup = datetime.now()
817
+ self._last_cleanup = _now()
614
818
  return True
615
819
 
616
820
  except Exception as e:
@@ -671,7 +875,7 @@ class BiocFileCache:
671
875
  except Exception as e:
672
876
  session.delete(meta)
673
877
  session.commit()
674
- raise Exception("Failed to add metadata") from e
878
+ raise Exception("Failed to add metadata", str(e)) from e
675
879
  else:
676
880
  raise Exception(f"'key'={key} already exists in metadata.")
677
881
 
pybiocfilecache/config.py CHANGED
@@ -1,7 +1,6 @@
1
1
  from dataclasses import dataclass
2
2
  from datetime import timedelta
3
3
  from pathlib import Path
4
- from typing import Optional
5
4
 
6
5
  __author__ = "Jayaram Kancherla"
7
6
  __copyright__ = "Jayaram Kancherla"
@@ -28,6 +27,6 @@ class CacheConfig:
28
27
  """
29
28
 
30
29
  cache_dir: Path
31
- cleanup_interval: Optional[timedelta] = None # timedelta(days=30)
30
+ cleanup_interval: timedelta | None = None # timedelta(days=30)
32
31
  rname_pattern: str = r"^[a-zA-Z0-9_-]+$"
33
32
  hash_algorithm: str = "md5"
pybiocfilecache/models.py CHANGED
@@ -19,6 +19,9 @@ class Metadata(Base):
19
19
  def __repr__(self) -> str:
20
20
  return f"<Metadata(key='{self.key}', value='{self.value}')>"
21
21
 
22
+ def to_dict(self) -> dict:
23
+ return {"key": self.key, "value": self.value}
24
+
22
25
 
23
26
  class Resource(Base):
24
27
  """Resource information stored in cache.
@@ -59,9 +62,10 @@ class Resource(Base):
59
62
  """
60
63
 
61
64
  __tablename__ = "resource"
65
+ __table_args__ = {"sqlite_autoincrement": True}
62
66
 
63
67
  id = Column(Integer, primary_key=True, index=True, autoincrement=True)
64
- rid = Column(Text())
68
+ rid = Column(Text(), unique=True)
65
69
  rname = Column(Text())
66
70
  create_time = Column(DateTime, server_default=func.now())
67
71
  access_time = Column(DateTime, server_default=func.now())
@@ -74,3 +78,18 @@ class Resource(Base):
74
78
 
75
79
  def __repr__(self) -> str:
76
80
  return f"<Resource(rid='{self.rid}', rname='{self.rname}', rpath='{self.rpath}')>"
81
+
82
+ def to_dict(self) -> dict:
83
+ return {
84
+ "id": self.id,
85
+ "rid": self.rid,
86
+ "rname": self.rname,
87
+ "create_time": self.create_time,
88
+ "access_time": self.access_time,
89
+ "rpath": self.rpath,
90
+ "rtype": self.rtype,
91
+ "fpath": self.fpath,
92
+ "last_modified_time": self.last_modified_time,
93
+ "etag": self.etag,
94
+ "expires": self.expires,
95
+ }
File without changes
pybiocfilecache/utils.py CHANGED
@@ -8,6 +8,7 @@ import zlib
8
8
  from pathlib import Path
9
9
  from shutil import copy2, move
10
10
  from typing import Literal
11
+ from urllib.parse import urlparse
11
12
 
12
13
  __author__ = "Jayaram Kancherla"
13
14
  __copyright__ = "Jayaram Kancherla"
@@ -26,10 +27,9 @@ def generate_uuid() -> str:
26
27
  return uuid.uuid4().hex
27
28
 
28
29
 
29
- def generate_id(size) -> str:
30
- """Generate unique identifier."""
31
- size += 1
32
- return "BFC" + str(size)
30
+ def generate_id(row_id: int) -> str:
31
+ """Generate unique resource identifier from database row id."""
32
+ return f"BFC{row_id}"
33
33
 
34
34
 
35
35
  def validate_rname(rname: str, pattern: str) -> bool:
@@ -43,6 +43,7 @@ def calculate_file_hash(path: Path, algorithm: str = "md5") -> str:
43
43
  with open(path, "rb") as f:
44
44
  for chunk in iter(lambda: f.read(4096), b""):
45
45
  hasher.update(chunk)
46
+
46
47
  return hasher.hexdigest()
47
48
 
48
49
 
@@ -88,7 +89,13 @@ def copy_or_move(
88
89
  raise Exception(f"Failed to store resource '{rname}' from '{source}' to '{target}'") from e
89
90
 
90
91
 
91
- def download_web_file(url: str, filename: str, download: bool):
92
+ def download_web_file(url: str, filename: str | None = None, download: bool = True) -> Path:
93
+ """Download a web resource into a temporary directory."""
94
+
95
+ if not filename:
96
+ parsed_name = Path(urlparse(str(url)).path).name
97
+ filename = parsed_name or "download"
98
+
92
99
  tmp_dir = create_tmp_dir()
93
100
  outpath = tmp_dir / filename
94
101
  if download:
@@ -97,3 +104,17 @@ def download_web_file(url: str, filename: str, download: bool):
97
104
  open(str(outpath), "a").close()
98
105
 
99
106
  return outpath
107
+
108
+
109
+ def convert_to_columnar(list_of_dicts: list[dict]):
110
+ if not list_of_dicts:
111
+ return {}
112
+
113
+ column_names = list_of_dicts[0].keys()
114
+ result = {col: [] for col in column_names}
115
+
116
+ for row in list_of_dicts:
117
+ for col in column_names:
118
+ result[col].append(row.get(col))
119
+
120
+ return result
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.5
2
+ Name: pybiocfilecache
3
+ Version: 0.8.0
4
+ Summary: File based cache for resources and metadata
5
+ Project-URL: Homepage, https://github.com/BiocPy/pybiocfilecache
6
+ Project-URL: Documentation, https://biocpy.github.io/pybiocfilecache
7
+ Project-URL: Repository, https://github.com/BiocPy/pybiocfilecache
8
+ Project-URL: Bug Tracker, https://github.com/BiocPy/pybiocfilecache/issues
9
+ Author-email: Jayaram Kancherla <jayaram.kancherla@gmail.com>
10
+ License: The MIT License (MIT)
11
+
12
+ Copyright (c) 2021 Genentech, Inc.
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: AUTHORS.md
32
+ License-File: LICENSE.txt
33
+ Keywords: biocfilecache,cache,file-cache,resource-management,sqlite
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Intended Audience :: Developers
36
+ Classifier: Intended Audience :: Science/Research
37
+ Classifier: License :: OSI Approved :: MIT License
38
+ Classifier: Operating System :: OS Independent
39
+ Classifier: Programming Language :: Python :: 3
40
+ Classifier: Programming Language :: Python :: 3.10
41
+ Classifier: Programming Language :: Python :: 3.11
42
+ Classifier: Programming Language :: Python :: 3.12
43
+ Classifier: Programming Language :: Python :: 3.13
44
+ Classifier: Programming Language :: Python :: 3.14
45
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
46
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
47
+ Requires-Python: >=3.9
48
+ Requires-Dist: biocframe
49
+ Requires-Dist: sqlalchemy
50
+ Provides-Extra: testing
51
+ Requires-Dist: pytest; extra == 'testing'
52
+ Requires-Dist: pytest-cov; extra == 'testing'
53
+ Requires-Dist: setuptools; extra == 'testing'
54
+ Description-Content-Type: text/markdown
55
+
56
+ ```{include} ../README.md
57
+ :relative-docs: docs/
58
+ :relative-images:
59
+ ```
@@ -0,0 +1,12 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=-5R14I5np3WRKLpGpxvMhuLez1bII_NF6WXurkMc2gk,30906
3
+ pybiocfilecache/config.py,sha256=4tm0aAiNdxOn3rqJNHHgAWRNV8c8iDB1FLMnK9tuA0c,772
4
+ pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
+ pybiocfilecache/models.py,sha256=6CFAmSLDhIBjBGU2leV6B4MxEZQQnJE0xrF55CRT6mw,2582
6
+ pybiocfilecache/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pybiocfilecache/utils.py,sha256=HzONrEmukpHVJkXKMrvVVV2DSwn2vynK_o72dggKtCE,3247
8
+ pybiocfilecache-0.8.0.dist-info/METADATA,sha256=6ur2OEuMM_psEfBvB-QIksO_WYXlK7PEWV-8cTMR9S4,2837
9
+ pybiocfilecache-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ pybiocfilecache-0.8.0.dist-info/licenses/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
11
+ pybiocfilecache-0.8.0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
12
+ pybiocfilecache-0.8.0.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.7.0)
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
-
@@ -1,115 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: pyBiocFileCache
3
- Version: 0.6.2
4
- Summary: File based cache for resources and metadata
5
- Home-page: https://github.com/epiviz/pyBiocFileCache
6
- Author: jkanche
7
- Author-email: jayaram.kancherla@gmail.com
8
- License: MIT
9
- Project-URL: Documentation, https://pyscaffold.org/
10
- Platform: any
11
- Classifier: Development Status :: 4 - Beta
12
- Classifier: Programming Language :: Python
13
- Requires-Python: >=3.9
14
- Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
15
- License-File: LICENSE.txt
16
- License-File: AUTHORS.md
17
- Requires-Dist: importlib-metadata; python_version < "3.8"
18
- Requires-Dist: sqlalchemy
19
- Provides-Extra: testing
20
- Requires-Dist: setuptools; extra == "testing"
21
- Requires-Dist: pytest; extra == "testing"
22
- Requires-Dist: pytest-cov; extra == "testing"
23
-
24
- [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
25
- [![PyPI-Server](https://img.shields.io/pypi/v/pyBiocFileCache.svg)](https://pypi.org/project/pyBiocFileCache/)
26
- ![Unit tests](https://github.com/BiocPy/pyBiocFileCache/actions/workflows/run-tests.yml/badge.svg)
27
-
28
- # pyBiocFileCache
29
-
30
- `pyBiocFileCache` is a Python package that provides a robust file caching system with resource validation, cache size management, file compression, and resource tagging. Compatible with [BiocFileCache R package](https://github.com/Bioconductor/BiocFileCache).
31
-
32
- ## Installation
33
-
34
- Install from [PyPI](https://pypi.org/project/pyBiocFileCache/),
35
-
36
- ```bash
37
- pip install pybiocfilecache
38
- ```
39
-
40
- ## Quick Start
41
-
42
- ```python
43
- from pybiocfilecache import BiocFileCache
44
-
45
- # Initialize cache
46
- cache = BiocFileCache("path/to/cache/directory")
47
-
48
- # Add a file to cache
49
- resource = cache.add("myfile", "path/to/file.txt")
50
-
51
- # Retrieve a file from cache
52
- resource = cache.get("myfile")
53
-
54
- # Use the cached file
55
- print(resource.rpath) # Path to cached file
56
- ```
57
-
58
- ## Advanced Usage
59
-
60
- ### Configuration
61
-
62
- ```python
63
- from pybiocfilecache import BiocFileCache, CacheConfig
64
- from datetime import timedelta
65
- from pathlib import Path
66
-
67
- # Create custom configuration
68
- config = CacheConfig(
69
- cache_dir=Path("cache_directory"),
70
- cleanup_interval=timedelta(days=7),
71
- )
72
-
73
- # Initialize cache with configuration
74
- cache = BiocFileCache(config=config)
75
- ```
76
-
77
- ### Resource Management
78
-
79
- ```python
80
- # Add file with tags and expiration
81
- from datetime import datetime, timedelta
82
-
83
- resource = cache.add(
84
- "myfile",
85
- "path/to/file.txt",
86
- tags=["data", "raw"],
87
- expires=datetime.now() + timedelta(days=30)
88
- )
89
-
90
- # List resources by tag
91
- resources = cache.list_resources(tag="data")
92
-
93
- # Search resources
94
- results = cache.search("myfile", field="rname")
95
-
96
- # Update resource
97
- cache.update("myfile", "path/to/new_file.txt")
98
-
99
- # Remove resource
100
- cache.remove("myfile")
101
- ```
102
-
103
- ### Cache Statistics and Maintenance
104
-
105
- ```python
106
- # Get cache statistics
107
- stats = cache.get_stats()
108
- print(stats)
109
-
110
- # Clean up expired resources
111
- removed_count = cache.cleanup()
112
-
113
- # Purge entire cache
114
- cache.purge()
115
- ```
@@ -1,12 +0,0 @@
1
- pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
- pybiocfilecache/cache.py,sha256=CW_jjF2lIbUf-ZpNe3LXhNxrtLnLoeMRzTYxgigTwps,23171
3
- pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
4
- pybiocfilecache/const.py,sha256=c9167eSCGBp0wF1xuAEvr-fbYCzp0lcOtKF9sqxlLF8,26
5
- pybiocfilecache/models.py,sha256=qxOZqmvKLloNygiQgr2ECtgXCZbvxOA_JoLLeM18mRA,1967
6
- pybiocfilecache/utils.py,sha256=z0WSk9vSk3ivMJ4dRICQbbDj8JtgpeGzNMImyKPdROc,2659
7
- pyBiocFileCache-0.6.2.dist-info/AUTHORS.md,sha256=ptvMLokf9Knfp0Ng-dHSgtEimkXWZhjZAR_o2aJm9bw,161
8
- pyBiocFileCache-0.6.2.dist-info/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
9
- pyBiocFileCache-0.6.2.dist-info/METADATA,sha256=BEoKhTG5v4h8d0CS5C2VynWnN41SW7dDWo94w-Ob-Vw,2947
10
- pyBiocFileCache-0.6.2.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
11
- pyBiocFileCache-0.6.2.dist-info/top_level.txt,sha256=_A2QFmYMnsz6WoSRPk1EFMDr5mkQVGx9Xtz2RMv3aF4,16
12
- pyBiocFileCache-0.6.2.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- pybiocfilecache