pyBiocFileCache 0.6.2__py3-none-any.whl → 0.8.0.dev0__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,12 @@
1
1
  import logging
2
+ import shutil
2
3
  from contextlib import contextmanager
3
- from datetime import datetime
4
+ from datetime import datetime, timezone
4
5
  from pathlib import Path
5
6
  from time import sleep, time
6
7
  from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union
7
8
 
9
+ from biocframe import BiocFrame
8
10
  from sqlalchemy import create_engine, func, text
9
11
  from sqlalchemy.orm import Session, sessionmaker
10
12
  from sqlalchemy.pool import QueuePool
@@ -14,6 +16,7 @@ from .const import SCHEMA_VERSION
14
16
  from .models import Base, Metadata, Resource
15
17
  from .utils import (
16
18
  calculate_file_hash,
19
+ convert_to_columnar,
17
20
  copy_or_move,
18
21
  create_tmp_dir,
19
22
  download_web_file,
@@ -28,6 +31,19 @@ __license__ = "MIT"
28
31
  logger = logging.getLogger(__name__)
29
32
 
30
33
 
34
+ def _now() -> datetime:
35
+ """Return current UTC time as a naive datetime matching SQLite CURRENT_TIMESTAMP."""
36
+ return datetime.now(timezone.utc).replace(tzinfo=None)
37
+
38
+
39
+ def _normalize_datetime(dt: Optional[datetime]) -> Optional[datetime]:
40
+ """Normalize an optional datetime to naive UTC."""
41
+ if dt is not None and dt.tzinfo is not None:
42
+ return dt.astimezone(timezone.utc).replace(tzinfo=None)
43
+
44
+ return dt
45
+
46
+
31
47
  class BiocFileCache:
32
48
  """Enhanced file caching module.
33
49
 
@@ -61,7 +77,7 @@ class BiocFileCache:
61
77
  if db_schema_version != SCHEMA_VERSION:
62
78
  raise RuntimeError(f"Database version is not {SCHEMA_VERSION}.")
63
79
 
64
- self._last_cleanup = datetime.now()
80
+ self._last_cleanup = _now()
65
81
 
66
82
  def _setup_cache_dir(self) -> bool:
67
83
  if not self.config.cache_dir.exists():
@@ -104,15 +120,26 @@ class BiocFileCache:
104
120
 
105
121
  return SCHEMA_VERSION
106
122
 
107
- def _get_detached_resource(
108
- self, session: Session, obj: Union[Resource, Metadata]
109
- ) -> Optional[Union[Resource, Metadata]]:
123
+ def _resolve_rpath(self, rpath: str, rtype: Optional[str]) -> Path:
124
+ """Resolve a stored resource path against cache_dir when relative."""
125
+ path = Path(rpath)
126
+ if rtype in ("relative", "web") and not path.is_absolute():
127
+ return self.config.cache_dir / path
128
+
129
+ return path
130
+
131
+ def _get_detached_resource(self, session: Session, obj: Union[Resource, Metadata]) -> Optional[dict]:
110
132
  """Get a detached copy of a resource."""
111
133
  if obj is None:
112
134
  return None
113
135
  session.refresh(obj)
114
136
  session.expunge(obj)
115
- return obj
137
+ obj_dict = obj.to_dict()
138
+
139
+ if isinstance(obj, Resource) and obj_dict["rtype"] in ("relative", "web"):
140
+ obj_dict["rpath"] = str(self._resolve_rpath(obj_dict["rpath"], obj_dict["rtype"]))
141
+
142
+ return obj_dict
116
143
 
117
144
  def __enter__(self) -> "BiocFileCache":
118
145
  return self
@@ -137,6 +164,10 @@ class BiocFileCache:
137
164
  finally:
138
165
  session.close()
139
166
 
167
+ #########################
168
+ ######>> cleanup <<######
169
+ #########################
170
+
140
171
  # def _validate_rname(self, rname: str) -> None:
141
172
  # """Validate resource name format."""
142
173
  # if not validate_rname(rname, self.config.rname_pattern):
@@ -151,7 +182,7 @@ class BiocFileCache:
151
182
  if self.config.cleanup_interval is None:
152
183
  return False
153
184
 
154
- return datetime.now() - self._last_cleanup > self.config.cleanup_interval
185
+ return _now() - self._last_cleanup > self.config.cleanup_interval
155
186
 
156
187
  def cleanup(self) -> int:
157
188
  """Remove expired resources from the cache.
@@ -160,27 +191,25 @@ class BiocFileCache:
160
191
  Number of resources removed.
161
192
 
162
193
  Note:
163
- - If `cleanup_interval` is None, this method will still run if called explicitly.
194
+ - Runs whenever called explicitly, even if `cleanup_interval` is None.
164
195
  - Only removes resources with non-None expiration dates.
165
196
  """
166
- if not any([self.config.cleanup_interval, self._should_cleanup()]):
167
- return 0 # Early return if automatic cleanup is disabled
168
-
169
197
  removed = 0
198
+ now = _now()
170
199
  with self.get_session() as session:
171
200
  # Only query resources that have expiration dates
172
201
  expired = (
173
202
  session.query(Resource)
174
203
  .filter(
175
204
  Resource.expires.isnot(None), # Only check resources with expiration
176
- Resource.expires < datetime.now(),
205
+ Resource.expires < now,
177
206
  )
178
207
  .all()
179
208
  )
180
209
 
181
210
  for resource in expired:
182
211
  try:
183
- Path(resource.rpath).unlink(missing_ok=True)
212
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
184
213
  session.delete(resource)
185
214
  removed += 1
186
215
  except Exception as e:
@@ -188,11 +217,21 @@ class BiocFileCache:
188
217
 
189
218
  session.commit()
190
219
 
191
- self._last_cleanup = datetime.now()
220
+ self._last_cleanup = now
192
221
  return removed
193
222
 
194
- def get(self, rname: str = None, rid: str = None) -> Optional[Resource]:
195
- """Get resource by name from cache.
223
+ ###############################
224
+ ######>> get resources <<######
225
+ ###############################
226
+
227
+ def get(
228
+ self,
229
+ rname: Optional[str] = None,
230
+ rid: Optional[str] = None,
231
+ wait: bool = True,
232
+ timeout: float = 30,
233
+ ) -> Optional[dict]:
234
+ """Get resource by name or id from cache.
196
235
 
197
236
  Args:
198
237
  rname:
@@ -201,34 +240,110 @@ class BiocFileCache:
201
240
  rid:
202
241
  Resource id to search by.
203
242
 
243
+ wait:
244
+ Whether to wait for the cached file to exist on disk.
245
+ If False, returns the registered record immediately even if
246
+ the file is missing. Defaults to True.
247
+
248
+ timeout:
249
+ Maximum seconds to wait when `wait=True`. Defaults to 30.
250
+
204
251
  """
205
252
  if rname is None and rid is None:
206
253
  raise ValueError("either 'rname' or 'rid' must be provided.")
207
254
 
208
255
  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:
256
+ if rid is not None:
212
257
  resource = session.query(Resource).filter(Resource.rid == rid).first()
258
+ else:
259
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
213
260
 
214
261
  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)
