Coverage for src/album_sync_orchestrator.py: 100%

96 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 03:08 +0000

1"""Album synchronization orchestration module. 

2 

3This module contains the main album sync orchestration logic 

4that coordinates photo filtering, download collection, and parallel execution. 

5""" 

6 

7___author___ = "Mandar Patil <mandarons@pm.me>" 

8 

9import os 

10import time 

11from typing import Any 

12 

13from src import BUFFERED_DOWNLOAD_MAX_AGE_SEC, DEFAULT_ENUMERATION_CHUNK_SIZE, config_parser, get_logger 

14from src.hardlink_registry import HardlinkRegistry 

15from src.photo_download_manager import ( 

16 DownloadTaskInfo, 

17 collect_download_task, 

18 execute_parallel_downloads, 

19 would_fall_back_to_original, 

20) 

21from src.photo_filter_utils import is_photo_wanted 

22from src.photo_path_utils import normalize_file_path 

23 

24LOGGER = get_logger() 

25 

26 

27def _now() -> float: 

28 """Monotonic clock for buffer ageing; a seam for tests.""" 

29 return time.monotonic() 

30 

31 

32# DEFAULT_ENUMERATION_CHUNK_SIZE lives in src/__init__.py (with the other 

33# DEFAULT_* config constants) and is re-exported here for backward-compat. 

34# Picked to keep peak RSS bounded at ~10–20 MB of DownloadTaskInfo objects 

35# per chunk on typical iCloud libraries while still giving 

36# execute_parallel_downloads enough work to amortize HTTP connection setup. 

37# Users can override via ``photos.enumeration_chunk_size`` in config.yaml. 

38 

39 

40def sync_album_photos( 

41 album, 

42 destination_path: str, 

43 file_sizes: list[str], 

44 extensions: list[str] | None = None, 

45 files: set[str] | None = None, 

46 folder_format: str | None = None, 

47 hardlink_registry: HardlinkRegistry | None = None, 

48 config=None, 

49) -> tuple[int, int] | None: 

50 """Sync photos from given album. 

51 

52 This function orchestrates the synchronization of a single album by: 

53 1. Creating the destination directory 

54 2. Collecting download tasks for wanted photos 

55 3. Executing downloads in parallel 

56 4. Recursively syncing subalbums 

57 

58 Args: 

59 album: Album object from iCloudPy 

60 destination_path: Path where photos should be saved 

61 file_sizes: List of file size variants to download 

62 extensions: List of allowed file extensions (None = all allowed) 

63 files: Set to track downloaded files 

64 folder_format: strftime format string for folder organization 

65 hardlink_registry: Registry for tracking downloaded files for hardlinks 

66 config: Configuration dictionary 

67 

68 Returns: 

69 Tuple of (total_successful, total_failed) download counts, or None on invalid input 

70 """ 

71 if album is None or destination_path is None or file_sizes is None: 

72 return None 

73 

74 # Create destination directory with normalized path 

75 normalized_destination = normalize_file_path(destination_path) 

76 os.makedirs(normalized_destination, exist_ok=True) 

77 LOGGER.info(f"Syncing {album.title}") 

78 

79 # Stream the album in fixed-size chunks: collect → download → 

80 # release → next chunk. The task buffer is bounded by chunk_size 

81 # instead of len(album), avoiding the ~4 GB RSS seen when storing all 

82 # download tasks for a 111K-photo library (cgroup OOM at 4 GB). 

83 # Claimed asset IDs are retained per album pass to suppress repeated 

84 # entries from paginated enumeration. 

85 chunk_size = config_parser.get_photos_enumeration_chunk_size(config=config) 

86 total_successful, total_failed = _collect_and_execute_album_in_chunks( 

87 album, 

88 normalized_destination, 

89 file_sizes, 

90 extensions, 

91 files, 

92 folder_format, 

93 hardlink_registry, 

94 config, 

95 chunk_size=chunk_size, 

96 ) 

97 

98 # Recursively sync subalbums and aggregate counts 

99 sub_successful, sub_failed = _sync_subalbums( 

100 album, 

101 normalized_destination, 

102 file_sizes, 

103 extensions, 

104 files, 

105 folder_format, 

106 hardlink_registry, 

107 config, 

108 ) 

109 total_successful += sub_successful 

110 total_failed += sub_failed 

111 

112 return total_successful, total_failed 

113 

114 

115def _collect_photo_download_tasks( 

116 photo: Any, 

117 destination_path: str, 

118 file_sizes: list[str], 

119 extensions: list[str] | None, 

120 files: set[str] | None, 

121 folder_format: str | None, 

122 hardlink_registry: HardlinkRegistry | None, 

123 claimed_paths: set[str] | None = None, 

124) -> list[DownloadTaskInfo]: 

