python-dbsync 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dbsync/cli.py ADDED
@@ -0,0 +1,264 @@
1
+ """dbsync command line."""
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import sys
6
+
7
+ from . import config as cfgmod
8
+ from . import gitops
9
+
10
+ EXIT_OK, EXIT_ERR, EXIT_CONFLICT = 0, 1, 2
11
+
12
+
13
+ def setup_logging():
14
+ os.makedirs(cfgmod.DATA_DIR, exist_ok=True)
15
+ logging.basicConfig(filename=cfgmod.LOG_PATH, level=logging.INFO,
16
+ format="%(asctime)s %(levelname)s %(message)s")
17
+
18
+
19
+ def make_sync(cfg, out=print):
20
+ from .api import DropboxAPI
21
+ from .sync import FolderSync
22
+ api = DropboxAPI(cfg.roots, cfg.secrets_file)
23
+ return FolderSync(cfg.folders[0], api, cfg.roots, cfg.extra_ignore, out=out,
24
+ propagate_local_deletes=cfg.propagate_local_deletes,
25
+ max_deletes=cfg.max_deletes, settle_seconds=cfg.settle_seconds,
26
+ hot_upload_interval=cfg.hot_upload_interval,
27
+ local_wins=cfg.local_wins, push_only=cfg.push_only)
28
+
29
+
30
+ def print_report(rep, title):
31
+ print(f"== {title}")
32
+ for label, items in (("downloaded", rep.downloaded), ("uploaded", rep.uploaded),
33
+ ("pending", rep.pending)):
34
+ for i in items:
35
+ print(f" {label}: {i}")
36
+ for r in rep.remote_deleted:
37
+ print(f" deleted locally (deleted in Dropbox): {r}")
38
+ for a, b in rep.moved_local:
39
+ print(f" renamed locally (renamed in Dropbox): {a} -> {b}")
40
+ for r in rep.deleted_remote:
41
+ print(f" deleted in Dropbox (recoverable there): {r}")
42
+ for a, b in rep.moved_remote:
43
+ print(f" moved in Dropbox: {a} -> {b}")
44
+ for r in rep.local_deleted:
45
+ print(f" local deletion NOT pushed: {r}")
46
+ for r in rep.delete_conflicts:
47
+ print(f" CONFLICT (deleted in Dropbox, changed locally; kept): {r}")
48
+ for a, b in rep.kept_remote:
49
+ print(f" PROTECTED (Dropbox change not applied, local kept): {a}" + (f"; Dropbox copy at {b}" if b else ""))
50
+ for m in rep.messages:
51
+ print(f" note: {m}")
52
+ for r in rep.rev_conflicts:
53
+ print(f" CONFLICT (remote changed, not overwritten): {r}")
54
+ if rep.conflicts:
55
+ print(" MERGE CONFLICT on main (merge state left in place). Files:")
56
+ for r in rep.conflicts:
57
+ print(f" {r}")
58
+ print(" Resolve in the folder, `git add` + `git commit`, then run dbsync push.")
59
+ if rep.error:
60
+ print(f" ERROR: {rep.error}")
61
+ if not (rep.changed_anything or rep.has_conflict or rep.pending or rep.error
62
+ or rep.local_deleted):
63
+ print(" up to date")
64
+
65
+
66
+ def code_for(rep):
67
+ if rep.has_conflict:
68
+ return EXIT_CONFLICT
69
+ return EXIT_ERR if rep.error else EXIT_OK
70
+
71
+
72
+ def init_refusal(path):
73
+ return (f"ERROR: no config at {path}. Nothing was written or synced.\n"
74
+ f"Write that file first (a copy of config/example.toml) with your own folder in place\n"
75
+ f"of every CHANGE-ME:\n\n{cfgmod.FOLDER_HELP}\n"
76
+ f"Then run dbsync init again.")
77
+
78
+
79
+ def cmd_init(args):
80
+ # with no
81
+ # config, refuse; write nothing, sync nothing; say which file to write and what goes in it.
82
+ if not os.path.exists(args.config):
83
+ print(init_refusal(args.config), file=sys.stderr)
84
+ return EXIT_ERR
85
+ print(f"config: {args.config}")
86
+ cfg = cfgmod.load(args.config)
87
+ s = make_sync(cfg)
88
+ s.setup()
89
+ print(f"repo: {s.f.local} (branches main, dropbox); state: {s.f.state_path}")
90
+ rep = s.pull()
91
+ print_report(rep, f"initial pull {s.f.remote} -> {s.f.local}")
92
+ return code_for(rep)
93
+
94
+
95
+ def cmd_pull(args):
96
+ s = make_sync(cfgmod.load(args.config))
97
+ s.setup()
98
+ rep = s.pull(dry_run=args.dry_run)
99
+ print_report(rep, "pull" + (" (dry run)" if args.dry_run else ""))
100
+ return code_for(rep)
101
+
102
+
103
+ def cmd_push(args):
104
+ s = make_sync(cfgmod.load(args.config))
105
+ s.setup()
106
+ rep = s.push(dry_run=args.dry_run, allow_mass_delete=args.allow_mass_delete)
107
+ print_report(rep, "push" + (" (dry run)" if args.dry_run else ""))
108
+ return code_for(rep)
109
+
110
+
111
+ def cmd_auth(args):
112
+ # see auth.py.
113
+ from . import auth
114
+ path = args.secrets
115
+ if not path:
116
+ try:
117
+ path = cfgmod.load(args.config).secrets_file
118
+ except Exception:
119
+ path = "~/.config/secrets/api.env"
120
+ return auth.run(path)
121
+
122
+
123
+ def cmd_status(args):
124
+ cfg = cfgmod.load(args.config)
125
+ s = make_sync(cfg)
126
+ f = s.f
127
+ print(f"folder: {f.id} remote {f.remote} <-> local {f.local}")
128
+ print(f"state: {f.state_path} log: {cfgmod.LOG_PATH}")
129
+ print(f"last sync: {s.state.get_meta('last_sync', 'never')}")
130
+ if gitops.is_repo(f.local):
131
+ print(f"branch: {gitops.current_branch(f.local)}; dropbox merged into main: "
132
+ f"{gitops.is_ancestor(f.local, 'dropbox', 'main')}")
133
+ rep = s.status()
134
+ print_report(rep, "status")
135
+ return code_for(rep)
136
+
137
+
138
+ def cmd_watch(args):
139
+ cfg = cfgmod.load(args.config)
140
+ s = make_sync(cfg)
141
+ s.setup()
142
+ print(f"watching {s.f.remote} (longpoll {cfg.longpoll_timeout}s, fallback {cfg.fallback_poll}s); Ctrl-C to stop")
143
+ sys.stdout.flush()
144
+
145
+ def on_report(rep):
146
+ if rep.downloaded or rep.conflicts or rep.error:
147
+ print_report(rep, "pull")
148
+ sys.stdout.flush()
149
+ s.watch(cfg.longpoll_timeout, cfg.fallback_poll, on_report)
150
+ return EXIT_OK
151
+
152
+
153
+ def cmd_daemon(args):
154
+ from . import plat
155
+ from .daemon import Daemon
156
+ cfg = cfgmod.load(args.config)
157
+ log = logging.getLogger("dbsync")
158
+ s = make_sync(cfg, out=log.info)
159
+ d = Daemon(cfg, s, s.api.longpoll_client(), cfgmod.STATUS_PATH,
160
+ (plat.ControlServer, plat.control_address(cfgmod.DATA_DIR)))
161
+ print(f"dbsync daemon: {s.f.remote} <-> {s.f.local}; status {cfgmod.STATUS_PATH}")
162
+ sys.stdout.flush()
163
+ d.run()
164
+ return EXIT_OK
165
+
166
+
167
+ def cmd_ctl(args):
168
+ import json
169
+ from . import plat
170
+ from .status import effective_state, read_status
171
+ addr = plat.control_address(cfgmod.DATA_DIR)
172
+ if args.action == "status":
173
+ st = read_status(cfgmod.STATUS_PATH)
174
+ state = effective_state(st, plat.pid_alive)
175
+ print(f"state: {state}")
176
+ if st:
177
+ print(json.dumps(st, indent=1, sort_keys=True))
178
+ return EXIT_OK if state != "stopped" else EXIT_ERR
179
+ try:
180
+ r = plat.send_command(addr, args.action)
181
+ except OSError as e:
182
+ print(f"ERROR: daemon not reachable at {addr} ({type(e).__name__}); "
183
+ f"is it running? {plat.service_hint()}", file=sys.stderr)
184
+ return EXIT_ERR
185
+ print("ok" if r.get("ok") else f"ERROR: {r.get('error')}")
186
+ return EXIT_OK if r.get("ok") else EXIT_ERR
187
+
188
+
189
+ def cmd_tray(args):
190
+ try:
191
+ if not sys.platform.startswith("win"): # Windows tray is pystray, no gi
192
+ import gi # noqa: F401
193
+ except ImportError:
194
+ # The venv has no PyGObject: run the tray with the system python (it only needs stdlib +
195
+ # gi; the Dropbox SDK is not used by the tray).
196
+ syspy = "/usr/bin/python3"
197
+ in_venv = sys.prefix != sys.base_prefix
198
+ if not in_venv or not os.path.exists(syspy):
199
+ print("ERROR: PyGObject missing: sudo apt install python3-gi "
200
+ "gir1.2-ayatanaappindicator3-0.1", file=sys.stderr)
201
+ return EXIT_ERR
202
+ env = dict(os.environ)
203
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
204
+ env["PYTHONPATH"] = root + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
205
+ os.execve(syspy, [syspy, "-m", "dbsync", "--config", args.config, "tray"], env)
206
+ from . import plat
207
+ if plat.single_instance(os.path.join(cfgmod.DATA_DIR, "tray.lock")) is None:
208
+ print("dbsync tray is already running")
209
+ return EXIT_OK
210
+ cfg = cfgmod.load(args.config)
211
+ return plat.run_tray(cfgmod.STATUS_PATH, plat.control_address(cfgmod.DATA_DIR),
212
+ cfg.folders[0].local, cfgmod.LOG_PATH)
213
+
214
+
215
+ def main(argv=None):
216
+ # Under pythonw.exe (Windows, no console: the logon tasks) stdout and stderr are None and
217
+ # the first print or flush crashed the daemon.
218
+ if sys.stdout is None:
219
+ sys.stdout = open(os.devnull, "w")
220
+ if sys.stderr is None:
221
+ sys.stderr = open(os.devnull, "w")
222
+ p = argparse.ArgumentParser(prog="dbsync", description="Selective Dropbox folder sync")
223
+ p.add_argument("--config", default=cfgmod.CONFIG_PATH)
224
+ sub = p.add_subparsers(dest="cmd", required=True)
225
+ sub.add_parser("init").set_defaults(fn=cmd_init)
226
+ sp = sub.add_parser("auth", help="get a Dropbox refresh token into the secrets file (never printed)")
227
+ sp.add_argument("--secrets", help="the .env file to write (default: secrets_file from the config, "
228
+ "or ~/.config/secrets/api.env)")
229
+ sp.set_defaults(fn=cmd_auth)
230
+ for name, fn in (("pull", cmd_pull), ("push", cmd_push)):
231
+ sp = sub.add_parser(name)
232
+ sp.add_argument("--dry-run", action="store_true")
233
+ if name == "push":
234
+ sp.add_argument("--allow-mass-delete", action="store_true",
235
+ help="allow more than max_deletes remote deletions in this push")
236
+ sp.set_defaults(fn=fn)
237
+ sub.add_parser("status").set_defaults(fn=cmd_status)
238
+ sub.add_parser("watch", help="foreground longpoll loop (pull only)").set_defaults(fn=cmd_watch)
239
+ sub.add_parser("daemon", help="background service: watch + auto-push + status/control"
240
+ ).set_defaults(fn=cmd_daemon)
241
+ sub.add_parser("tray", help="Linux tray icon for the daemon").set_defaults(fn=cmd_tray)
242
+ sp = sub.add_parser("ctl", help="talk to the running daemon")
243
+ sp.add_argument("action", choices=["status", "sync-now", "pause", "resume", "stop"])
244
+ sp.set_defaults(fn=cmd_ctl)
245
+ args = p.parse_args(argv)
246
+ setup_logging()
247
+ try:
248
+ return args.fn(args)
249
+ except KeyboardInterrupt:
250
+ return EXIT_OK
251
+ except Exception as e:
252
+ logging.getLogger("dbsync").exception("command failed")
253
+ if "missing_scope" in repr(e):
254
+ print("ERROR: the Dropbox app token lacks a required scope "
255
+ f"({getattr(getattr(e, 'error', None), 'get_missing_scope', lambda: None)() or e}). "
256
+ "Enable it in the Dropbox App Console (Permissions) and create a new refresh token.",
257
+ file=sys.stderr)
258
+ return EXIT_ERR
259
+ print(f"ERROR: {type(e).__name__}: {e}", file=sys.stderr)
260
+ return EXIT_ERR
261
+
262
+
263
+ if __name__ == "__main__":
264
+ sys.exit(main())
dbsync/config.py ADDED
@@ -0,0 +1,135 @@
1
+ """Config loading (<plat.CONFIG_DIR>/config.toml).
2
+
3
+ default paths come from
4
+ plat.CONFIG_DIR / plat.DATA_DIR; the hardcoded ALLOWED_ROOTS list is gone: the allowed roots are
5
+ the remote paths of the configured [[folder]] entries, each an explicit absolute Dropbox path
6
+ (never "/" or empty; validate_root also refuses a single top-level folder).
7
+
8
+ no
9
+ built-in folder anywhere; `init` with no config refuses and writes nothing; the example config
10
+ (EXAMPLE_CONFIG = config/example.toml) has a CHANGE-ME [[folder]] that load() refuses.
11
+ """
12
+ import os
13
+ import tomllib
14
+ from dataclasses import dataclass, field
15
+
16
+ from . import plat
17
+ from .api import OutsideRootError, validate_root
18
+
19
+ CONFIG_PATH = os.path.join(plat.CONFIG_DIR, "config.toml")
20
+ DATA_DIR = plat.DATA_DIR
21
+ LOG_PATH = os.path.join(DATA_DIR, "dbsync.log")
22
+
23
+ STATUS_PATH = os.path.join(DATA_DIR, "status.json")
24
+
25
+ PLACEHOLDER = "CHANGE-ME" # in the example [[folder]]; a config that still has it is refused
26
+
27
+ EXAMPLE_CONFIG = """# dbsync config (exactly one folder for now): copy to the config path, then replace every
28
+ # CHANGE-ME in [[folder]] with your own folder. dbsync refuses to run until you do.
29
+ [settings]
30
+ secrets_file = "~/.config/secrets/api.env" # .env with DROPBOX_APP_KEY, DROPBOX_APP_SECRET, DROPBOX_REFRESH_TOKEN
31
+ longpoll_timeout = 240 # seconds (30-480)
32
+ fallback_poll = 30 # seconds, used when longpoll fails / retry delay when offline
33
+ extra_ignore = [] # extra patterns; ".env" files are never ignored
34
+ propagate_local_deletes = true # local delete/rename -> rev-checked remote delete/move
35
+ max_deletes = 20 # more local deletions than this in one sync -> refused (error)
36
+ auto_push = true # daemon uploads local changes automatically
37
+ local_scan = 10 # seconds between local change scans in the daemon
38
+ settle_seconds = 30 # file modified < this many s ago is "hot" (still being written)
39
+ hot_upload_interval = 600 # hot files upload at most once per this many s (e.g. logs)
40
+ ntfy_alerts = false # phone push on conflict/error, rate-limited (needs ntfy_script)
41
+ ntfy_script = "" # e.g. "~/bin/notify.sh"
42
+ local_wins = ["logs/**"] # after a push, conflicts in these paths keep the local side
43
+ push_only = false # true: one way, local -> Dropbox; Dropbox-side edits/deletes never reach the local folder
44
+
45
+ [[folder]]
46
+ id = "CHANGE-ME" # short name: state file, lock and log use it
47
+ remote = "/CHANGE-ME/your-folder" # explicit Dropbox path, at least two levels deep; must exist
48
+ local = "~/CHANGE-ME/your-folder" # outside the official Dropbox client's folder
49
+ protect = [] # e.g. ["CLAUDE.md", "NOTES.md"]: a Dropbox-only change to these is kept aside, not applied
50
+ """
51
+
52
+ FOLDER_HELP = EXAMPLE_CONFIG[EXAMPLE_CONFIG.index("\n[[folder]]") + 1:]
53
+
54
+ @dataclass
55
+ class Folder:
56
+ id: str
57
+ remote: str
58
+ local: str
59
+ # files a change made only in Dropbox may not
60
+ # replace or remove (an agent's start-up files). Globs, relative to the folder. Empty = off.
61
+ protect: list = field(default_factory=list)
62
+ state_path: str = ""
63
+ worktree: str = ""
64
+ lock_path: str = ""
65
+
66
+ def __post_init__(self):
67
+ self.local = os.path.expanduser(self.local)
68
+ raw = (self.remote or "").strip()
69
+ if not raw.startswith("/") or raw.strip("/") == "":
70
+ raise ValueError(f"folder {self.id!r}: remote must be an explicit absolute Dropbox path "
71
+ f"(not empty, not '/'): {self.remote!r}")
72
+ self.remote = "/" + raw.strip("/")
73
+ try:
74
+ validate_root(self.remote)
75
+ except OutsideRootError as e:
76
+ raise ValueError(f"folder {self.id!r}: {e}") from None
77
+ self.state_path = os.path.join(DATA_DIR, f"{self.id}.db")
78
+ self.worktree = os.path.join(DATA_DIR, f"{self.id}.dropbox-worktree")
79
+ self.lock_path = os.path.join(DATA_DIR, f"{self.id}.lock")
80
+
81
+
82
+ @dataclass
83
+ class Config:
84
+ folders: list
85
+ secrets_file: str = "~/.config/secrets/api.env"
86
+ longpoll_timeout: int = 240
87
+ fallback_poll: int = 30
88
+ extra_ignore: list = field(default_factory=list)
89
+ propagate_local_deletes: bool = True
90
+ max_deletes: int = 20
91
+ auto_push: bool = True
92
+ local_scan: int = 10
93
+ settle_seconds: int = 30
94
+ hot_upload_interval: int = 600
95
+ ntfy_alerts: bool = True
96
+ ntfy_script: str = ""
97
+ local_wins: list = field(default_factory=lambda: ["logs/**"])
98
+ # push_only: local -> Dropbox only.
99
+ push_only: bool = False
100
+
101
+ @property
102
+ def roots(self):
103
+ return [f.remote for f in self.folders]
104
+
105
+
106
+ def load(path=CONFIG_PATH, strict=True):
107
+ with open(path, "rb") as f:
108
+ raw = tomllib.load(f)
109
+ s = raw.get("settings", {})
110
+ for d in raw.get("folder", []):
111
+ if any(PLACEHOLDER in str(d.get(k, "")) for k in ("id", "remote", "local")):
112
+ raise ValueError(f"config {path} still has the example [[folder]] ({PLACEHOLDER}): "
113
+ f"set its id, remote and local first")
114
+ folders = [Folder(id=d["id"], remote=d.get("remote", ""), local=d["local"],
115
+ protect=list(d.get("protect", [])))
116
+ for d in raw.get("folder", [])]
117
+ if not folders:
118
+ raise ValueError("config has no [[folder]] entries")
119
+ if strict:
120
+ if len(folders) != 1:
121
+ raise ValueError("this build supports exactly one folder")
122
+ timeout = max(30, min(480, int(s.get("longpoll_timeout", 240))))
123
+ return Config(folders=folders, secrets_file=s.get("secrets_file", "~/.config/secrets/api.env"),
124
+ longpoll_timeout=timeout, fallback_poll=int(s.get("fallback_poll", 30)),
125
+ extra_ignore=list(s.get("extra_ignore", [])),
126
+ propagate_local_deletes=bool(s.get("propagate_local_deletes", True)),
127
+ max_deletes=max(0, int(s.get("max_deletes", 20))),
128
+ auto_push=bool(s.get("auto_push", True)),
129
+ local_scan=max(2, int(s.get("local_scan", 10))),
130
+ settle_seconds=max(0, int(s.get("settle_seconds", 30))),
131
+ hot_upload_interval=max(0, int(s.get("hot_upload_interval", 600))),
132
+ ntfy_alerts=bool(s.get("ntfy_alerts", True)),
133
+ ntfy_script=str(s.get("ntfy_script", "")),
134
+ local_wins=list(s.get("local_wins", ["logs/**"])),
135
+ push_only=bool(s.get("push_only", False)))
dbsync/daemon.py ADDED
@@ -0,0 +1,260 @@
1
+ """`dbsync daemon`: longpoll watch loop + local change scan + status file + control channel.
2
+
3
+ Platform-neutral; OS specifics (control channel, locks) come from dbsync.plat.
4
+
5
+ Threads: main (does ALL syncing and SQLite access), longpoll (only calls api.longpoll on
6
+ its own HTTP client), control server (only enqueues commands / returns a status snapshot).
7
+ """
8
+ import collections
9
+ import logging
10
+ import os
11
+ import queue
12
+ import signal
13
+ import threading
14
+ import time
15
+
16
+ from . import gitops
17
+ from .alerts import PhoneAlerter
18
+ from .api import is_network_error
19
+ from .status import STOPPED, write_status
20
+
21
+ log = logging.getLogger("dbsync")
22
+
23
+ COMMANDS = ("sync-now", "pause", "resume", "status", "stop")
24
+
25
+
26
+ def summarize(rep):
27
+ d = {k: len(getattr(rep, k)) for k in
28
+ ("downloaded", "uploaded", "remote_deleted", "moved_local", "deleted_remote",
29
+ "moved_remote", "local_deleted", "kept_remote")}
30
+ return {k: v for k, v in d.items() if v}
31
+
32
+
33
+ class Daemon:
34
+ def __init__(self, cfg, sync, longpoll_api, status_path, control, alerter=None):
35
+ """control: (ControlServer class, address)"""
36
+ self.alerter = alerter or PhoneAlerter(cfg.ntfy_script, cfg.ntfy_alerts)
37
+ self.cfg = cfg
38
+ self.sync = sync
39
+ self.lp_api = longpoll_api
40
+ self.status_path = status_path
41
+ self.server_cls, self.control_addr = control
42
+ self.q = queue.Queue()
43
+ self.paused = False
44
+ self.state = "syncing"
45
+ self.message = "starting"
46
+ self.conflicts = []
47
+ self.last_result = {}
48
+ self.last_attempt = 0.0
49
+ self.last_ok = None
50
+ self.history = collections.deque(maxlen=20)
51
+ self.started = time.strftime("%Y-%m-%d %H:%M:%S")
52
+ self._cursor = None
53
+ self._cursor_changed = threading.Event()
54
+ self._stopping = threading.Event()
55
+ self._lock = threading.Lock()
56
+ self.kept_remote = []
57
+ self._noise = 0 # consecutive longpoll wake-ups with nothing for us
58
+
59
+ # ---------- status ----------
60
+ def snapshot(self):
61
+ with self._lock:
62
+ return {
63
+ "state": self.state, "message": self.message, "paused": self.paused,
64
+ "pid": os.getpid(), "started": self.started,
65
+ "updated": time.strftime("%Y-%m-%d %H:%M:%S"),
66
+ "last_sync": self.last_ok, "last_result": self.last_result,
67
+ "conflicts": self.conflicts,
68
+ "kept_remote": self.kept_remote,
69
+ "folder": {"id": self.sync.f.id, "remote": self.sync.f.remote,
70
+ "local": self.sync.f.local},
71
+ "auto_push": self.cfg.auto_push,
72
+ "propagate_local_deletes": self.cfg.propagate_local_deletes,
73
+ "history": list(self.history),
74
+ }
75
+
76
+ def _set(self, state, message=""):
77
+ with self._lock:
78
+ if state != self.state:
79
+ log.info("state %s -> %s %s", self.state, state, message)
80
+ self.history.append([time.strftime("%H:%M:%S"), state])
81
+ self.state, self.message = state, message
82
+ write_status(self.status_path, self.snapshot())
83
+ if state != "syncing":
84
+ try:
85
+ self.alerter.observe(state, message, self.sync.f.remote)
86
+ except Exception as e:
87
+ log.warning("alert failed: %s", type(e).__name__)
88
+
89
+ # ---------- control ----------
90
+ def handle_command(self, cmd): # runs on the control thread
91
+ if cmd == "status":
92
+ return {"ok": True, "status": self.snapshot()}
93
+ if cmd in COMMANDS:
94
+ self.q.put(("cmd", cmd))
95
+ return {"ok": True, "queued": cmd}
96
+ return {"ok": False, "error": f"unknown command {cmd!r}; use one of {', '.join(COMMANDS)}"}
97
+
98
+ # ---------- longpoll thread ----------
99
+ def _publish_cursor(self):
100
+ cur = self.sync.state.cursor
101
+ if cur != self._cursor:
102
+ self._cursor = cur
103
+ self._cursor_changed.set()
104
+
105
+ def _longpoll_loop(self):
106
+ while not self._stopping.is_set():
107
+ cur = self._cursor
108
+ if self.paused or not cur:
109
+ self._cursor_changed.wait(5)
110
+ self._cursor_changed.clear()
111
+ continue
112
+ try:
113
+ changes, backoff = self.lp_api.longpoll(cur, self.cfg.longpoll_timeout)
114
+ except Exception as e:
115
+ log.warning("longpoll failed (%s); retry in %ss", type(e).__name__, self.cfg.fallback_poll)
116
+ self.q.put(("lp_error", None))
117
+ self._stopping.wait(self.cfg.fallback_poll)
118
+ continue
119
+ if changes:
120
+ self._cursor_changed.clear()
121
+ self.q.put(("remote", None))
122
+ self._cursor_changed.wait(120) # until the main thread has pulled
123
+ if self._noise: # noisy account: back off (max fallback_poll)
124
+ self._stopping.wait(min(self.cfg.fallback_poll, 2 ** min(self._noise, 8)))
125
+ if backoff:
126
+ self._stopping.wait(backoff)
127
+
128
+ # ---------- syncing (main thread) ----------
129
+ def _do_sync(self, why, push=None):
130
+ push = self.cfg.auto_push if push is None else push
131
+ self.last_attempt = time.time()
132
+ self._set("syncing", why)
133
+ try:
134
+ rep = self.sync.push() if push else self.sync.pull()
135
+ except Exception as e:
136
+ if is_network_error(e):
137
+ log.warning("offline: %s", type(e).__name__)
138
+ self._set("offline", f"no connection ({type(e).__name__}); retrying every "
139
+ f"{self.cfg.fallback_poll}s")
140
+ else:
141
+ log.exception("sync failed")
142
+ self._set("error", f"{type(e).__name__}: {str(e)[:200]}")
143
+ return
144
+ finally:
145
+ try:
146
+ self._publish_cursor()
147
+ except Exception:
148
+ pass
149
+ with self._lock:
150
+ self.last_result = summarize(rep)
151
+ self.conflicts = sorted(set(rep.conflicts + rep.rev_conflicts + rep.delete_conflicts))
152
+ if rep.kept_remote: # protected files, last ones kept
153
+ self.kept_remote = [{"file": a, "copy": b, "at": time.strftime("%Y-%m-%d %H:%M:%S")}
154
+ for a, b in rep.kept_remote]
155
+ if rep.has_conflict:
156
+ self._set("conflict", f"{len(self.conflicts)} conflicted file(s); resolve in "
157
+ f"{self.sync.f.local} (git add + git commit)")
158
+ elif rep.error:
159
+ self._set("error", rep.error)
160
+ else:
161
+ self.last_ok = time.strftime("%Y-%m-%d %H:%M:%S")
162
+ msg = ", ".join(f"{k.replace('_', ' ')} {v}" for k, v in self.last_result.items())
163
+ self._set("paused" if self.paused else "synced", msg or "up to date")
164
+
165
+ def _quiet(self):
166
+ try:
167
+ return self.sync.advance_if_quiet()
168
+ except Exception as e: # let the real sync path classify the error
169
+ log.info("quiet check failed (%s)", type(e).__name__)
170
+ return False
171
+
172
+ def _local_signature(self):
173
+ """Stable token for pending local work. Deferred hot files are left out; due hot files
174
+ count by name only (their hash changes every scan)."""
175
+ changed, deleted = self.sync.local_changes()
176
+ now = time.time()
177
+ items = []
178
+ for rel, ap, h, _ in changed:
179
+ if self.sync.is_deferred(rel, ap, now):
180
+ continue
181
+ items.append((rel, "hot" if self.sync.is_hot(ap, now) else h))
182
+ return tuple(sorted(items)) + tuple(("-", d) for d in deleted)
183
+
184
+ def _tick(self, last_sig):
185
+ """Periodic work. Returns the new local-change signature."""
186
+ if self.paused:
187
+ return None
188
+ now = time.time()
189
+ if self.state in ("error", "offline"):
190
+ if now - self.last_attempt >= self.cfg.fallback_poll:
191
+ self._do_sync("retry")
192
+ return None
193
+ if self.state == "conflict":
194
+ if not gitops.merge_in_progress(self.sync.f.local) and \
195
+ now - self.last_attempt >= self.cfg.fallback_poll:
196
+ self._do_sync("re-check after conflict")
197
+ return None
198
+ if not self.cfg.auto_push:
199
+ return None
200
+ sig = self._local_signature()
201
+ if sig and sig == last_sig: # unchanged for one scan interval -> settled
202
+ self._do_sync(f"local changes ({len(sig)})", push=True)
203
+ return None
204
+ return sig or None
205
+
206
+ def _stop_from_signal(self, *_):
207
+ self._stopping.set()
208
+ threading.Thread(target=self.q.put, args=(("cmd", "stop"),), daemon=True).start()
209
+
210
+ def run(self):
211
+ if threading.current_thread() is threading.main_thread():
212
+ signal.signal(signal.SIGTERM, self._stop_from_signal)
213
+ signal.signal(signal.SIGINT, self._stop_from_signal)
214
+ server = self.server_cls(self.control_addr, self.handle_command)
215
+ server.start()
216
+ log.info("daemon started pid=%s control=%s", os.getpid(), self.control_addr)
217
+ try:
218
+ self.sync.setup()
219
+ threading.Thread(target=self._longpoll_loop, name="longpoll", daemon=True).start()
220
+ self._do_sync("startup")
221
+ last_sig = None
222
+ while True:
223
+ try:
224
+ kind, arg = self.q.get(timeout=self.cfg.local_scan)
225
+ except queue.Empty:
226
+ kind, arg = "tick", None
227
+ if kind == "cmd":
228
+ if arg == "stop":
229
+ break
230
+ if arg == "pause":
231
+ self.paused = True
232
+ self._set("paused", "paused by user")
233
+ elif arg == "resume":
234
+ self.paused = False
235
+ self._cursor_changed.set()
236
+ self._do_sync("resumed")
237
+ elif arg == "sync-now":
238
+ self._do_sync("sync now", push=True)
239
+ last_sig = None
240
+ elif kind in ("remote", "lp_error"):
241
+ if self.paused:
242
+ self._cursor_changed.set()
243
+ elif kind == "remote" and self.state in ("synced", "paused") and self._quiet():
244
+ self._noise += 1
245
+ self._publish_cursor()
246
+ else:
247
+ self._noise = 0
248
+ self._do_sync("remote changes" if kind == "remote" else "longpoll retry")
249
+ else:
250
+ try:
251
+ last_sig = self._tick(last_sig)
252
+ except Exception as e:
253
+ log.exception("tick failed")
254
+ self._set("error", f"{type(e).__name__}: {str(e)[:200]}")
255
+ finally:
256
+ self._stopping.set()
257
+ self._cursor_changed.set()
258
+ server.close()
259
+ self._set(STOPPED, "daemon stopped")
260
+ log.info("daemon stopped")