262
+ if wait:
263
+ resolved_path = self._resolve_rpath(resource.rpath, resource.rtype)
264
+ start = time()
265
+ while not resolved_path.exists():
266
+ if time() - start >= timeout:
267
+ identifier = rid if rid is not None else rname
268
+ raise TimeoutError(
269
+ f"For resource: '{identifier}' the rpath does not exist after {timeout} seconds."
270
+ )
271
+ sleep(0.1)
224
272
 
225
273
  # Update access time
226
- resource.access_time = datetime.now()
274
+ resource.access_time = _now()
227
275
  session.commit()
228
276
  return self._get_detached_resource(session, resource)
229
277
 
230
278
  return None
231
279
 
280
+ def _add_to_session(
281
+ self,
282
+ session: Session,
283
+ rname: str,
284
+ fpath: Union[str, Path],
285
+ rtype: Literal["local", "web", "relative"] = "relative",
286
+ action: Literal["copy", "move", "asis"] = "copy",
287
+ expires: Optional[datetime] = None,
288
+ download: bool = True,
289
+ ext: bool = True,
290
+ ) -> Tuple[Resource, Optional[Path]]:
291
+ """Insert a resource record and store its file within an active session."""
292
+ if session.query(Resource).filter(Resource.rname == rname).first() is not None:
293
+ raise FileExistsError(f"Resource '{rname}' already exists")
294
+
295
+ fpath_val = Path(fpath) if rtype != "web" else fpath
296
+ tmp_dir: Optional[Path] = None
297
+
298
+ if rtype == "web":
299
+ outpath = download_web_file(str(fpath_val), None, download)
300
+ tmp_dir = outpath.parent
301
+ action = "copy"
302
+ else:
303
+ outpath = Path(fpath_val)
304
+
305
+ if action == "asis":
306
+ if rtype != "local":
307
+ logger.warning("If action='asis', rtype must be 'local'.")
308
+ rtype = "local"
309
+ elif rtype == "local":
310
+ rtype = "relative"
311
+
312
+ uuid_str = generate_uuid()
313
+ rpath = f"{uuid_str}_{outpath.name if ext else outpath.stem}" if action != "asis" else str(fpath_val)
314
+
315
+ resource = Resource(
316
+ rid=None,
317
+ rname=rname,
318
+ rpath=str(rpath),
319
+ rtype=rtype,
320
+ fpath=str(fpath_val),
321
+ expires=_normalize_datetime(expires),
322
+ )
323
+
324
+ copied_target: Optional[Path] = None
325
+ try:
326
+ session.add(resource)
327
+ session.flush()
328
+ resource.rid = generate_id(resource.id)
329
+
330
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
331
+ copy_or_move(outpath, target_path, rname, action, False)
332
+ if action != "asis":
333
+ copied_target = target_path
334
+
335
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
336
+
337
+ return resource, copied_target
338
+ except Exception:
339
+ if copied_target is not None and copied_target.exists():
340
+ copied_target.unlink(missing_ok=True)
341
+
342
+ raise
343
+ finally:
344
+ if tmp_dir is not None:
345
+ shutil.rmtree(tmp_dir, ignore_errors=True)
346
+
232
347
  def add(
233
348
  self,
234
349
  rname: str,
@@ -238,7 +353,7 @@ class BiocFileCache:
238
353
  expires: Optional[datetime] = None,
239
354
  download: bool = True,
240
355
  ext: bool = True,
241
- ) -> Resource:
356
+ ) -> dict:
242
357
  """Add a resource to the cache.
243
358
 
244
359
  Args:
@@ -251,7 +366,7 @@ class BiocFileCache:
251
366
  rtype:
252
367
  Type of resource.
253
368
  One of ``local``, ``web``, or ``relative``.
254
- Defaults to ``local``.
369
+ Defaults to ``relative``.
255
370
 
256
371
  action:
257
372
  How to handle the file ("copy", "move", or "asis").
@@ -270,83 +385,68 @@ class BiocFileCache:
270
385
  Defaults to `True`.
271
386
 
272
387
  Returns:
273
- The `Resource` object added to the cache.
388
+ The `Resource` object added to the cache as dictionary.
274
389
  """
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
390
  with self.get_session() as session:
308
- session.add(resource)
309
- session.commit()
310
-
311
391
  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)
392
+ resource, _ = self._add_to_session(
393
+ session=session,
394
+ rname=rname,
395
+ fpath=fpath,
396
+ rtype=rtype,
397
+ action=action,
398
+ expires=expires,
399
+ download=download,
400
+ ext=ext,
401
+ )
316
402
  session.commit()
317
- result = self._get_detached_resource(session, resource)
318
- return result
319
-
403
+
404
+ return self._get_detached_resource(session, resource)
405
+ except FileExistsError:
406
+ session.rollback()
407
+ raise
320
408
  except Exception as e:
321
- session.delete(resource)
322
- session.commit()
409
+ session.rollback()
323
410
  raise Exception("Failed to add resource") from e
324
411
 
325
- def add_batch(self, resources: List[Dict[str, Any]]) -> List[Resource]:
412
+ def add_batch(self, resources: List[Dict[str, Any]]) -> BiocFrame:
326
413
  """Add multiple resources in a single transaction.
327
414
 
328
415
  Args:
329
416
  resources:
330
417
  List of resources to add.
331
418
  """
332
- results = []
419
+ added_resources: List[Resource] = []
420
+ copied_targets: List[Path] = []
333
421
  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
422
+ try:
423
+ for resource_info in resources:
424
+ resource, copied_target = self._add_to_session(session=session, **resource_info)
425
+ added_resources.append(resource)
426
+ if copied_target is not None:
427
+ copied_targets.append(copied_target)
428
+
429
+ session.commit()
430
+
431
+ return BiocFrame(
432
+ convert_to_columnar([self._get_detached_resource(session, r) for r in added_resources])
433
+ )
434
+ except Exception as e:
435
+ logger.error("Failed to add batch of resources", exc_info=e)
436
+ session.rollback()
437
+
438
+ for target in copied_targets:
439
+ target.unlink(missing_ok=True)
440
+
441
+ raise
343
442
 