125 """Collect download tasks for a single photo, handling errors gracefully. 

126 

127 Wraps per-photo processing so that exceptions (e.g. binascii.Error from 

128 iCloudPy's base64-encoded filename decoding) are caught at the photo level 

129 rather than inside the album iteration loop (avoids PERF203). 

130 

131 Args: 

132 photo: Photo object from iCloudPy 

133 destination_path: Path where photos should be saved 

134 file_sizes: List of file size variants to download 

135 extensions: List of allowed file extensions 

136 files: Set of paths the run owns (granted after a verified write) 

137 folder_format: strftime format string for folder organization 

138 hardlink_registry: Registry for tracking downloaded files 

139 claimed_paths: Paths already queued earlier in this album pass 

140 

141 Returns: 

142 List of download tasks for this photo (empty on error or if unwanted) 

143 """ 

144 try: 

145 if not is_photo_wanted(photo, extensions): 

146 LOGGER.debug(f"Skipping the unwanted photo {photo.filename}.") 

147 return [] 

148 tasks: list[DownloadTaskInfo] = [] 

149 # With ``fallback_to_original`` on, two requested sizes a photo lacks 

150 # (e.g. ``[adjusted, alternative]`` for an unedited photo) both 

151 # resolve to ``original``. Claim that substitution once per photo so 

152 # the parallel executor never queues two downloads onto one path. 

153 fallback_claimed = False 

154 for file_size in file_sizes: 

155 if would_fall_back_to_original(photo, file_size): 

156 if fallback_claimed: 

157 LOGGER.debug( 

158 f"Already downloading the original for {photo.filename}; " 

159 f"skipping the {file_size} fallback.", 

160 ) 

161 continue 

162 fallback_claimed = True 

163 download_info = collect_download_task( 

164 photo, 

165 file_size, 

166 destination_path, 

167 files, 

168 folder_format, 

169 hardlink_registry, 

170 claimed_paths, 

171 ) 

172 if download_info: 

173 tasks.append(download_info) 

174 # Live Photos: add "live_video_original" (or _medium/_thumb) to 

175 # photos.filters.file_sizes to pull the paired .mov. It flows through 

176 # the loop above like any other version; non-Live-Photos don't have 

177 # those versions and are skipped (quietly -- see collect_download_task). 

178 return tasks 

179 except Exception as e: 

180 try: 

181 photo_id = photo.id 

182 except Exception: 

183 # Not just AttributeError: ``photo.id`` reads 

184 # ``_master_record["recordName"]``, so a malformed master 

185 # raises KeyError here. Anything unresolvable means this 

186 # id is unusable for the log line -- not that the album 

187 # should abort. 

188 photo_id = "<unknown>" 

189 LOGGER.warning( 

190 f"Error processing photo (id: {photo_id}), skipping: {type(e).__name__}: {e!s}", 

191 ) 

192 return [] 

193 

194 

195def _collect_and_execute_album_in_chunks( 

196 album, 

197 destination_path: str, 

198 file_sizes: list[str], 

199 extensions: list[str] | None, 

200 files: set[str] | None, 

201 folder_format: str | None, 

202 hardlink_registry: HardlinkRegistry | None, 

203 config, 

204 chunk_size: int = DEFAULT_ENUMERATION_CHUNK_SIZE, 

205) -> tuple[int, int]: 

206 """Stream album → fixed-size chunks → download → release. 

207 

208 Buffers up to ``chunk_size`` download tasks, then drains them via 

209 ``execute_parallel_downloads`` and clears the buffer before 

210 collecting the next chunk. The buffer also drains once its oldest 

211 task is ``BUFFERED_DOWNLOAD_MAX_AGE_SEC`` old, so download URLs (which 

212 expire ~30-40 minutes after listing) do not wait out a long walk of 

213 photos already on disk. That is checked between photos, so it is a 

214 bound on the usual wait, not a guarantee; a URL that still expires is 

215 recovered by the expired-URL refresh. Task memory is bounded by chunk_size; 

216 the set of claimed asset IDs grows with the number of queued assets in 

217 this album pass. Apart from repeated album entries, task counts and 

218 per-photo side effects match the unchunked path. 

219 

220 Args: 

221 album: Album object from iCloudPy 

222 destination_path: Path where photos should be saved 

223 file_sizes: List of file size variants to download 

224 extensions: List of allowed file extensions 

225 files: Set to track downloaded files 

226 folder_format: strftime format string for folder organization 

227 hardlink_registry: Registry for tracking downloaded files 

228 config: Configuration dictionary (passed through to 

229 ``execute_parallel_downloads`` for per-album thread count) 

230 chunk_size: Tasks to buffer before draining. Smaller = lower 

231 peak memory but more per-chunk HTTP setup overhead. 

232 

233 Returns: 

234 Tuple of (total_successful, total_failed) summed across chunks. 

235 """ 

