Coverage for src/romfarmer/cas/store.py: 37%

114 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1""" 

2Content-Addressable Store. 

3 

4Stores files by their SHA-256 hash with 2-character prefix sharding. 

5Layout: {store_dir}/{hash[:2]}/{hash[2:]}.{ext} 

6 

7On ZFS with 256 buckets, this handles millions of files efficiently. 

8Extensions are preserved so emulators/viewers can identify file types 

9without sniffing. 

10""" 

11 

12import hashlib 

13import os 

14import shutil 

15from pathlib import Path 

16 

17 

18class ContentStore: 

19 """ 

20 Content-addressable blob store with SHA-256 hashing and 1-level sharding. 

21 

22 Files are stored at: {store_dir}/{hash[:2]}/{hash[2:]}.{ext} 

23 

24 Thread-safe for concurrent reads. Writes use atomic temp+rename 

25 to prevent partial files. 

26 """ 

27 

28 HASH_ALGO = "sha256" 

29 HASH_LENGTH = 64 # hex chars for SHA-256 

30 PREFIX_LENGTH = 2 # 256 buckets 

31 CHUNK_SIZE = 1_048_576 # 1MB - good throughput on ZFS 

32 

33 def __init__(self, store_dir: str | Path = "store"): 

34 """ 

35 Initialize content store. 

36 

37 Args: 

38 store_dir: Root directory for the store. Can be relative 

39 (paths returned will also be relative) or absolute. 

40 """ 

41 self.store_dir = Path(store_dir) 

42 self.store_dir.mkdir(parents=True, exist_ok=True) 

43 

44 def put( 

45 self, 

46 source: Path, 

47 *, 

48 file_hash: str | None = None, 

49 move: bool = False, 

50 ) -> tuple[str, Path]: 

51 """ 

52 Store a file by its content hash. 

53 

54 If the blob already exists, the source is left untouched 

55 (or deleted if move=True) and the existing path is returned. 

56 

57 Args: 

58 source: Path to file to store. 

59 file_hash: Pre-computed SHA-256 hex digest. Computed if None. 

60 move: If True, rename source into store (atomic on same FS). 

61 If False, copy with atomic temp+rename. 

62 

63 Returns: 

64 (hash, blob_path) tuple. 

65 """ 

66 source = Path(source) 

67 if file_hash is None: 

68 file_hash = self.hash_file(source) 

69 

70 blob = self.blob_path(file_hash, source.suffix) 

71 

72 if blob.exists(): 

73 # Already stored — deduplicated 

74 if move: 

75 source.unlink() 

76 return file_hash, blob 

77 

78 blob.parent.mkdir(parents=True, exist_ok=True) 

79 

80 if move: 

81 # Atomic on same filesystem (ZFS pool) 

82 source.rename(blob) 

83 else: 

84 # Atomic: write to temp, then rename 

85 tmp = blob.with_suffix(blob.suffix + ".tmp") 

86 try: 

87 shutil.copy2(source, tmp) 

88 tmp.rename(blob) 

89 except BaseException: 

90 tmp.unlink(missing_ok=True) 

91 raise 

92 

93 return file_hash, blob 

94 

95 def blob_path(self, file_hash: str, ext: str = "") -> Path: 

96 """ 

97 Get the store path for a given hash and extension. 

98 

99 Args: 

100 file_hash: SHA-256 hex digest (64 chars). 

101 ext: File extension, with or without leading dot. 

102 

103 Returns: 

104 Path like store/ab/cdef0123...{ext} 

105 """ 

106 ext = self._normalize_ext(ext) 

107 return ( 

108 self.store_dir 

109 / file_hash[: self.PREFIX_LENGTH] 

110 / (file_hash[self.PREFIX_LENGTH :] + ext) 

111 ) 

112 

113 def relative_path(self, file_hash: str, ext: str = "") -> str: 

114 """ 

115 Get path as string, suitable for database storage. 

116 

117 Returns the same path as blob_path() but as a string. 

118 If the store was initialized with a relative path, this 

119 will be relative (e.g., "store/ab/cdef...png"). 

120 """ 

121 return str(self.blob_path(file_hash, ext)) 

122 

123 def exists(self, file_hash: str, ext: str = "") -> bool: 

124 """Check if a blob exists in the store.""" 

125 return self.blob_path(file_hash, ext).exists() 

126 

127 def verify(self, file_hash: str, ext: str = "") -> bool: 

128 """ 

129 Verify a blob's integrity by re-hashing. 

130 

131 Returns False if the file is missing or the hash doesn't match. 

132 """ 

133 blob = self.blob_path(file_hash, ext) 

134 if not blob.exists(): 

135 return False 

136 return self.hash_file(blob) == file_hash 

137 

138 def put_hardlink( 

139 self, 

140 source: Path, 

141 *, 

142 file_hash: str | None = None, 

143 ) -> tuple[str, Path]: 

144 """ 

145 Store a file by hardlinking from the source. 

146 

147 Zero-copy on the same filesystem (ZFS pool). The source file 

148 gains an additional hardlink in the CAS — both paths point to 

149 the same inode, so no extra disk space is used. 

150 

151 If the blob already exists (by hash), skips — the source is 

152 left untouched. 

153 

154 Args: 

155 source: Path to file to ingest via hardlink. 

156 file_hash: Pre-computed SHA-256 hex digest. Computed if None. 

157 

158 Returns: 

159 (hash, blob_path) tuple. 

160 

161 Raises: 

162 OSError: If hardlink fails (cross-filesystem). Use put() instead. 

163 """ 