344
443
  def update(
345
444
  self,
346
- rname: str,
347
- fpath: Union[str, Path],
445
+ rname: Optional[str] = None,
446
+ fpath: Union[str, Path] = None,
348
447
  action: Literal["copy", "move", "asis"] = "copy",
349
- ) -> Resource:
448
+ rid: Optional[str] = None,
449
+ ) -> dict:
350
450
  """Update an existing resource.
351
451
 
352
452
  Args:
@@ -360,36 +460,62 @@ class BiocFileCache:
360
460
  Either ``copy``, ``move`` or ``asis``.
361
461
  Defaults to ``copy``.
362
462
 
463
+ rid:
464
+ Optional resource id to identify the resource.
465
+
363
466
  Returns:
364
- Updated `Resource` object.
467
+ Updated `Resource` object as dictionary.
365
468
 
366
469
  """
470
+ if rname is None and rid is None:
471
+ raise ValueError("either 'rname' or 'rid' must be provided.")
472
+
473
+ if fpath is None:
474
+ raise ValueError("'fpath' must be provided.")
475
+
367
476
  fpath = Path(fpath)
368
477
  if not fpath.exists():
369
478
  raise FileNotFoundError(f"File '{fpath}' does not exist")
370
479
 
371
480
  with self.get_session() as session:
372
- resource = session.query(Resource).filter(Resource.rname == rname).first()
481
+ if rid is not None:
482
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
483
+ else:
484
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
373
485
 
374
486
  if resource is None:
487
+ if rname is None:
488
+ raise KeyError(f"Resource with rid '{rid}' not found")
375
489
  return self.add(rname=rname, fpath=fpath, action=action)
376
490
 
377
- old_path = Path(resource.rpath)
378
491
  try:
379
- copy_or_move(fpath, old_path, rname, action, False)
492
+ if action == "asis":
493
+ resource.rpath = str(fpath)
494
+ resource.rtype = "local"
495
+ target_path = fpath
496
+ else:
497
+ if resource.rtype == "local":
498
+ resource.rtype = "relative"
499
+ resource.rpath = f"{generate_uuid()}_{fpath.name}"
500
+
501
+ target_path = self._resolve_rpath(resource.rpath, resource.rtype)
502
+ copy_or_move(fpath, target_path, resource.rname, action, False)
380
503
 