236 if chunk_size <= 0: 

237 # Degenerate config; fall back to default rather than refusing 

238 # to sync. Logging is at INFO so operators see the fallback. 

239 LOGGER.info( 

240 f"Invalid photos.enumeration_chunk_size={chunk_size!r}; " 

241 f"using default {DEFAULT_ENUMERATION_CHUNK_SIZE}.", 

242 ) 

243 chunk_size = DEFAULT_ENUMERATION_CHUNK_SIZE 

244 

245 buffer: list[DownloadTaskInfo] = [] 

246 # A paged album can yield the same asset again after a chunk has drained. 

247 # The master id alone is not enough: separate edits may share a master. 

248 claimed_assets: set[tuple[str, str]] = set() 

249 # Paths queued by this album pass, used to route in-flight filename 

250 # collisions to the suffix name. Ownership (``files``) is granted only 

251 # once a transfer verifies, so a failed download cannot shelter a 

252 # never-written path from obsolete cleanup. 

253 claimed_paths: set[str] = set() 

254 # When the buffer must drain regardless of size; None while it is empty. 

255 drain_by: float | None = None 

256 total_successful = 0 

257 total_failed = 0 

258 

259 def _drain(): 

260 nonlocal total_successful, total_failed, buffer, drain_by 

261 if not buffer: 

262 return 

263 succ, fail = execute_parallel_downloads(buffer, config) 

264 total_successful += succ 

265 total_failed += fail 

266 # Rebind to a fresh list rather than clearing in place: the old 

267 # list was just handed to execute_parallel_downloads, so a fresh 

268 # object gives each chunk an independent buffer (no aliasing of 

269 # an already-passed list) and lets the old chunk's task objects 

270 # (and the photo refs they hold) be collected immediately. 

271 buffer = [] 

272 drain_by = None 

273 

274 for photo in album: 

275 asset_record = getattr(photo, "_asset_record", None) 

276 asset_id = asset_record.get("recordName") if isinstance(asset_record, dict) else None 

277 try: 

278 master_id = photo.id 

279 except AttributeError, KeyError: 

280 # Leave malformed photos to the collector's per-photo error handler. 

281 asset_key = None 

282 else: 

283 asset_key = (master_id, asset_id or master_id) 

284 if asset_key is not None and asset_key in claimed_assets: 

285 continue 

286 tasks = _collect_photo_download_tasks( 

287 photo, 

288 destination_path, 

289 file_sizes, 

290 extensions, 

291 files, 

292 folder_format, 

293 hardlink_registry, 

294 claimed_paths, 

295 ) 

296 if tasks and asset_key is not None: 

297 claimed_assets.add(asset_key) 

298 if tasks and drain_by is None: 

299 drain_by = _now() + BUFFERED_DOWNLOAD_MAX_AGE_SEC 

300 buffer.extend(tasks) 

301 aged_out = drain_by is not None and _now() >= drain_by 

302 if len(buffer) >= chunk_size or aged_out: 

303 _drain() 

304 

305 _drain() # final partial chunk 

306 

307 return total_successful, total_failed 

308 

309 

310def _sync_subalbums( 

311 album, 

312 destination_path: str, 

313 file_sizes: list[str], 

314 extensions: list[str] | None, 

315 files: set[str] | None, 

316 folder_format: str | None, 

317 hardlink_registry: HardlinkRegistry | None, 

318 config, 

319) -> tuple[int, int]: 

320 """Recursively sync all subalbums. 

321 

322 Args: 

323 album: Album object from iCloudPy 

324 destination_path: Base path where subalbums should be created 

325 file_sizes: List of file size variants to download 

326 extensions: List of allowed file extensions 

327 files: Set to track downloaded files 

328 folder_format: strftime format string for folder organization 

329 hardlink_registry: Registry for tracking downloaded files 

330 config: Configuration dictionary 

331 

332 Returns: 

333 Tuple of (total_successful, total_failed) aggregated across all subalbums 

334 """ 

335 total_successful, total_failed = 0, 0 

336 for subalbum in album.subalbums: 

337 result = sync_album_photos( 

338 album.subalbums[subalbum], 

339 os.path.join(destination_path, subalbum), 

340 file_sizes, 

341 extensions, 

342 files, 

343 folder_format, 

344 hardlink_registry, 

345 config, 

346 ) 

347 if result is not None: 

348 sub_successful, sub_failed = result 

349 total_successful += sub_successful 

350 total_failed += sub_failed 

351 return total_successful, total_failed