164 source = Path(source) 

165 if file_hash is None: 

166 file_hash = self.hash_file(source) 

167 

168 blob = self.blob_path(file_hash, source.suffix) 

169 

170 if blob.exists(): 

171 return file_hash, blob 

172 

173 blob.parent.mkdir(parents=True, exist_ok=True) 

174 os.link(source, blob) 

175 

176 return file_hash, blob 

177 

178 def link_to(self, file_hash: str, ext: str, target: Path) -> None: 

179 """ 

180 Hard-link a blob to target path. 

181 

182 Creates parent directories as needed. Falls back to copy 

183 if hard-linking fails (cross-filesystem). 

184 

185 Args: 

186 file_hash: SHA-256 hex digest. 

187 ext: File extension. 

188 target: Destination path for the link. 

189 

190 Raises: 

191 FileNotFoundError: If the blob doesn't exist in the store. 

192 """ 

193 source = self.blob_path(file_hash, ext) 

194 if not source.exists(): 

195 raise FileNotFoundError(f"Blob not found: {file_hash[:12]}...{ext}") 

196 target = Path(target) 

197 target.parent.mkdir(parents=True, exist_ok=True) 

198 try: 

199 os.link(source, target) 

200 except OSError: 

201 shutil.copy2(source, target) 

202 

203 def hash_file(self, path: Path) -> str: 

204 """ 

205 Compute SHA-256 hex digest of a file. 

206 

207 Uses 1MB chunks for good throughput on large files. 

208 """ 

209 h = hashlib.sha256() 

210 with open(path, "rb") as f: 

211 while chunk := f.read(self.CHUNK_SIZE): 

212 h.update(chunk) 

213 return h.hexdigest() 

214 

215 def stats(self) -> dict: 

216 """ 

217 Gather store statistics. 

218 

219 Walks the store directory and counts files and bytes. 

220 Returns dict with: total_files, total_bytes, total_gb, 

221 buckets_used, buckets_total, avg_files_per_bucket. 

222 """ 

223 total_files = 0 

224 total_bytes = 0 

225 buckets_used = 0 

226 

227 for bucket in sorted(self.store_dir.iterdir()): 

228 if not bucket.is_dir() or len(bucket.name) != self.PREFIX_LENGTH: 

229 continue 

230 bucket_count = 0 

231 for blob in bucket.iterdir(): 

232 if blob.is_file() and not blob.name.endswith(".tmp"): 

233 total_files += 1 

234 total_bytes += blob.stat().st_size 

235 bucket_count += 1 

236 if bucket_count > 0: 

237 buckets_used += 1 

238 

239 return { 

240 "total_files": total_files, 

241 "total_bytes": total_bytes, 

242 "total_gb": round(total_bytes / (1024**3), 2), 

243 "buckets_used": buckets_used, 

244 "buckets_total": 256, 

245 "avg_files_per_bucket": round(total_files / max(buckets_used, 1), 1), 

246 } 

247 

248 def gc(self, referenced_hashes: set[str]) -> dict: 

249 """ 

250 Garbage-collect unreferenced blobs. 

251 

252 For tree manifests, callers should expand tree hashes to include 

253 all blob hashes referenced by each manifest (using 

254 TreeStore.referenced_hashes()) before calling this method. 

255 

256 Args: 

257 referenced_hashes: Set of SHA-256 hashes that are still 

258 referenced (from the database). Must include 

259 both single-file hashes and all blob hashes 

260 from tree manifests. 

261 

262 Returns: 

263 Dict with: removed_files, removed_bytes, kept_files. 

264 """ 

265 removed_files = 0 

266 removed_bytes = 0 

267 kept_files = 0 

268 

269 for bucket in sorted(self.store_dir.iterdir()): 

270 if not bucket.is_dir() or len(bucket.name) != self.PREFIX_LENGTH: 

271 continue 

272 for blob in bucket.iterdir(): 

273 if not blob.is_file() or blob.name.endswith(".tmp"): 

274 continue 

275 # Reconstruct hash: prefix dir + filename stem 

276 stem = blob.stem 

277 full_hash = bucket.name + stem 

278 if full_hash in referenced_hashes: 

279 kept_files += 1 

280 else: 

281 size = blob.stat().st_size 

282 blob.unlink() 

283 removed_files += 1 

284 removed_bytes += size 

285 

286 # Remove empty bucket dirs 

287 if not any(bucket.iterdir()): 

288 bucket.rmdir() 

289 

290 return { 

291 "removed_files": removed_files, 

292 "removed_bytes": removed_bytes, 

293 "removed_gb": round(removed_bytes / (1024**3), 2), 

294 "kept_files": kept_files, 

295 } 

296 

297 @staticmethod 

298 def _normalize_ext(ext: str) -> str: 

299 """Ensure extension starts with '.' or is empty.""" 

300 if ext and not ext.startswith("."): 

301 return "." + ext 

302 return ext 

303 

304 def __repr__(self) -> str: 

305 return f"ContentStore({self.store_dir!r})"