381
- resource.last_modified_time = datetime.now()
382
- resource.etag = calculate_file_hash(old_path, self.config.hash_algorithm)
504
+ resource.fpath = str(fpath)
505
+ resource.last_modified_time = _now()
506
+ resource.etag = calculate_file_hash(target_path, self.config.hash_algorithm)
383
507
 
384
508
  session.commit()
509
+
385
510
  return self._get_detached_resource(session, resource)
386
511
 
387
512
  except Exception as e:
388
513
  session.rollback()
514
+
389
515
  raise Exception("Failed to update resource") from e
390
516
 
391
- def remove(self, rname: str) -> None:
392
- """Remove a resource from cache by name.
517
+ def remove(self, rname: Optional[str] = None, rid: Optional[str] = None) -> None:
518
+ """Remove a resource from cache by name or id.
393
519
 
394
520
  Removes both the cached file and its database entry.
395
521
 
@@ -397,16 +523,25 @@ class BiocFileCache:
397
523
  rname:
398
524
  Name to identify the resource in cache.
399
525
 
526
+ rid:
527
+ Resource id to identify the resource in cache.
528
+
400
529
  Raises:
401
530
  Exception: If resource removal fails
402
531
  """
532
+ if rname is None and rid is None:
533
+ raise ValueError("either 'rname' or 'rid' must be provided.")
534
+
403
535
  with self.get_session() as session:
404
- resource = session.query(Resource).filter(Resource.rname == rname).first()
536
+ if rid is not None:
537
+ resource = session.query(Resource).filter(Resource.rid == rid).first()
538
+ else:
539
+ resource = session.query(Resource).filter(Resource.rname == rname).first()
405
540
 
406
541
  if resource is not None:
407
542
  try:
408
543
  # Try to remove the file first
409
- rpath = Path(resource.rpath)
544
+ rpath = self._resolve_rpath(resource.rpath, resource.rtype)
410
545
  if rpath.exists():
411
546
  rpath.unlink()
412
547
 
@@ -416,9 +551,10 @@ class BiocFileCache:
416
551
 
417
552
  except Exception as e:
418
553
  session.rollback()
419
- raise Exception(f"Failed to remove resource '{rname}'") from e
554
+ identifier = rid if rid is not None else rname
555
+ raise Exception(f"Failed to remove resource '{identifier}'") from e
420
556
 
421
- def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> List[Resource]:
557
+ def list_resources(self, rtype: Optional[str] = None, expired: Optional[bool] = None) -> BiocFrame:
422
558
  """List resources in the cache with optional filtering.
423
559
 
424
560
  Args:
@@ -434,7 +570,7 @@ class BiocFileCache:
434
570
  Note: Resources with no expiration are always considered non-expired.
435
571
 
436
572
  Returns:
437
- List of Resource objects matching the filters
573
+ List of Resource objects matching the filters.
438
574
  """
439
575
  with self.get_session() as session:
440
576
  query = session.query(Resource)
@@ -442,38 +578,52 @@ class BiocFileCache:
442
578
  if rtype:
443
579
  query = query.filter(Resource.rtype == rtype)
444
580
  if expired is not None:
581
+ now = _now()
445
582
  if expired:
446
583
  query = query.filter(
447
584
  Resource.expires.isnot(None), # Only check resources with expiration
448
- Resource.expires < datetime.now(),
585
+ Resource.expires < now,
449
586
  )
450
587
  else:
451
588
  query = query.filter(
452
589
  (Resource.expires.is_(None)) # Never expires
453
- | (Resource.expires > datetime.now()) # Not yet expired
590
+ | (Resource.expires > now) # Not yet expired
454
591
  )
455
592
 
456
593
  resources = query.all()
457
- return [self._get_detached_resource(session, r) for r in resources]
594
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
458
595
 
459
- def validate_resource(self, resource: Resource) -> bool:
596
+ def validate_resource(self, resource: Union[Resource, dict]) -> bool:
460
597
  """Validate resource integrity.
461
598
 
462
599
  Args:
463
600
  resource:
464
- Resource to validate.
601
+ Resource ORM object or dictionary to validate.
465
602
 
