Fix watcher sync loop when auto-watch is enabled

This commit is contained in:
2026-01-15 16:26:52 +09:00
parent c00d6100c2
commit 96c853125c
3 changed files with 72 additions and 7 deletions
+33
View File
@@ -4,6 +4,7 @@ import json
import os
import hashlib
import re
import time
from datetime import datetime
from app.utils.logger import logger
from app.utils.playlist_merge import sync_all_playlists, SyncMode
@@ -21,6 +22,23 @@ class SyncManager:
self._last_error = None
self._listeners = [] # List of asyncio.Queue
self._loop = None
# Suppress watcher events briefly after we write/delete local playlists.
# This prevents feedback loops where a sync triggers another sync.
self._watcher_suppress_until = 0.0
# Tunable defaults (seconds). Keep short to avoid missing real user edits.
self._watcher_suppress_after_write_seconds = 2.5
self._watcher_suppress_after_sync_seconds = 2.5
def suppress_watcher_events(self, seconds: float):
now = time.monotonic()
with self._lock:
self._watcher_suppress_until = max(self._watcher_suppress_until, now + float(seconds))
@property
def is_watcher_suppressed(self) -> bool:
with self._lock:
return time.monotonic() < self._watcher_suppress_until
def set_event_loop(self, loop):
self._loop = loop
@@ -78,6 +96,11 @@ class SyncManager:
self._is_syncing = True
self._last_status = "syncing"
self._last_error = None
# Preemptively suppress watcher in case the poller notices changes right after.
self._watcher_suppress_until = max(
self._watcher_suppress_until,
time.monotonic() + self._watcher_suppress_after_sync_seconds,
)
self._notify_listeners()
logger.info(f"Starting sync (Source: {trigger_source})...")
@@ -144,6 +167,7 @@ class SyncManager:
dest_path = self._safe_local_playlist_path(server_config.local_path, playlist_name, ".m3u8")
# Ensure directory exists
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
self.suppress_watcher_events(self._watcher_suppress_after_write_seconds)
write_local_playlist(dest_path, tracks)
# 2. Write Remote (Plex)
@@ -159,9 +183,11 @@ class SyncManager:
elif action == "deleted":
# Delete Local
dest_path = self._safe_local_playlist_path(server_config.local_path, playlist_name, ".m3u8")
self.suppress_watcher_events(self._watcher_suppress_after_write_seconds)
delete_local_playlist(dest_path)
# Also check for .m3u
dest_path_m3u = self._safe_local_playlist_path(server_config.local_path, playlist_name, ".m3u")
self.suppress_watcher_events(self._watcher_suppress_after_write_seconds)
delete_local_playlist(dest_path_m3u)
# Delete Remote
@@ -218,7 +244,14 @@ class SyncManager:
return candidate
def _complete_sync(self, status, error=None):
now = time.monotonic()
with self._lock:
# Keep watcher suppression a bit after sync finishes, since PollingObserver
# may detect file changes on the next polling tick.
self._watcher_suppress_until = max(
self._watcher_suppress_until,
now + self._watcher_suppress_after_sync_seconds,
)
self._last_status = status
self._last_error = error
self._last_sync_time = datetime.now()