Coverage for fastblocks / actions / sync / static.py: 32%
382 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Static files synchronization between filesystem, cloud storage, and selective caching.
3Static sync uses selective caching based on file type:
4- Text-based files (CSS, JS, MD, TXT) are cached for performance
5- Binary files (images, fonts, media) sync to storage only to avoid cache bloat
6"""
8import typing as t
9from pathlib import Path
11import yaml
12from oneiric.core.resolution import Resolver
14# Migration from ACB to Oneiric
15depends = Resolver()
17# ACB compatibility imports - these will be migrated in future phases
18try:
19 # MIGRATED: Removed ACB import - debug import debug
20 pass
21except ImportError:
22 # Fallback for Oneiric-only mode
23 def debug(msg: str) -> None:
24 """Debug function fallback."""
25 print(f"[DEBUG] {msg}")
28from anyio import Path as AsyncPath
30from .strategies import (
31 ConflictStrategy,
32 SyncDirection,
33 SyncResult,
34 SyncStrategy,
35 create_backup,
36 get_file_info,
37 resolve_conflict,
38 should_sync,
39)
42class StaticSyncResult(SyncResult):
43 def __init__(
44 self,
45 *,
46 assets_processed: list[str] | None = None,
47 mime_types_detected: dict[str, str] | None = None,
48 cache_invalidated: list[str] | None = None,
49 cache_cleared: list[str] | None = None,
50 cacheable_assets: list[str] | None = None,
51 non_cacheable_assets: list[str] | None = None,
52 **kwargs: t.Any,
53 ) -> None:
54 super().__init__(**kwargs)
55 self.assets_processed = assets_processed if assets_processed is not None else []
56 self.mime_types_detected = (
57 mime_types_detected if mime_types_detected is not None else {}
58 )
59 self.cache_invalidated = (
60 cache_invalidated if cache_invalidated is not None else []
61 )
62 self.cache_cleared = cache_cleared if cache_cleared is not None else []
63 self.cacheable_assets = cacheable_assets if cacheable_assets is not None else []
64 self.non_cacheable_assets = (
65 non_cacheable_assets if non_cacheable_assets is not None else []
66 )
69CACHEABLE_EXTENSIONS = {".css", ".js", ".md", ".txt"}
70NON_CACHEABLE_EXTENSIONS = {
71 ".png",
72 ".jpg",
73 ".jpeg",
74 ".gif",
75 ".svg",
76 ".ico",
77 ".webp",
78 ".avif",
79 ".mp4",
80 ".mov",
81 ".mp3",
82 ".wav",
83 ".pdf",
84 ".zip",
85 ".woff",
86 ".woff2",
87 ".ttf",
88 ".eot",
89 ".otf",
90}
93def _is_cacheable_file(file_path: AsyncPath) -> bool:
94 return file_path.suffix.lower() in CACHEABLE_EXTENSIONS
97async def sync_static(
98 *,
99 static_path: AsyncPath | None = None,
100 file_patterns: list[str] | None = None,
101 strategy: SyncStrategy | None = None,
102 storage_bucket: str | None = None,
103 exclude_patterns: list[str] | None = None,
104) -> StaticSyncResult:
105 config = _prepare_static_sync_config(
106 static_path, file_patterns, strategy, exclude_patterns
107 )
108 result = StaticSyncResult()
110 if storage_bucket is None:
111 storage_bucket = await _get_default_static_bucket()
113 adapters = await _initialize_adapters(result)
114 if not adapters:
115 return result
117 static_files = await _discover_static_files(
118 config["static_path"],
119 config["file_patterns"],
120 config["exclude_patterns"],
121 )
122 if not static_files:
123 debug("No static files found to sync")
124 return result
126 debug(f"Found {len(static_files)} static files to sync")
128 await _sync_static_files(
129 static_files,
130 adapters,
131 config["strategy"],
132 storage_bucket,
133 result,
134 )
136 debug(
137 f"Static sync completed: {len(result.synced_items)} synced, {len(result.conflicts)} conflicts",
138 )
140 return result
143def _prepare_static_sync_config(
144 static_path: AsyncPath | None,
145 file_patterns: list[str] | None,
146 strategy: SyncStrategy | None,
147 exclude_patterns: list[str] | None,
148) -> dict[str, t.Any]:
149 return {
150 "static_path": static_path or AsyncPath("static"),
151 "file_patterns": file_patterns
152 or [
153 "*.css",
154 "*.js",
155 "*.png",
156 "*.jpg",
157 "*.jpeg",
158 "*.gif",
159 "*.svg",
160 "*.ico",
161 "*.woff",
162 "*.woff2",
163 "*.ttf",
164 "*.eot",
165 "*.otf",
166 "*.webp",
167 "*.avif",
168 "*.pdf",
169 "*.zip",
170 "*.tar.gz",
171 ],
172 "strategy": strategy or SyncStrategy(),
173 "exclude_patterns": exclude_patterns or ["*.tmp", "*.log", ".*", "__pycache__"],
174 }
177async def _initialize_adapters(result: StaticSyncResult) -> dict[str, t.Any] | None:
178 try:
179 # MIGRATED: Removed ACB import - using Oneiric equivalent
181 storage = await depends.resolve("fastblocks", "storage")
182 cache = await depends.resolve("fastblocks", "cache")
183 if not storage:
184 result.errors.append(Exception("Storage adapter not available"))
185 return None
187 return {"storage": storage, "cache": cache}
188 except Exception as e:
189 result.errors.append(e)
190 return None
193async def _get_default_static_bucket() -> str:
194 try:
195 storage_config_path = AsyncPath("settings/storage.yml")
196 if await storage_config_path.exists():
197 content = await storage_config_path.read_text()
198 config = yaml.safe_load(content)
199 if isinstance(config, dict):
200 bucket_name = t.cast(
201 str, config.get("buckets", {}).get("static", "static")
202 )
203 else:
204 bucket_name = "static"
205 debug(f"Using static bucket from config: {bucket_name}")
206 return bucket_name
207 except Exception as e:
208 debug(f"Could not load storage config, using default: {e}")
209 debug("Using fallback static bucket: static")
210 return "static"
213async def _discover_static_files(
214 static_path: AsyncPath,
215 file_patterns: list[str],
216 exclude_patterns: list[str],
217) -> list[dict[str, t.Any]]:
218 static_files: list[dict[str, t.Any]] = []
220 if not await static_path.exists():
221 debug(f"Static path does not exist: {static_path}")
222 return static_files
224 for pattern in file_patterns:
225 await _discover_files_with_pattern(
226 static_path,
227 pattern,
228 exclude_patterns,
229 static_files,
230 )
232 return static_files
235async def _discover_files_with_pattern(
236 static_path: AsyncPath,
237 pattern: str,
238 exclude_patterns: list[str],
239 static_files: list[dict[str, t.Any]],
240) -> None:
241 async for file_path in static_path.rglob(pattern):
242 if await file_path.is_file():
243 if _should_exclude_file(file_path, exclude_patterns):
244 continue
246 await _process_static_file(
247 file_path,
248 static_path,
249 static_files,
250 )
253def _should_exclude_file(file_path: AsyncPath, exclude_patterns: list[str]) -> bool:
254 import fnmatch
256 file_name = file_path.name
257 relative_path = str(file_path)
258 for pattern in exclude_patterns:
259 if fnmatch.fnmatch(file_name, pattern) or fnmatch.fnmatch(
260 relative_path, pattern
261 ):
262 return True
264 return False
267async def _process_static_file(
268 file_path: AsyncPath,
269 static_path: AsyncPath,
270 static_files: list[dict[str, t.Any]],
271) -> None:
272 try:
273 rel_path = file_path.relative_to(static_path)
274 mime_type = _detect_mime_type(file_path)
275 is_cacheable = _is_cacheable_file(file_path)
277 static_files.append(
278 {
279 "local_path": file_path,
280 "relative_path": rel_path,
281 "storage_path": str(rel_path),
282 "mime_type": mime_type,
283 "is_cacheable": is_cacheable,
284 },
285 )
286 except ValueError:
287 debug(f"Could not get relative path for {file_path}")
290def _detect_mime_type(file_path: AsyncPath) -> str:
291 import mimetypes
293 mime_type, _ = mimetypes.guess_type(str(file_path))
294 return mime_type or "application/octet-stream"
297async def _sync_static_files(
298 static_files: list[dict[str, t.Any]],
299 adapters: dict[str, t.Any],
300 strategy: SyncStrategy,
301 storage_bucket: str,
302 result: StaticSyncResult,
303) -> None:
304 for static_info in static_files:
305 try:
306 file_result = await _sync_single_static_file(
307 static_info,
308 adapters["storage"],
309 adapters["cache"],
310 strategy,
311 storage_bucket,
312 )
313 _accumulate_static_sync_results(file_result, result)
315 if file_result.get("synced"):
316 result.assets_processed.append(static_info["storage_path"])
317 result.mime_types_detected[static_info["storage_path"]] = static_info[
318 "mime_type"
319 ]
321 if static_info["is_cacheable"]:
322 result.cacheable_assets.append(static_info["storage_path"])
323 else:
324 result.non_cacheable_assets.append(static_info["storage_path"])
326 except Exception as e:
327 result.errors.append(e)
328 debug(f"Error syncing static file {static_info['relative_path']}: {e}")
331def _accumulate_static_sync_results(
332 file_result: dict[str, t.Any],
333 result: StaticSyncResult,
334) -> None:
335 if file_result.get("synced"):
336 result.synced_items.extend(file_result["synced"])
337 if file_result.get("conflicts"):
338 result.conflicts.extend(file_result["conflicts"])
339 if file_result.get("errors"):
340 result.errors.extend(file_result["errors"])
341 if file_result.get("skipped"):
342 result.skipped.extend(file_result["skipped"])
343 if file_result.get("backed_up"):
344 result.backed_up.extend(file_result["backed_up"])
345 if file_result.get("cache_invalidated"):
346 result.cache_invalidated.extend(file_result["cache_invalidated"])
347 if file_result.get("cache_cleared"):
348 result.cache_cleared.extend(file_result["cache_cleared"])
351async def _sync_single_static_file(
352 static_info: dict[str, t.Any],
353 storage: t.Any,
354 cache: t.Any,
355 strategy: SyncStrategy,
356 storage_bucket: str,
357) -> dict[str, t.Any]:
358 local_path = static_info["local_path"]
359 storage_path = static_info["storage_path"]
360 mime_type = static_info["mime_type"]
361 is_cacheable = static_info["is_cacheable"]
363 result = _create_sync_result()
365 try:
366 local_info, remote_info = await _get_file_infos(
367 local_path,
368 storage,
369 storage_bucket,
370 storage_path,
371 )
373 if not await _should_sync_file(
374 local_info,
375 remote_info,
376 strategy,
377 storage_path,
378 result,
379 ):
380 return result
382 await _execute_sync_operation(
383 local_path,
384 storage,
385 cache,
386 storage_bucket,
387 storage_path,
388 local_info,
389 remote_info,
390 strategy,
391 mime_type,
392 is_cacheable,
393 result,
394 )
396 except Exception as e:
397 result["errors"].append(e)
398 debug(f"Error in _sync_single_static_file for {storage_path}: {e}")
400 return result
403def _create_sync_result() -> dict[str, t.Any]:
404 return {
405 "synced": [],
406 "conflicts": [],
407 "errors": [],
408 "skipped": [],
409 "backed_up": [],
410 "cache_invalidated": [],
411 "cache_cleared": [],
412 }
415async def _get_file_infos(
416 local_path: t.Any,
417 storage: t.Any,
418 storage_bucket: str,
419 storage_path: str,
420) -> tuple[dict[str, t.Any], dict[str, t.Any]]:
421 local_info = await get_file_info(Path(local_path))
422 remote_info = await _get_storage_file_info(storage, storage_bucket, storage_path)
423 return local_info, remote_info
426async def _should_sync_file(
427 local_info: dict[str, t.Any],
428 remote_info: dict[str, t.Any],
429 strategy: SyncStrategy,
430 storage_path: str,
431 result: dict[str, t.Any],
432) -> bool:
433 sync_needed, reason = should_sync(local_info, remote_info, strategy.direction)
434 if not sync_needed:
435 result["skipped"].append(f"{storage_path} ({reason})")
436 return False
438 debug(f"Syncing static file {storage_path}: {reason}")
439 return True
442async def _execute_sync_operation(
443 local_path: t.Any,
444 storage: t.Any,
445 cache: t.Any,
446 storage_bucket: str,
447 storage_path: str,
448 local_info: dict[str, t.Any],
449 remote_info: dict[str, t.Any],
450 strategy: SyncStrategy,
451 mime_type: str,
452 is_cacheable: bool,
453 result: dict[str, t.Any],
454) -> None:
455 if _should_pull_static(strategy, local_info, remote_info):
456 await _pull_static(
457 local_path,
458 storage,
459 cache,
460 storage_bucket,
461 storage_path,
462 strategy,
463 is_cacheable,
464 result,
465 )
466 elif _should_push_static(strategy, local_info, remote_info):
467 await _push_static(
468 local_path,
469 storage,
470 cache,
471 storage_bucket,
472 storage_path,
473 strategy,
474 mime_type,
475 is_cacheable,
476 result,
477 )
478 elif _has_bidirectional_conflict(strategy, local_info, remote_info):
479 await _handle_static_conflict(
480 local_path,
481 storage,
482 cache,
483 storage_bucket,
484 storage_path,
485 local_info,
486 remote_info,
487 strategy,
488 mime_type,
489 is_cacheable,
490 result,
491 )
494def _should_pull_static(
495 strategy: SyncStrategy,
496 local_info: dict[str, t.Any],
497 remote_info: dict[str, t.Any],
498) -> bool:
499 return strategy.direction == SyncDirection.PULL or (
500 strategy.direction == SyncDirection.BIDIRECTIONAL
501 and remote_info["exists"]
502 and (not local_info["exists"] or remote_info["mtime"] > local_info["mtime"])
503 )
506def _should_push_static(
507 strategy: SyncStrategy,
508 local_info: dict[str, t.Any],
509 remote_info: dict[str, t.Any],
510) -> bool:
511 return strategy.direction == SyncDirection.PUSH or (
512 strategy.direction == SyncDirection.BIDIRECTIONAL
513 and local_info["exists"]
514 and (not remote_info["exists"] or local_info["mtime"] > remote_info["mtime"])
515 )
518def _has_bidirectional_conflict(
519 strategy: SyncStrategy,
520 local_info: dict[str, t.Any],
521 remote_info: dict[str, t.Any],
522) -> bool:
523 return (
524 strategy.direction == SyncDirection.BIDIRECTIONAL
525 and local_info["exists"]
526 and remote_info["exists"]
527 )
530async def _get_storage_file_info(
531 storage: t.Any,
532 bucket: str,
533 file_path: str,
534) -> dict[str, t.Any]:
535 try:
536 bucket_obj = getattr(storage, bucket, None)
538 if not bucket_obj:
539 await storage._create_bucket(bucket)
540 bucket_obj = getattr(storage, bucket)
542 exists = await bucket_obj.exists(file_path)
544 if not exists:
545 return {
546 "exists": False,
547 "size": 0,
548 "mtime": 0,
549 "content_hash": None,
550 }
552 content = await bucket_obj.read(file_path)
553 metadata = await bucket_obj.stat(file_path)
555 import hashlib
557 content_hash = hashlib.blake2b(content).hexdigest()
559 return {
560 "exists": True,
561 "size": len(content),
562 "mtime": metadata.get("mtime", 0),
563 "content_hash": content_hash,
564 "content": content,
565 }
567 except Exception as e:
568 debug(f"Error getting storage file info for {file_path}: {e}")
569 return {
570 "exists": False,
571 "size": 0,
572 "mtime": 0,
573 "content_hash": None,
574 "error": str(e),
575 }
578async def _pull_static(
579 local_path: AsyncPath,
580 storage: t.Any,
581 cache: t.Any,
582 bucket: str,
583 storage_path: str,
584 strategy: SyncStrategy,
585 is_cacheable: bool,
586 result: dict[str, t.Any],
587) -> None:
588 try:
589 bucket_obj = getattr(storage, bucket)
591 if strategy.dry_run:
592 debug(f"DRY RUN: Would pull {storage_path} to {local_path}")
593 result["synced"].append(f"PULL(dry-run): {storage_path}")
594 return
596 if await local_path.exists() and strategy.backup_on_conflict:
597 backup_path = await create_backup(Path(local_path))
598 result["backed_up"].append(str(backup_path))
600 content = await bucket_obj.read(storage_path)
602 await local_path.parent.mkdir(parents=True, exist_ok=True)
603 await local_path.write_bytes(content)
605 result["synced"].append(f"PULL: {storage_path}")
606 debug(f"Pulled static file from storage: {storage_path}")
608 if is_cacheable and cache:
609 await _cache_static_file(cache, storage_path, content, result)
611 except Exception as e:
612 result["errors"].append(e)
613 debug(f"Error pulling static file {storage_path}: {e}")
616async def _push_static(
617 local_path: AsyncPath,
618 storage: t.Any,
619 cache: t.Any,
620 bucket: str,
621 storage_path: str,
622 strategy: SyncStrategy,
623 mime_type: str,
624 is_cacheable: bool,
625 result: dict[str, t.Any],
626) -> None:
627 try:
628 bucket_obj = getattr(storage, bucket)
630 if strategy.dry_run:
631 debug(f"DRY RUN: Would push {local_path} to {storage_path}")
632 result["synced"].append(f"PUSH(dry-run): {storage_path}")
633 return
635 content = await local_path.read_bytes()
637 metadata = {"content_type": mime_type}
638 await bucket_obj.write(storage_path, content, metadata=metadata)
640 result["synced"].append(f"PUSH: {storage_path}")
641 debug(f"Pushed static file to storage: {storage_path} (MIME: {mime_type})")
643 if is_cacheable and cache:
644 await _cache_static_file(cache, storage_path, content, result)
646 except Exception as e:
647 result["errors"].append(e)
648 debug(f"Error pushing static file {storage_path}: {e}")
651async def _handle_static_conflict(
652 local_path: AsyncPath,
653 storage: t.Any,
654 cache: t.Any,
655 bucket: str,
656 storage_path: str,
657 local_info: dict[str, t.Any],
658 remote_info: dict[str, t.Any],
659 strategy: SyncStrategy,
660 mime_type: str,
661 is_cacheable: bool,
662 result: dict[str, t.Any],
663) -> None:
664 try:
665 if strategy.conflict_strategy == ConflictStrategy.MANUAL:
666 result["conflicts"].append(
667 {
668 "path": storage_path,
669 "local_mtime": local_info["mtime"],
670 "remote_mtime": remote_info["mtime"],
671 "reason": "manual_resolution_required",
672 },
673 )
674 return
676 resolved_content, resolution_reason = await resolve_conflict(
677 Path(local_path),
678 remote_info["content"],
679 local_info["content"],
680 strategy.conflict_strategy,
681 local_info["mtime"],
682 remote_info["mtime"],
683 )
685 if strategy.dry_run:
686 debug(
687 f"DRY RUN: Would resolve conflict for {storage_path}: {resolution_reason}",
688 )
689 result["synced"].append(
690 f"CONFLICT(dry-run): {storage_path} - {resolution_reason}",
691 )
692 return
694 if (
695 strategy.backup_on_conflict
696 or strategy.conflict_strategy == ConflictStrategy.BACKUP_BOTH
697 ):
698 backup_path = await create_backup(Path(local_path), "conflict")
699 result["backed_up"].append(str(backup_path))
701 if resolved_content == remote_info["content"]:
702 await local_path.write_bytes(resolved_content)
703 result["synced"].append(
704 f"CONFLICT->REMOTE: {storage_path} - {resolution_reason}",
705 )
706 else:
707 bucket_obj = getattr(storage, bucket)
708 metadata = {"content_type": mime_type}
709 await bucket_obj.write(storage_path, resolved_content, metadata=metadata)
710 result["synced"].append(
711 f"CONFLICT->LOCAL: {storage_path} - {resolution_reason}",
712 )
714 if is_cacheable and cache:
715 await _cache_static_file(cache, storage_path, resolved_content, result)
717 debug(f"Resolved static conflict: {storage_path} - {resolution_reason}")
719 except Exception as e:
720 result["errors"].append(e)
721 result["conflicts"].append(
722 {
723 "path": storage_path,
724 "error": str(e),
725 "reason": "resolution_failed",
726 },
727 )
730async def _cache_static_file(
731 cache: t.Any,
732 storage_path: str,
733 content: bytes,
734 result: dict[str, t.Any],
735) -> None:
736 if not cache:
737 return
739 try:
740 cache_key = f"static:{storage_path}"
741 await cache.set(cache_key, content, ttl=86400)
742 result["cache_invalidated"].append(cache_key)
743 debug(f"Cached static file: {storage_path}")
744 except Exception as e:
745 debug(f"Error caching static file {storage_path}: {e}")
747 pass
750async def _validate_cache_dependencies() -> tuple[t.Any, t.Any, dict[str, t.Any]]:
751 """Validate and return cache and storage dependencies."""
752 # MIGRATED: Removed ACB import - using Oneiric equivalent
754 cache = await depends.resolve("fastblocks", "cache")
755 storage = await depends.resolve("fastblocks", "storage")
756 result: dict[str, t.Any] = {
757 "warmed": [],
758 "errors": [],
759 "skipped": [],
760 }
762 if not cache or not storage:
763 result["errors"].append(Exception("Cache or storage not available"))
764 return None, None, result
766 return cache, storage, result
769async def _warm_single_static_file(
770 static_path: str,
771 cache: t.Any,
772 storage: t.Any,
773 cache_namespace: str,
774 result: dict[str, t.Any],
775) -> None:
776 """Warm cache for a single static file."""
777 try:
778 if not _is_cacheable_file(AsyncPath(static_path)):
779 result["skipped"].append(f"{static_path} (not cacheable)")
780 return
782 cache_key = f"{cache_namespace}:{static_path}"
783 if await cache.exists(cache_key):
784 result["skipped"].append(static_path)
785 return
787 content = await storage.static.read(static_path)
788 await cache.set(cache_key, content, ttl=86400)
789 result["warmed"].append(static_path)
791 debug(f"Warmed cache for static file: {static_path}")
793 except Exception as e:
794 result["errors"].append(f"{static_path}: {e}")
795 debug(f"Error warming cache for static file {static_path}: {e}")
798async def warm_static_cache(
799 static_paths: list[str] | None = None,
800 cache_namespace: str = "static",
801) -> dict[str, t.Any]:
802 result: dict[str, t.Any] = {
803 "warmed": [],
804 "errors": [],
805 "skipped": [],
806 }
808 if not static_paths:
809 static_paths = [
810 "css/main.css",
811 "css/app.css",
812 "js/main.js",
813 "js/app.js",
814 ]
816 try:
817 cache, storage, dep_result = await _validate_cache_dependencies()
818 if not cache or not storage:
819 return dep_result
821 result = dep_result
823 for static_path in static_paths:
824 await _warm_single_static_file(
825 static_path, cache, storage, cache_namespace, result
826 )
828 except Exception as e:
829 result["errors"].append(str(e))
830 debug(f"Error in warm_static_cache: {e}")
832 return result
835async def get_static_sync_status(
836 static_path: AsyncPath | None = None,
837 storage_bucket: str = "static",
838) -> dict[str, t.Any]:
839 if static_path is None:
840 static_path = AsyncPath("static")
842 status: dict[str, t.Any] = {
843 "total_static_files": 0,
844 "in_sync": 0,
845 "out_of_sync": 0,
846 "local_only": 0,
847 "remote_only": 0,
848 "conflicts": 0,
849 "details": [],
850 }
852 try:
853 storage = await _get_storage_adapter()
854 if not storage:
855 status["error"] = "Storage adapter not available"
856 return status
858 static_files = await _discover_static_files(
859 static_path,
860 ["*.css", "*.js", "*.png", "*.jpg", "*.jpeg", "*.gif", "*.svg", "*.ico"],
861 ["*.tmp", "*.log", ".*"],
862 )
863 status["total_static_files"] = len(static_files)
865 await _process_static_files(static_files, storage, storage_bucket, status)
867 status["out_of_sync"] = (
868 status["conflicts"] + status["local_only"] + status["remote_only"]
869 )
871 except Exception as e:
872 status["error"] = str(e)
873 debug(f"Error getting static sync status: {e}")
875 return status
878async def _get_storage_adapter() -> t.Any:
879 """Get the storage adapter."""
880 # MIGRATED: Removed ACB import - using Oneiric equivalent
882 return depends.resolve("fastblocks", "storage")
885async def _process_static_files(
886 static_files: list[dict[str, t.Any]],
887 storage: t.Any,
888 storage_bucket: str,
889 status: dict[str, t.Any],
890) -> None:
891 """Process all static files and update status."""
892 for static_info in static_files:
893 local_info = await get_file_info(Path(static_info["local_path"]))
894 remote_info = await _get_storage_file_info(
895 storage,
896 storage_bucket,
897 static_info["storage_path"],
898 )
900 file_status = _create_file_status(static_info, local_info, remote_info)
901 _update_status_counters(local_info, remote_info, file_status, status)
902 status["details"].append(file_status)
905def _create_file_status(
906 static_info: dict[str, t.Any],
907 local_info: dict[str, t.Any],
908 remote_info: dict[str, t.Any],
909) -> dict[str, t.Any]:
910 """Create file status dictionary."""
911 file_status: dict[str, t.Any] = {
912 "path": static_info["storage_path"],
913 "mime_type": static_info["mime_type"],
914 "local_exists": local_info["exists"],
915 "remote_exists": remote_info["exists"],
916 }
918 # Determine sync status
919 if local_info["exists"] and remote_info["exists"]:
920 if local_info["content_hash"] == remote_info["content_hash"]:
921 file_status["status"] = "in_sync"
922 else:
923 file_status["status"] = "conflict"
924 file_status["local_mtime"] = local_info["mtime"]
925 file_status["remote_mtime"] = remote_info["mtime"]
926 elif local_info["exists"]:
927 file_status["status"] = "local_only"
928 elif remote_info["exists"]:
929 file_status["status"] = "remote_only"
930 else:
931 file_status["status"] = "missing"
933 return file_status
936def _update_status_counters(
937 local_info: dict[str, t.Any],
938 remote_info: dict[str, t.Any],
939 file_status: dict[str, t.Any],
940 status: dict[str, t.Any],
941) -> None:
942 """Update status counters based on file status."""
943 if local_info["exists"] and remote_info["exists"]:
944 if local_info["content_hash"] == remote_info["content_hash"]:
945 status["in_sync"] += 1
946 else:
947 status["conflicts"] += 1
948 elif local_info["exists"]:
949 status["local_only"] += 1
950 elif remote_info["exists"]:
951 status["remote_only"] += 1
954async def backup_static_files(
955 static_path: AsyncPath | None = None,
956 backup_suffix: str | None = None,
957) -> dict[str, t.Any]:
958 static_path = static_path or AsyncPath("static")
959 backup_suffix = backup_suffix or _generate_backup_suffix()
961 result = _create_backup_result()
963 try:
964 if not await static_path.exists():
965 result["errors"].append(f"Static path does not exist: {static_path}")
966 return result
968 await _backup_static_files_with_patterns(static_path, backup_suffix, result)
970 except Exception as e:
971 result["errors"].append(str(e))
972 debug(f"Error in backup_static_files: {e}")
974 return result
977def _generate_backup_suffix() -> str:
978 import time
980 timestamp = int(time.time())
981 return f"backup_{timestamp}"
984def _create_backup_result() -> dict[str, t.Any]:
985 return {
986 "backed_up": [],
987 "errors": [],
988 "skipped": [],
989 }
992async def _backup_static_files_with_patterns(
993 static_path: AsyncPath,
994 backup_suffix: str,
995 result: dict[str, t.Any],
996) -> None:
997 patterns = [
998 "*.css",
999 "*.js",
1000 "*.png",
1001 "*.jpg",
1002 "*.jpeg",
1003 "*.gif",
1004 "*.svg",
1005 "*.ico",
1006 "*.woff",
1007 "*.woff2",
1008 "*.ttf",
1009 "*.eot",
1010 "*.otf",
1011 "*.webp",
1012 "*.avif",
1013 ]
1015 for pattern in patterns:
1016 await _backup_files_with_pattern(static_path, pattern, backup_suffix, result)
1019async def _backup_files_with_pattern(
1020 static_path: AsyncPath,
1021 pattern: str,
1022 backup_suffix: str,
1023 result: dict[str, t.Any],
1024) -> None:
1025 async for file_path in static_path.rglob(pattern):
1026 if await file_path.is_file():
1027 await _backup_single_file(file_path, backup_suffix, result)
1030async def _backup_single_file(
1031 file_path: AsyncPath,
1032 backup_suffix: str,
1033 result: dict[str, t.Any],
1034) -> None:
1035 try:
1036 backup_path = await create_backup(Path(file_path), backup_suffix)
1037 result["backed_up"].append(str(backup_path))
1038 except Exception as e:
1039 result["errors"].append(f"{file_path}: {e}")
1042# Migration status indicator
1043# Note: Partial migration - ACB debug system still in use
1044_using_oneiric = True # Oneiric resolver available
1045_requires_further_migration = True # ACB debug system needs migration