diskcache-rs 0.1.0__cp312-cp312-win_amd64.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.
@@ -0,0 +1,36 @@
1
+ """
2
+ DiskCache RS - A high-performance disk cache implementation in Rust with Python bindings
3
+
4
+ This module provides a Python interface compatible with python-diskcache,
5
+ but implemented in Rust for better performance and network filesystem support.
6
+ """
7
+
8
+ # Always use the Python wrapper for now
9
+ # The Python wrapper will handle importing the Rust implementation
10
+ from .cache import Cache, FanoutCache
11
+ from .fast_cache import FastCache, FastFanoutCache
12
+ from .pickle_cache import PickleCache, cache_object, clear_cache, get_cached_object
13
+
14
+ # Import Rust pickle functions
15
+ try:
16
+ from ._diskcache_rs import rust_pickle_dumps, rust_pickle_loads
17
+ except ImportError:
18
+ rust_pickle_dumps = None
19
+ rust_pickle_loads = None
20
+
21
+ __version__ = "0.1.0"
22
+ __all__ = [
23
+ "Cache",
24
+ "FanoutCache",
25
+ "PickleCache",
26
+ "cache_object",
27
+ "get_cached_object",
28
+ "clear_cache",
29
+ "FastCache",
30
+ "FastFanoutCache",
31
+ "rust_pickle_dumps",
32
+ "rust_pickle_loads",
33
+ ]
34
+
35
+ # For backward compatibility
36
+ DiskCache = Cache
diskcache_rs/cache.py ADDED
@@ -0,0 +1,550 @@
1
+ """
2
+ Python-compatible cache interface for diskcache_rs
3
+ """
4
+
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Iterator, List, Optional, Union
9
+
10
+ # Use high-performance Rust pickle implementation when available
11
+ try:
12
+ from . import rust_pickle as pickle
13
+ except ImportError:
14
+ import pickle
15
+
16
+ # We'll import the Rust implementation at runtime to avoid circular imports
17
+ _RustCache = None
18
+
19
+
20
+ def _get_rust_cache():
21
+ """Get the Rust cache class, importing it if necessary"""
22
+ global _RustCache
23
+ if _RustCache is None:
24
+ from .core import get_rust_cache
25
+
26
+ _RustCache = get_rust_cache()
27
+ return _RustCache
28
+
29
+
30
+ class Cache:
31
+ """
32
+ High-performance disk cache compatible with python-diskcache API
33
+
34
+ This implementation uses Rust for better performance and network filesystem support.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ directory: Union[str, Path] = None,
40
+ timeout: float = 60.0,
41
+ disk_min_file_size: int = 32 * 1024,
42
+ **kwargs,
43
+ ):
44
+ """
45
+ Initialize cache
46
+
47
+ Args:
48
+ directory: Cache directory path
49
+ timeout: Operation timeout (not used in Rust implementation)
50
+ disk_min_file_size: Minimum file size for disk storage (not used)
51
+ **kwargs: Additional arguments (max_size, max_entries, etc.)
52
+ """
53
+ if directory is None:
54
+ directory = os.path.join(os.getcwd(), "cache")
55
+
56
+ self.directory = Path(directory)
57
+ self.timeout = timeout
58
+
59
+ # Extract Rust cache parameters
60
+ max_size = kwargs.get(
61
+ "size_limit", kwargs.get("max_size", 1024 * 1024 * 1024)
62
+ ) # 1GB default
63
+ max_entries = kwargs.get("count_limit", kwargs.get("max_entries", 100_000))
64
+
65
+ # Create the underlying Rust cache
66
+ _RustCache = _get_rust_cache()
67
+ self._cache = _RustCache(
68
+ str(self.directory), max_size=max_size, max_entries=max_entries
69
+ )
70
+
71
+ def set(
72
+ self,
73
+ key: str,
74
+ value: Any,
75
+ expire: Optional[float] = None,
76
+ read: bool = False,
77
+ tag: Optional[str] = None,
78
+ retry: bool = False,
79
+ ) -> bool:
80
+ """
81
+ Set key to value in cache
82
+
83
+ Args:
84
+ key: Cache key
85
+ value: Value to store
86
+ expire: Expiration time (seconds from now, or timestamp)
87
+ read: Whether this is a read operation (ignored)
88
+ tag: Tag for the entry
89
+ retry: Whether to retry on failure (ignored)
90
+
91
+ Returns:
92
+ True if successful
93
+ """
94
+ try:
95
+ # Serialize the value
96
+ serialized_value = pickle.dumps(value)
97
+
98
+ # Calculate expiration time
99
+ expire_time = None
100
+ if expire is not None:
101
+ if expire > time.time():
102
+ # Assume it's already a timestamp
103
+ expire_time = int(expire)
104
+ else:
105
+ # Assume it's seconds from now
106
+ expire_time = int(time.time() + expire)
107
+
108
+ # Prepare tags
109
+ tags = [tag] if tag else []
110
+
111
+ # Store in Rust cache
112
+ self._cache.set(key, serialized_value, expire_time=expire_time, tags=tags)
113
+ return True
114
+
115
+ except Exception:
116
+ return False
117
+
118
+ def get(
119
+ self,
120
+ key: str,
121
+ default: Any = None,
122
+ read: bool = False,
123
+ expire_time: bool = False,
124
+ tag: bool = False,
125
+ retry: bool = False,
126
+ ) -> Any:
127
+ """
128
+ Get value for key from cache
129
+
130
+ Args:
131
+ key: Cache key
132
+ default: Default value if key not found
133
+ read: Whether this is a read operation (ignored)
134
+ expire_time: Whether to return expire time (not supported)
135
+ tag: Whether to return tag (not supported)
136
+ retry: Whether to retry on failure (ignored)
137
+
138
+ Returns:
139
+ Cached value or default
140
+ """
141
+ try:
142
+ serialized_value = self._cache.get(key)
143
+ if serialized_value is None:
144
+ return default
145
+
146
+ # Deserialize the value
147
+ value = pickle.loads(serialized_value)
148
+
149
+ # Handle additional return values
150
+ if expire_time or tag:
151
+ result = [value]
152
+ if expire_time:
153
+ result.append(None) # Expire time not supported yet
154
+ if tag:
155
+ result.append(None) # Tag not supported yet
156
+ return tuple(result)
157
+
158
+ return value
159
+
160
+ except Exception:
161
+ return default
162
+
163
+ def delete(self, key: str) -> bool:
164
+ """
165
+ Delete key from cache
166
+
167
+ Args:
168
+ key: Cache key to delete
169
+
170
+ Returns:
171
+ True if key existed and was deleted
172
+ """
173
+ try:
174
+ return self._cache.delete(key)
175
+ except Exception:
176
+ return False
177
+
178
+ def exists(self, key: str) -> bool:
179
+ """Check if key exists in cache"""
180
+ try:
181
+ return self._cache.exists(key)
182
+ except Exception:
183
+ return False
184
+
185
+ def __contains__(self, key: str) -> bool:
186
+ """Check if key exists in cache"""
187
+ try:
188
+ return self._cache.exists(key)
189
+ except Exception:
190
+ return False
191
+
192
+ def __getitem__(self, key: str) -> Any:
193
+ """Get item using [] syntax"""
194
+ result = self.get(key)
195
+ try:
196
+ exists = self._cache.exists(key)
197
+ except Exception:
198
+ exists = False
199
+ if result is None and not exists:
200
+ raise KeyError(key)
201
+ return result
202
+
203
+ def __setitem__(self, key: str, value: Any) -> None:
204
+ """Set item using [] syntax"""
205
+ self.set(key, value)
206
+
207
+ def __delitem__(self, key: str) -> None:
208
+ """Delete item using del syntax"""
209
+ if not self.delete(key):
210
+ raise KeyError(key)
211
+
212
+ def keys(self) -> List[str]:
213
+ """Get list of all cache keys"""
214
+ try:
215
+ return self._cache.keys()
216
+ except Exception:
217
+ return []
218
+
219
+ def __iter__(self) -> Iterator[str]:
220
+ """Iterate over cache keys"""
221
+ try:
222
+ return iter(self._cache.keys())
223
+ except Exception:
224
+ return iter([])
225
+
226
+ def __len__(self) -> int:
227
+ """Get number of items in cache"""
228
+ try:
229
+ return len(self._cache.keys())
230
+ except Exception:
231
+ return 0
232
+
233
+ def clear(self) -> int:
234
+ """
235
+ Clear all items from cache
236
+
237
+ Returns:
238
+ Number of items removed
239
+ """
240
+ try:
241
+ count = len(self)
242
+ self._cache.clear()
243
+ return count
244
+ except Exception:
245
+ return 0
246
+
247
+ def pop(
248
+ self,
249
+ key: str,
250
+ default=None,
251
+ expire_time: bool = False,
252
+ tag: bool = False,
253
+ retry: bool = False,
254
+ ):
255
+ """
256
+ Remove and return value for key
257
+
258
+ Args:
259
+ key: Cache key
260
+ default: Default value if key not found
261
+ expire_time: Whether to return expire time (not supported)
262
+ tag: Whether to return tag (not supported)
263
+ retry: Whether to retry on failure (ignored)
264
+
265
+ Returns:
266
+ Value, or tuple with additional metadata if requested
267
+ """
268
+ try:
269
+ value = self.get(key)
270
+ if value is None:
271
+ if expire_time or tag:
272
+ return (default, None, None)
273
+ return default
274
+
275
+ # Remove the key
276
+ del self[key]
277
+
278
+ if expire_time or tag:
279
+ # Return tuple format: (value, expire_time, tag)
280
+ return (value, None, None)
281
+ return value
282
+ except Exception:
283
+ if expire_time or tag:
284
+ return (default, None, None)
285
+ return default
286
+
287
+ def stats(self, enable: bool = True, reset: bool = False) -> Dict[str, Any]:
288
+ """
289
+ Get cache statistics
290
+
291
+ Args:
292
+ enable: Whether to enable stats (ignored)
293
+ reset: Whether to reset stats (not supported)
294
+
295
+ Returns:
296
+ Dictionary of statistics
297
+ """
298
+ try:
299
+ rust_stats = self._cache.stats()
300
+
301
+ # Convert to python-diskcache compatible format
302
+ return {
303
+ "hits": rust_stats.get("hits", 0),
304
+ "misses": rust_stats.get("misses", 0),
305
+ "sets": rust_stats.get("sets", 0),
306
+ "deletes": rust_stats.get("deletes", 0),
307
+ "evictions": rust_stats.get("evictions", 0),
308
+ "size": rust_stats.get("total_size", 0),
309
+ "count": rust_stats.get("entry_count", 0),
310
+ }
311
+ except Exception:
312
+ return {}
313
+
314
+ def volume(self) -> int:
315
+ """Get cache size in bytes"""
316
+ try:
317
+ return self._cache.size()
318
+ except Exception:
319
+ return 0
320
+
321
+ def add(
322
+ self,
323
+ key: str,
324
+ value: Any,
325
+ expire: Optional[float] = None,
326
+ read: bool = False,
327
+ tag: Optional[str] = None,
328
+ retry: bool = False,
329
+ ) -> bool:
330
+ """
331
+ Add key to cache only if it doesn't already exist
332
+
333
+ Args:
334
+ key: Cache key
335
+ value: Value to store
336
+ expire: Expiration time (seconds from now, or timestamp)
337
+ read: Whether this is a read operation (ignored)
338
+ tag: Tag for the entry
339
+ retry: Whether to retry on failure (ignored)
340
+
341
+ Returns:
342
+ True if key was added, False if key already exists
343
+ """
344
+ if key in self:
345
+ return False
346
+ return self.set(key, value, expire, read, tag, retry)
347
+
348
+ def incr(
349
+ self, key: str, delta: int = 1, default: int = 0, retry: bool = False
350
+ ) -> int:
351
+ """
352
+ Increment value for key by delta
353
+
354
+ Args:
355
+ key: Cache key
356
+ delta: Amount to increment by
357
+ default: Default value if key doesn't exist
358
+ retry: Whether to retry on failure (ignored)
359
+
360
+ Returns:
361
+ New value after increment
362
+ """
363
+ try:
364
+ current = self.get(key)
365
+ if current is None:
366
+ new_value = default + delta
367
+ else:
368
+ new_value = int(current) + delta
369
+ self.set(key, new_value)
370
+ return new_value
371
+ except Exception:
372
+ # If key doesn't exist and no default provided, raise KeyError
373
+ if default is None:
374
+ raise KeyError(key)
375
+ new_value = default + delta
376
+ self.set(key, new_value)
377
+ return new_value
378
+
379
+ def decr(
380
+ self, key: str, delta: int = 1, default: int = 0, retry: bool = False
381
+ ) -> int:
382
+ """
383
+ Decrement value for key by delta
384
+
385
+ Args:
386
+ key: Cache key
387
+ delta: Amount to decrement by
388
+ default: Default value if key doesn't exist
389
+ retry: Whether to retry on failure (ignored)
390
+
391
+ Returns:
392
+ New value after decrement
393
+ """
394
+ return self.incr(key, -delta, default, retry)
395
+
396
+ def touch(
397
+ self, key: str, expire: Optional[float] = None, retry: bool = False
398
+ ) -> bool:
399
+ """
400
+ Update expiration time for key
401
+
402
+ Args:
403
+ key: Cache key
404
+ expire: New expiration time
405
+ retry: Whether to retry on failure (ignored)
406
+
407
+ Returns:
408
+ True if key was touched, False if key doesn't exist
409
+ """
410
+ if key not in self:
411
+ return False
412
+
413
+ # Get current value and update with new expiration
414
+ value = self.get(key)
415
+ if value is not None:
416
+ return self.set(key, value, expire)
417
+ return False
418
+
419
+ def close(self) -> None:
420
+ """Close cache (no-op for Rust implementation)"""
421
+ pass
422
+
423
+ def __enter__(self):
424
+ """Context manager entry"""
425
+ return self
426
+
427
+ def __exit__(self, exc_type, exc_val, exc_tb):
428
+ """Context manager exit"""
429
+ self.close()
430
+
431
+
432
+ class FanoutCache:
433
+ """
434
+ Fanout cache implementation using multiple Cache instances
435
+
436
+ This provides sharding across multiple cache directories for better performance.
437
+ """
438
+
439
+ def __init__(
440
+ self,
441
+ directory: Union[str, Path] = None,
442
+ shards: int = 8,
443
+ timeout: float = 60.0,
444
+ **kwargs,
445
+ ):
446
+ """
447
+ Initialize fanout cache
448
+
449
+ Args:
450
+ directory: Base cache directory
451
+ shards: Number of cache shards
452
+ timeout: Operation timeout
453
+ **kwargs: Additional arguments passed to Cache
454
+ """
455
+ if directory is None:
456
+ directory = os.path.join(os.getcwd(), "cache")
457
+
458
+ self.directory = Path(directory)
459
+ self.shards = shards
460
+ self.timeout = timeout
461
+
462
+ # Create shard caches
463
+ self._caches = []
464
+ for i in range(shards):
465
+ shard_dir = self.directory / f"shard_{i:03d}"
466
+ cache = Cache(shard_dir, timeout=timeout, **kwargs)
467
+ self._caches.append(cache)
468
+
469
+ def _get_shard(self, key: str) -> Cache:
470
+ """Get the cache shard for a given key"""
471
+ # Simple hash-based sharding
472
+ shard_index = hash(key) % self.shards
473
+ return self._caches[shard_index]
474
+
475
+ def set(self, key: str, value: Any, **kwargs) -> bool:
476
+ """Set key to value in appropriate shard"""
477
+ return self._get_shard(key).set(key, value, **kwargs)
478
+
479
+ def get(self, key: str, default: Any = None, **kwargs) -> Any:
480
+ """Get value for key from appropriate shard"""
481
+ return self._get_shard(key).get(key, default, **kwargs)
482
+
483
+ def delete(self, key: str) -> bool:
484
+ """Delete key from appropriate shard"""
485
+ return self._get_shard(key).delete(key)
486
+
487
+ def __contains__(self, key: str) -> bool:
488
+ """Check if key exists in appropriate shard"""
489
+ return key in self._get_shard(key)
490
+
491
+ def __getitem__(self, key: str) -> Any:
492
+ """Get item using [] syntax"""
493
+ return self._get_shard(key)[key]
494
+
495
+ def __setitem__(self, key: str, value: Any) -> None:
496
+ """Set item using [] syntax"""
497
+ self._get_shard(key)[key] = value
498
+
499
+ def __delitem__(self, key: str) -> None:
500
+ """Delete item using del syntax"""
501
+ del self._get_shard(key)[key]
502
+
503
+ def __iter__(self) -> Iterator[str]:
504
+ """Iterate over all cache keys"""
505
+ for cache in self._caches:
506
+ yield from cache
507
+
508
+ def __len__(self) -> int:
509
+ """Get total number of items across all shards"""
510
+ return sum(len(cache) for cache in self._caches)
511
+
512
+ def clear(self) -> int:
513
+ """Clear all items from all shards"""
514
+ return sum(cache.clear() for cache in self._caches)
515
+
516
+ def stats(self, **kwargs) -> Dict[str, Any]:
517
+ """Get combined statistics from all shards"""
518
+ combined_stats = {
519
+ "hits": 0,
520
+ "misses": 0,
521
+ "sets": 0,
522
+ "deletes": 0,
523
+ "evictions": 0,
524
+ "size": 0,
525
+ "count": 0,
526
+ }
527
+
528
+ for cache in self._caches:
529
+ shard_stats = cache.stats(**kwargs)
530
+ for key in combined_stats:
531
+ combined_stats[key] += shard_stats.get(key, 0)
532
+
533
+ return combined_stats
534
+
535
+ def volume(self) -> int:
536
+ """Get total cache size across all shards"""
537
+ return sum(cache.volume() for cache in self._caches)
538
+
539
+ def close(self) -> None:
540
+ """Close all shard caches"""
541
+ for cache in self._caches:
542
+ cache.close()
543
+
544
+ def __enter__(self):
545
+ """Context manager entry"""
546
+ return self
547
+
548
+ def __exit__(self, exc_type, exc_val, exc_tb):
549
+ """Context manager exit"""
550
+ self.close()
diskcache_rs/core.py ADDED
@@ -0,0 +1,41 @@
1
+ """
2
+ Core module that provides access to the Rust implementation
3
+ """
4
+
5
+
6
+ def get_rust_cache():
7
+ """Get the Rust PyCache class"""
8
+ try:
9
+ # Import the compiled Rust module directly (avoid circular import)
10
+ from diskcache_rs import _diskcache_rs
11
+
12
+ # Ensure we get the PyCache class that returns dict from stats()
13
+ if hasattr(_diskcache_rs, "PyCache"):
14
+ return _diskcache_rs.PyCache
15
+ else:
16
+ raise ImportError("PyCache class not found in _diskcache_rs module")
17
+
18
+ except ImportError as e:
19
+ raise ImportError(
20
+ f"Could not import the compiled diskcache_rs module: {e}"
21
+ ) from e
22
+ except AttributeError as e:
23
+ raise ImportError(
24
+ f"PyCache class not available in _diskcache_rs module: {e}"
25
+ ) from e
26
+
27
+
28
+ def get_rust_fanout_cache():
29
+ """Get the Rust FanoutCache class"""
30
+ try:
31
+ # Import the compiled Rust module directly (avoid circular import)
32
+ from diskcache_rs import _diskcache_rs
33
+
34
+ return _diskcache_rs.FanoutCache
35
+ except ImportError as e:
36
+ raise ImportError(
37
+ f"Could not import the compiled diskcache_rs module: {e}"
38
+ ) from e
39
+
40
+
41
+ __all__ = ["get_rust_cache", "get_rust_fanout_cache"]