Coverage for fastblocks / actions / sync / templates.py: 35%
358 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"""Template synchronization between filesystem, storage, and cache layers."""
3import typing as t
4from pathlib import Path
6import yaml
7from oneiric.core.resolution import Resolver
9# Migration from ACB to Oneiric
10depends = Resolver()
12# ACB compatibility imports - these will be migrated in future phases
13try:
14 # MIGRATED: Removed ACB import - debug import debug
15 pass
16except ImportError:
17 # Fallback for Oneiric-only mode
18 def debug(msg: str) -> None:
19 """Debug function fallback."""
20 print(f"[DEBUG] {msg}")
23from anyio import Path as AsyncPath
25from .strategies import (
26 ConflictStrategy,
27 SyncDirection,
28 SyncResult,
29 SyncStrategy,
30 create_backup,
31 get_file_info,
32 resolve_conflict,
33 should_sync,
34)
37class TemplateSyncResult(SyncResult):
38 def __init__(
39 self,
40 *,
41 cache_invalidated: list[str] | None = None,
42 bytecode_cleared: list[str] | None = None,
43 **kwargs: t.Any,
44 ) -> None:
45 super().__init__(**kwargs)
46 self.cache_invalidated = (
47 cache_invalidated if cache_invalidated is not None else []
48 )
49 self.bytecode_cleared = bytecode_cleared if bytecode_cleared is not None else []
50 self._direction: str | None = None
51 self._conflict_strategy: str | None = None
52 self._filters: dict[str, t.Any] | None = None
53 self._dry_run: bool = False
55 @property
56 def synchronized_files(self) -> list[str]:
57 return self.synced_items
59 @property
60 def sync_status(self) -> str:
61 if self.has_errors:
62 return "error"
63 elif self.has_conflicts:
64 return "conflict"
65 elif self.synced_items:
66 return "success"
67 return "no_changes"
69 @property
70 def conflicts_resolved(self) -> list[dict[str, t.Any]]:
71 return self.conflicts
73 @property
74 def direction(self) -> str | None:
75 return getattr(self, "_direction", None)
77 @property
78 def conflict_strategy(self) -> str | None:
79 return getattr(self, "_conflict_strategy", None)
81 @property
82 def conflicts_requiring_resolution(self) -> list[dict[str, t.Any]]:
83 return self.conflicts
85 @property
86 def filtered_files(self) -> list[str]:
87 return []
89 @property
90 def dry_run(self) -> bool:
91 return getattr(self, "_dry_run", False)
93 @property
94 def would_sync_files(self) -> list[str]:
95 if self.dry_run:
96 return [item for item in self.synced_items if "dry-run" in item]
97 return []
99 @property
100 def would_resolve_conflicts(self) -> list[dict[str, t.Any]]:
101 if self.dry_run:
102 return [conf for conf in self.conflicts if "dry-run" in str(conf)]
103 return []
106async def sync_templates(
107 *,
108 template_paths: list[AsyncPath] | None = None,
109 patterns: list[str] | None = None,
110 strategy: SyncStrategy | None = None,
111 storage_bucket: str | None = None,
112 direction: str | None = None,
113 conflict_strategy: str | None = None,
114 filters: dict[str, t.Any] | None = None,
115 dry_run: bool = False,
116) -> TemplateSyncResult:
117 if filters and "include_patterns" in filters:
118 patterns = filters["include_patterns"]
120 config = _prepare_sync_config(
121 template_paths, patterns, strategy, direction, conflict_strategy, dry_run
122 )
123 result = TemplateSyncResult()
124 result._direction = config.get("direction")
125 result._conflict_strategy = conflict_strategy
126 result._filters = filters
127 result._dry_run = dry_run
129 if storage_bucket is None:
130 storage_bucket = await _get_default_templates_bucket()
132 try:
133 adapters = await _initialize_adapters(result)
134 except Exception as e:
135 result.errors.append(e)
136 debug(f"Error initializing adapters: {e}")
137 return result
139 if not adapters:
140 return result
142 template_files = await _discover_template_files(
143 config["template_paths"],
144 config["patterns"],
145 )
146 debug(f"Found {len(template_files)} template files to sync")
148 await _sync_template_files(
149 template_files,
150 adapters,
151 config["strategy"],
152 storage_bucket,
153 result,
154 )
156 debug(
157 f"Template sync completed: {len(result.synced_items)} synced, {len(result.conflicts)} conflicts",
158 )
159 return result
162def _prepare_sync_config(
163 template_paths: list[AsyncPath] | None,
164 patterns: list[str] | None,
165 strategy: SyncStrategy | None,
166 direction: str | None = None,
167 conflict_strategy: str | None = None,
168 dry_run: bool = False,
169) -> dict[str, t.Any]:
170 direction_mapping = {
171 "cloud_to_local": SyncDirection.PULL,
172 "local_to_cloud": SyncDirection.PUSH,
173 "bidirectional": SyncDirection.BIDIRECTIONAL,
174 }
176 conflict_mapping = {
177 "local_wins": ConflictStrategy.LOCAL_WINS,
178 "remote_wins": ConflictStrategy.REMOTE_WINS,
179 "cloud_wins": ConflictStrategy.REMOTE_WINS,
180 "newest_wins": ConflictStrategy.NEWEST_WINS,
181 "manual": ConflictStrategy.MANUAL,
182 "backup_both": ConflictStrategy.BACKUP_BOTH,
183 }
185 if strategy is None:
186 sync_direction = SyncDirection.BIDIRECTIONAL
187 if direction and direction in direction_mapping:
188 sync_direction = direction_mapping[direction]
190 sync_conflict = ConflictStrategy.NEWEST_WINS
191 if conflict_strategy and conflict_strategy in conflict_mapping:
192 sync_conflict = conflict_mapping[conflict_strategy]
194 strategy = SyncStrategy(
195 direction=sync_direction, conflict_strategy=sync_conflict, dry_run=dry_run
196 )
198 return {
199 "template_paths": template_paths or [AsyncPath("templates")],
200 "patterns": patterns or ["*.html", "*.jinja2", "*.j2", "*.txt"],
201 "strategy": strategy,
202 "direction": direction,
203 }
206async def _initialize_adapters(result: TemplateSyncResult) -> dict[str, t.Any] | None:
207 try:
208 # MIGRATED: Removed ACB import - using Oneiric equivalent
210 storage = await depends.resolve("fastblocks", "storage")
211 cache = await depends.resolve("fastblocks", "cache")
212 if not storage:
213 result.errors.append(Exception("Storage adapter not available"))
214 return None
216 return {"storage": storage, "cache": cache}
217 except Exception as e:
218 result.errors.append(e)
219 return None
222async def _get_default_templates_bucket() -> str:
223 try:
224 storage_config_path = AsyncPath("settings/storage.yml")
225 if await storage_config_path.exists():
226 content = await storage_config_path.read_text()
227 config = yaml.safe_load(content)
228 if isinstance(config, dict):
229 bucket_name = t.cast(
230 str, config.get("buckets", {}).get("templates", "templates")
231 )
232 else:
233 bucket_name = "templates"
234 debug(f"Using templates bucket from config: {bucket_name}")
235 return bucket_name
236 except Exception as e:
237 debug(f"Could not load storage config, using default: {e}")
238 debug("Using fallback templates bucket: templates")
239 return "templates"
242async def _discover_template_files(
243 template_paths: list[AsyncPath],
244 patterns: list[str],
245) -> list[dict[str, t.Any]]:
246 template_files = []
248 for base_path in template_paths:
249 if not await base_path.exists():
250 debug(f"Template path does not exist: {base_path}")
251 continue
253 files = await _scan_path_for_templates(base_path, patterns)
254 template_files.extend(files)
256 return template_files
259async def _scan_path_for_templates(
260 base_path: AsyncPath,
261 patterns: list[str],
262) -> list[dict[str, t.Any]]:
263 files = []
265 for pattern in patterns:
266 async for file_path in base_path.rglob(pattern):
267 if await file_path.is_file():
268 try:
269 rel_path = file_path.relative_to(base_path)
270 files.append(
271 {
272 "local_path": file_path,
273 "relative_path": rel_path,
274 "storage_path": str(rel_path),
275 },
276 )
277 except ValueError:
278 debug(f"Could not get relative path for {file_path}")
280 return files
283async def _sync_template_files(
284 template_files: list[dict[str, t.Any]],
285 adapters: dict[str, t.Any],
286 strategy: SyncStrategy,
287 storage_bucket: str,
288 result: TemplateSyncResult,
289) -> None:
290 for template_info in template_files:
291 try:
292 file_result = await _sync_single_template(
293 template_info,
294 adapters["storage"],
295 adapters["cache"],
296 strategy,
297 storage_bucket,
298 )
299 _accumulate_sync_results(file_result, result)
301 except Exception as e:
302 result.errors.append(e)
303 debug(f"Error syncing template {template_info['relative_path']}: {e}")
306def _accumulate_sync_results(
307 file_result: dict[str, t.Any],
308 result: TemplateSyncResult,
309) -> None:
310 for key in (
311 "synced",
312 "conflicts",
313 "errors",
314 "skipped",
315 "backed_up",
316 "cache_invalidated",
317 "bytecode_cleared",
318 ):
319 if file_result.get(key):
320 getattr(result, f"{key}_items" if key == "synced" else key).extend(
321 file_result[key],
322 )
325async def _sync_single_template(
326 template_info: dict[str, t.Any],
327 storage: t.Any,
328 cache: t.Any,
329 strategy: SyncStrategy,
330 storage_bucket: str,
331) -> dict[str, t.Any]:
332 local_path = template_info["local_path"]
333 storage_path = template_info["storage_path"]
334 relative_path = template_info["relative_path"]
336 result: dict[str, t.Any] = {
337 "synced": [],
338 "conflicts": [],
339 "errors": [],
340 "skipped": [],
341 "backed_up": [],
342 "cache_invalidated": [],
343 "bytecode_cleared": [],
344 }
346 try:
347 local_info = await get_file_info(Path(local_path))
348 remote_info = await _get_storage_file_info(
349 storage,
350 storage_bucket,
351 storage_path,
352 )
354 sync_needed, reason = should_sync(local_info, remote_info, strategy.direction)
356 if not sync_needed:
357 result["skipped"].append(f"{relative_path} ({reason})")
358 return result
360 debug(f"Syncing template {relative_path}: {reason}")
362 # Handle sync based on direction
363 await _handle_sync_direction(
364 strategy,
365 local_info,
366 remote_info,
367 local_path,
368 storage,
369 storage_bucket,
370 storage_path,
371 result,
372 )
374 # Invalidate cache if needed
375 if result["synced"]:
376 await _invalidate_template_cache(cache, str(relative_path), result)
378 except Exception as e:
379 result["errors"].append(e)
380 debug(f"Error in _sync_single_template for {relative_path}: {e}")
382 return result
385async def _handle_sync_direction(
386 strategy: SyncStrategy,
387 local_info: dict[str, t.Any],
388 remote_info: dict[str, t.Any],
389 local_path: t.Any,
390 storage: t.Any,
391 storage_bucket: str,
392 storage_path: str,
393 result: dict[str, t.Any],
394) -> None:
395 """Handle sync based on direction."""
396 if _should_pull_template(strategy, local_info, remote_info):
397 await _pull_template(
398 local_path,
399 storage,
400 storage_bucket,
401 storage_path,
402 strategy,
403 result,
404 )
405 elif _should_push_template(strategy, local_info, remote_info):
406 await _push_template(
407 local_path,
408 storage,
409 storage_bucket,
410 storage_path,
411 strategy,
412 result,
413 )
414 elif _has_bidirectional_conflict(strategy, local_info, remote_info):
415 await _handle_template_conflict(
416 local_path,
417 storage,
418 storage_bucket,
419 storage_path,
420 local_info,
421 remote_info,
422 strategy,
423 result,
424 )
427def _should_pull_template(
428 strategy: SyncStrategy, local_info: dict[str, t.Any], remote_info: dict[str, t.Any]
429) -> bool:
430 """Check if template should be pulled."""
431 return strategy.direction == SyncDirection.PULL or (
432 strategy.direction == SyncDirection.BIDIRECTIONAL
433 and remote_info["exists"]
434 and (not local_info["exists"] or remote_info["mtime"] > local_info["mtime"])
435 )
438def _should_push_template(
439 strategy: SyncStrategy, local_info: dict[str, t.Any], remote_info: dict[str, t.Any]
440) -> bool:
441 """Check if template should be pushed."""
442 return strategy.direction == SyncDirection.PUSH or (
443 strategy.direction == SyncDirection.BIDIRECTIONAL
444 and local_info["exists"]
445 and (not remote_info["exists"] or local_info["mtime"] > remote_info["mtime"])
446 )
449def _has_bidirectional_conflict(
450 strategy: SyncStrategy, local_info: dict[str, t.Any], remote_info: dict[str, t.Any]
451) -> bool:
452 """Check if there's a bidirectional conflict."""
453 return (
454 strategy.direction == SyncDirection.BIDIRECTIONAL
455 and local_info["exists"]
456 and remote_info["exists"]
457 )
460async def _get_storage_file_info(
461 storage: t.Any,
462 bucket: str,
463 file_path: str,
464) -> dict[str, t.Any]:
465 try:
466 bucket_obj = getattr(storage, bucket)
468 exists = await bucket_obj.exists(file_path)
470 if not exists:
471 return {
472 "exists": False,
473 "size": 0,
474 "mtime": 0,
475 "content_hash": None,
476 }
478 content = await bucket_obj.read(file_path)
479 metadata = await bucket_obj.stat(file_path)
481 import hashlib
483 content_hash = hashlib.blake2b(content).hexdigest()
485 return {
486 "exists": True,
487 "size": len(content),
488 "mtime": metadata.get("mtime", 0),
489 "content_hash": content_hash,
490 "content": content,
491 }
493 except Exception as e:
494 debug(f"Error getting storage file info for {file_path}: {e}")
495 return {
496 "exists": False,
497 "size": 0,
498 "mtime": 0,
499 "content_hash": None,
500 "error": str(e),
501 }
504async def _pull_template(
505 local_path: AsyncPath,
506 storage: t.Any,
507 bucket: str,
508 storage_path: str,
509 strategy: SyncStrategy,
510 result: dict[str, t.Any],
511) -> None:
512 try:
513 bucket_obj = getattr(storage, bucket)
515 if strategy.dry_run:
516 debug(f"DRY RUN: Would pull {storage_path} to {local_path}")
517 result["synced"].append(f"PULL(dry-run): {storage_path}")
518 return
520 if await local_path.exists() and strategy.backup_on_conflict:
521 backup_path = await create_backup(Path(local_path))
522 result["backed_up"].append(str(backup_path))
524 content = await bucket_obj.read(storage_path)
526 await local_path.parent.mkdir(parents=True, exist_ok=True)
528 await local_path.write_bytes(content)
530 result["synced"].append(f"PULL: {storage_path}")
531 debug(f"Pulled template from storage: {storage_path}")
533 except Exception as e:
534 result["errors"].append(e)
535 debug(f"Error pulling template {storage_path}: {e}")
538async def _push_template(
539 local_path: AsyncPath,
540 storage: t.Any,
541 bucket: str,
542 storage_path: str,
543 strategy: SyncStrategy,
544 result: dict[str, t.Any],
545) -> None:
546 try:
547 bucket_obj = getattr(storage, bucket)
549 if strategy.dry_run:
550 debug(f"DRY RUN: Would push {local_path} to {storage_path}")
551 result["synced"].append(f"PUSH(dry-run): {storage_path}")
552 return
554 content = await local_path.read_bytes()
556 await bucket_obj.write(storage_path, content)
558 result["synced"].append(f"PUSH: {storage_path}")
559 debug(f"Pushed template to storage: {storage_path}")
561 except Exception as e:
562 result["errors"].append(e)
563 debug(f"Error pushing template {storage_path}: {e}")
566async def _handle_template_conflict(
567 local_path: AsyncPath,
568 storage: t.Any,
569 bucket: str,
570 storage_path: str,
571 local_info: dict[str, t.Any],
572 remote_info: dict[str, t.Any],
573 strategy: SyncStrategy,
574 result: dict[str, t.Any],
575) -> None:
576 try:
577 if strategy.conflict_strategy == ConflictStrategy.MANUAL:
578 result["conflicts"].append(
579 {
580 "path": storage_path,
581 "local_mtime": local_info["mtime"],
582 "remote_mtime": remote_info["mtime"],
583 "reason": "manual_resolution_required",
584 },
585 )
586 return
588 resolved_content, resolution_reason = await resolve_conflict(
589 Path(local_path),
590 remote_info["content"],
591 local_info["content"],
592 strategy.conflict_strategy,
593 local_info["mtime"],
594 remote_info["mtime"],
595 )
597 if strategy.dry_run:
598 debug(
599 f"DRY RUN: Would resolve conflict for {storage_path}: {resolution_reason}",
600 )
601 result["synced"].append(
602 f"CONFLICT(dry-run): {storage_path} - {resolution_reason}",
603 )
604 return
606 if (
607 strategy.backup_on_conflict
608 or strategy.conflict_strategy == ConflictStrategy.BACKUP_BOTH
609 ):
610 backup_path = await create_backup(Path(local_path), "conflict")
611 result["backed_up"].append(str(backup_path))
613 if resolved_content == remote_info["content"]:
614 await local_path.write_bytes(resolved_content)
615 result["synced"].append(
616 f"CONFLICT->REMOTE: {storage_path} - {resolution_reason}",
617 )
618 else:
619 bucket_obj = getattr(storage, bucket)
620 await bucket_obj.write(storage_path, resolved_content)
621 result["synced"].append(
622 f"CONFLICT->LOCAL: {storage_path} - {resolution_reason}",
623 )
625 debug(f"Resolved template conflict: {storage_path} - {resolution_reason}")
627 except Exception as e:
628 result["errors"].append(e)
629 result["conflicts"].append(
630 {
631 "path": storage_path,
632 "error": str(e),
633 "reason": "resolution_failed",
634 },
635 )
638async def _invalidate_template_cache(
639 cache: t.Any,
640 template_path: str,
641 result: dict[str, t.Any],
642) -> None:
643 if not cache:
644 return
646 try:
647 template_key = f"template:{template_path}"
648 await cache.delete(template_key)
649 result["cache_invalidated"].append(template_key)
651 bytecode_key = f"bccache:{template_path}"
652 await cache.delete(bytecode_key)
653 result["bytecode_cleared"].append(bytecode_key)
655 await cache.delete_pattern(f"template:*:{template_path}")
656 await cache.delete_pattern(f"bccache:*:{template_path}")
658 debug(f"Invalidated cache for template: {template_path}")
660 except Exception as e:
661 debug(f"Error invalidating cache for {template_path}: {e}")
664async def warm_template_cache(
665 template_paths: list[str] | None = None,
666 cache_namespace: str = "templates",
667) -> dict[str, t.Any]:
668 result: dict[str, t.Any] = {
669 "warmed": [],
670 "errors": [],
671 "skipped": [],
672 }
674 if not template_paths:
675 template_paths = [
676 "base.html",
677 "index.html",
678 "layout.html",
679 "404.html",
680 "500.html",
681 ]
683 try:
684 # MIGRATED: Removed ACB import - using Oneiric equivalent
686 cache = await depends.resolve("fastblocks", "cache")
687 storage = await depends.resolve("fastblocks", "storage")
689 if not cache or not storage:
690 result["errors"].append(Exception("Cache or storage not available"))
691 return result
693 for template_path in template_paths:
694 try:
695 cache_key = f"{cache_namespace}:{template_path}"
696 if await cache.exists(cache_key):
697 result["skipped"].append(template_path)
698 continue
700 content = await storage.templates.read(template_path)
702 await cache.set(cache_key, content, ttl=86400)
703 result["warmed"].append(template_path)
705 debug(f"Warmed cache for template: {template_path}")
707 except Exception as e:
708 result["errors"].append(f"{template_path}: {e}")
709 debug(f"Error warming cache for {template_path}: {e}")
711 except Exception as e:
712 result["errors"].append(str(e))
713 debug(f"Error in warm_template_cache: {e}")
715 return result
718async def get_template_sync_status(
719 template_paths: list[AsyncPath] | None = None,
720 storage_bucket: str = "templates",
721) -> dict[str, t.Any]:
722 if template_paths is None:
723 template_paths = [AsyncPath("templates")]
725 status: dict[str, t.Any] = {
726 "total_templates": 0,
727 "in_sync": 0,
728 "out_of_sync": 0,
729 "local_only": 0,
730 "remote_only": 0,
731 "conflicts": 0,
732 "details": [],
733 }
735 try:
736 # MIGRATED: Removed ACB import - using Oneiric equivalent
738 storage = await depends.resolve("fastblocks", "storage")
740 if not storage:
741 status["error"] = "Storage adapter not available"
742 return status
744 template_files = await _discover_template_files_for_status(template_paths)
745 status["total_templates"] = len(template_files)
747 await _process_template_files_for_status(
748 template_files,
749 storage,
750 storage_bucket,
751 status,
752 )
754 except Exception as e:
755 status["error"] = str(e)
756 debug(f"Error getting template sync status: {e}")
758 return status
761async def _discover_template_files_for_status(
762 template_paths: list[AsyncPath],
763) -> list[dict[str, t.Any]]:
764 template_files = []
765 for base_path in template_paths:
766 if await base_path.exists():
767 async for file_path in base_path.rglob("*.html"):
768 if await file_path.is_file():
769 rel_path = file_path.relative_to(base_path)
770 template_files.append(
771 {
772 "local_path": file_path,
773 "storage_path": str(rel_path),
774 },
775 )
776 return template_files
779async def _process_template_files_for_status(
780 template_files: list[dict[str, t.Any]],
781 storage: t.Any,
782 storage_bucket: str,
783 status: dict[str, t.Any],
784) -> None:
785 for template_info in template_files:
786 local_info = await get_file_info(Path(template_info["local_path"]))
787 remote_info = await _get_storage_file_info(
788 storage,
789 storage_bucket,
790 template_info["storage_path"],
791 )
793 file_status = _create_file_status_info(template_info, local_info, remote_info)
794 _update_status_counters(local_info, remote_info, file_status, status)
796 details_list = status["details"]
797 assert isinstance(details_list, list)
798 details_list.append(file_status)
800 _calculate_out_of_sync_total(status)
803# Migration status indicator
804# Note: Partial migration - ACB debug system still in use
805_using_oneiric = True # Oneiric resolver available
806_requires_further_migration = True # ACB debug system needs migration
809def _create_file_status_info(
810 template_info: dict[str, t.Any],
811 local_info: dict[str, t.Any],
812 remote_info: dict[str, t.Any],
813) -> dict[str, t.Any]:
814 return {
815 "path": template_info["storage_path"],
816 "local_exists": local_info["exists"],
817 "remote_exists": remote_info["exists"],
818 }
821def _update_status_counters(
822 local_info: dict[str, t.Any],
823 remote_info: dict[str, t.Any],
824 file_status: dict[str, t.Any],
825 status: dict[str, t.Any],
826) -> None:
827 if local_info["exists"] and remote_info["exists"]:
828 if local_info["content_hash"] == remote_info["content_hash"]:
829 file_status["status"] = "in_sync"
830 status["in_sync"] = status["in_sync"] + 1
831 else:
832 file_status["status"] = "conflict"
833 file_status["local_mtime"] = local_info["mtime"]
834 file_status["remote_mtime"] = remote_info["mtime"]
835 status["conflicts"] = status["conflicts"] + 1
836 elif local_info["exists"]:
837 file_status["status"] = "local_only"
838 status["local_only"] = status["local_only"] + 1
839 elif remote_info["exists"]:
840 file_status["status"] = "remote_only"
841 status["remote_only"] = status["remote_only"] + 1
842 else:
843 file_status["status"] = "missing"
846def _calculate_out_of_sync_total(status: dict[str, t.Any]) -> None:
847 conflicts = status["conflicts"]
848 local_only = status["local_only"]
849 remote_only = status["remote_only"]
850 assert isinstance(conflicts, int)
851 assert isinstance(local_only, int)
852 assert isinstance(remote_only, int)
853 status["out_of_sync"] = conflicts + local_only + remote_only