466
603
  Returns:
467
604
  True if resource is valid, False otherwise.
468
605
  """
469
- if not resource.etag:
606
+ if isinstance(resource, dict):
607
+ etag = resource.get("etag")
608
+ rpath = resource.get("rpath")
609
+ rtype = resource.get("rtype")
610
+ rname = resource.get("rname")
611
+ else:
612
+ etag = resource.etag
613
+ rpath = resource.rpath
614
+ rtype = resource.rtype
615
+ rname = resource.rname
616
+
617
+ if not etag:
470
618
  return True # No validation if no checksum
471
619
 
472
620
  try:
473
- current_hash = calculate_file_hash(Path(resource.rpath), self.config.hash_algorithm)
474
- return current_hash == resource.etag
621
+ resolved_path = self._resolve_rpath(rpath, rtype)
622
+ current_hash = calculate_file_hash(resolved_path, self.config.hash_algorithm)
623
+
624
+ return current_hash == etag
475
625
  except Exception as e:
476
- logger.error(f"Failed to validate resource: {resource.rname}", exc_info=e)
626
+ logger.error(f"Failed to validate resource: {rname}", exc_info=e)
477
627
  return False
478
628
 
479
629
  # def export_metadata(self, path: Path) -> None:
@@ -516,14 +666,16 @@ class BiocFileCache:
516
666
  Tuple of (valid_count, invalid_count).
517
667
  """
518
668
  valid = invalid = 0
519
- for resource in self.list_resources():
520
- if self.validate_resource(resource):
521
- valid += 1
522
- else:
523
- invalid += 1
669
+ with self.get_session() as session:
670
+ for resource in session.query(Resource).all():
671
+ if self.validate_resource(resource):
672
+ valid += 1
673
+ else:
674
+ invalid += 1
675
+
524
676
  return valid, invalid
525
677
 
526
- def search(self, query: str, field: str = "rname", exact: bool = False) -> List[Resource]:
678
+ def search(self, query: str, field: str = "rname", exact: bool = False) -> BiocFrame:
527
679
  """Search for resources by field value.
528
680
 
529
681
  Args:
@@ -537,15 +689,19 @@ class BiocFileCache:
537
689
  Whether to require exact match.
538
690
 
539
691
  Returns:
540
- List of matching resources.
692
+ BiocFrame of matching resources.
541
693
  """
694
+ if field not in Resource.__table__.columns:
695
+ raise ValueError(f"Invalid search field: '{field}'")
696
+
697
+ column = getattr(Resource, field)
542
698
  with self.get_session() as session:
543
699
  if exact:
544
- resources = session.query(Resource).filter(Resource[field] == query).all()
700
+ resources = session.query(Resource).filter(column == query).all()
545
701
  else:
546
- resources = session.query(Resource).filter(Resource[field].ilike(f"%{query}%")).all()
702
+ resources = session.query(Resource).filter(column.ilike(f"%{query}%")).all()
547
703
 
548
- return [self._get_detached_resource(session, r) for r in resources]
704
+ return BiocFrame(convert_to_columnar([self._get_detached_resource(session, r) for r in resources]))
549
705
 
550
706
  def get_stats(self) -> Dict[str, Any]:
551
707
  """Get statistics about the cache."""
@@ -555,7 +711,7 @@ class BiocFileCache:
555
711
  session.query(Resource)
556
712
  .filter(
557
713
  Resource.expires.isnot(None), # Only check resources with expiration
558
- Resource.expires < datetime.now(),
714
+ Resource.expires < _now(),
559
715
  )
560
716
  .count()
561
717
  )
@@ -590,7 +746,7 @@ class BiocFileCache:
590
746
 
591
747
  for resource in resources:
592
748
  try:
593
- Path(resource.rpath).unlink(missing_ok=True)
749
+ self._resolve_rpath(resource.rpath, resource.rtype).unlink(missing_ok=True)
594
750
  except Exception as e:
595
751
  if not force:
596
752
  session.rollback()
@@ -610,7 +766,7 @@ class BiocFileCache:
610
766
  except Exception as e:
611
767
  logger.warning(f"Failed to remove {file}: {e}")
612
768
 
613
- self._last_cleanup = datetime.now()
769
+ self._last_cleanup = _now()
614
770
  return True
615
771
 
616
772
  except Exception as e:
@@ -671,7 +827,7 @@ class BiocFileCache:
671
827
  except Exception as e:
672
828
  session.delete(meta)
673
829
  session.commit()
674
- raise Exception("Failed to add metadata") from e
830
+ raise Exception("Failed to add metadata", str(e)) from e
675
831
  else:
676
832
  raise Exception(f"'key'={key} already exists in metadata.")
677
833
 
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
@@ -7,7 +7,8 @@ import uuid
7
7
  import zlib
8
8
  from pathlib import Path
9
9
  from shutil import copy2, move
10
- from typing import Literal
10
+ from typing import List, Literal, Optional
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: Optional[str] = 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,21 @@
1
+ Metadata-Version: 2.5
2
+ Name: pybiocfilecache
3
+ Version: 0.8.0.dev0
4
+ Summary: File based cache for resources and metadata
5
+ Author-email: Jayaram Kancherla <jayaram.kancherla@gmail.com>
6
+ License-File: AUTHORS.md
7
+ License-File: LICENSE.txt
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: biocframe>=0.7.3
10
+ Requires-Dist: importlib-metadata>=9.0.0; python_full_version < '3.8'
11
+ Requires-Dist: sqlalchemy>=2.0.52
12
+ Provides-Extra: testing
13
+ Requires-Dist: pytest-cov>=7.1.0; extra == 'testing'
14
+ Requires-Dist: pytest>=9.1.1; extra == 'testing'
15
+ Requires-Dist: setuptools>=84.0.0; extra == 'testing'
16
+ Description-Content-Type: text/markdown
17
+
18
+ ```{include} ../README.md
19
+ :relative-docs: docs/
20
+ :relative-images:
21
+ ```
@@ -0,0 +1,12 @@
1
+ pybiocfilecache/__init__.py,sha256=kClwDkzgGPYAyDW-fuo5LI4lKCruYJhDHvw0lq9u4b0,652
2
+ pybiocfilecache/cache.py,sha256=EJ8seT-OeW2uaTr58HK_qyXtfSR6P6sf4zfPrPn6WmY,29136
3
+ pybiocfilecache/config.py,sha256=bado4Hg6QFIfV46zKwx6Q9AoV__G-e8fghylnk5I-nk,803
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=fzr00U8D3yGp09gYJfhvHoQrt5P5KbVpLNsNkJfB4hY,3282
8
+ pybiocfilecache-0.8.0.dev0.dist-info/METADATA,sha256=HrmOTJC2Ueqi4QPfSqnEZVJ260PWQ8nzL7vNqq7sOD4,681
9
+ pybiocfilecache-0.8.0.dev0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ pybiocfilecache-0.8.0.dev0.dist-info/licenses/AUTHORS.md,sha256=6nnc80t6djIXiPNai5Mumh8ROiq0E19XOlhCGgKc8Uw,71
11
+ pybiocfilecache-0.8.0.dev0.dist-info/licenses/LICENSE.txt,sha256=bV5MJ4ezdCnC4yREyxU30iel5hFq8T8kGqobu4Kc-WM,1082
12
+ pybiocfilecache-0.8.0.dev0.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
-
@@ -0,0 +1,4 @@
1
+ ```{include} ../AUTHORS.md
2
+ :relative-docs: docs/
3
+ :relative-images:
4
+ ```
@@ -1,5 +0,0 @@
1
- # Contributors
2
-
3
- * Jayaram Kancherla <jayaram.kancherla@gmail.com>
4
- * Max Hargreaves <max_hargreaves@outlook.com>
5
- * Oleksandr Khoroshevskyi <khorosh@virginia.edu>
@@ -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