opendrone-bin-sync-agent 0.1.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.
@@ -0,0 +1 @@
1
+ """Standalone OpenDrone DataFlash synchronization agent."""
@@ -0,0 +1,3 @@
1
+ from opendrone_bin_sync_agent.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,188 @@
1
+ """Durable polling agent for stable DataFlash log files."""
2
+
3
+ import logging
4
+ from pathlib import Path
5
+
6
+ from opendrone_bin_sync_agent.backend import (
7
+ BackendRejected,
8
+ BackendUnavailable,
9
+ OpenDroneClient,
10
+ )
11
+ from opendrone_bin_sync_agent.config import AgentConfig
12
+ from opendrone_bin_sync_agent.files import (
13
+ FileIdentity,
14
+ FolderScanner,
15
+ SourceChangedError,
16
+ StabilityTracker,
17
+ create_snapshot,
18
+ sha256_file,
19
+ )
20
+ from opendrone_bin_sync_agent.state import AgentStateStore
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class SyncAgent:
26
+ def __init__(
27
+ self,
28
+ config: AgentConfig,
29
+ *,
30
+ backend_client: OpenDroneClient | None = None,
31
+ state: AgentStateStore | None = None,
32
+ ) -> None:
33
+ self.config = config
34
+ self.backend = backend_client or OpenDroneClient(config.api_url)
35
+ self.state = state or AgentStateStore(config.state_db_path)
36
+ self.scanner = FolderScanner(config.watch_dir)
37
+ self.stability = StabilityTracker(config.stability_seconds)
38
+ self.state.recover_interrupted()
39
+
40
+ def scan_once(self, now: float | None = None) -> None:
41
+ try:
42
+ candidates = self.scanner.discover()
43
+ except OSError as exc:
44
+ logger.warning("Cannot scan watched folder %s: %s", self.config.watch_dir, exc)
45
+ return
46
+ for path in candidates:
47
+ try:
48
+ stable_identity = self.stability.stable_identity(path, now=now)
49
+ if stable_identity is None:
50
+ continue
51
+ self._sync(path, stable_identity)
52
+ except OSError as exc:
53
+ self.stability.invalidate(path)
54
+ logger.warning("Cannot process watched file %s: %s", path, exc)
55
+
56
+ def _sync(self, source_path: Path, expected_identity: FileIdentity) -> None:
57
+ try:
58
+ snapshot = create_snapshot(source_path)
59
+ except (FileNotFoundError, SourceChangedError):
60
+ self.stability.invalidate(source_path)
61
+ return
62
+
63
+ try:
64
+ if snapshot.source_identity != expected_identity:
65
+ self.stability.invalidate(source_path)
66
+ return
67
+
68
+ existing = self.state.get_version(source_path, snapshot.sha256)
69
+ if existing is not None and existing["state"] in {"synced", "failed"}:
70
+ return
71
+
72
+ self.state.save_version(
73
+ path=source_path,
74
+ sha256=snapshot.sha256,
75
+ size_bytes=snapshot.size_bytes,
76
+ mtime_ns=snapshot.mtime_ns,
77
+ state="uploading",
78
+ flight_id=existing["flight_id"] if existing else None,
79
+ last_error=None,
80
+ )
81
+
82
+ try:
83
+ if existing and existing["flight_id"]:
84
+ response = self.backend.get_flight(existing["flight_id"])
85
+ else:
86
+ response = self.backend.upload_file(snapshot.snapshot_path, source_path.name)
87
+ except BackendUnavailable as exc:
88
+ self._save_pending(snapshot, str(exc))
89
+ return
90
+ except BackendRejected as exc:
91
+ self._save_failed(snapshot, str(exc))
92
+ return
93
+
94
+ status = response.get("status")
95
+ flight_id = response.get("id")
96
+ if not flight_id:
97
+ self._save_pending(snapshot, "OpenDrone API response did not include a flight id")
98
+ return
99
+
100
+ if response.get("sha256") != snapshot.sha256:
101
+ self._save_failed(
102
+ snapshot,
103
+ "OpenDrone API response checksum did not match the uploaded file",
104
+ flight_id=flight_id,
105
+ )
106
+ return
107
+
108
+ if not self._source_matches_snapshot(snapshot):
109
+ self.state.save_version(
110
+ path=source_path,
111
+ sha256=snapshot.sha256,
112
+ size_bytes=snapshot.size_bytes,
113
+ mtime_ns=snapshot.mtime_ns,
114
+ state="pending",
115
+ flight_id=flight_id,
116
+ last_error="Watched file changed during upload; checking its current version",
117
+ )
118
+ self.stability.invalidate(source_path)
119
+ return
120
+
121
+ if status == "ready":
122
+ self.state.save_version(
123
+ path=source_path,
124
+ sha256=snapshot.sha256,
125
+ size_bytes=snapshot.size_bytes,
126
+ mtime_ns=snapshot.mtime_ns,
127
+ state="synced",
128
+ flight_id=flight_id,
129
+ )
130
+ logger.info("Vuelo sincronizado: %s (id %s)", source_path.name, flight_id)
131
+ elif status == "failed":
132
+ self._save_failed(
133
+ snapshot,
134
+ str(response.get("error_summary") or "OpenDrone could not process the log"),
135
+ flight_id=flight_id,
136
+ )
137
+ else:
138
+ logger.info("Vuelo recibido; procesamiento pendiente: %s", source_path.name)
139
+ self.state.save_version(
140
+ path=source_path,
141
+ sha256=snapshot.sha256,
142
+ size_bytes=snapshot.size_bytes,
143
+ mtime_ns=snapshot.mtime_ns,
144
+ state="processing",
145
+ flight_id=flight_id,
146
+ )
147
+ finally:
148
+ snapshot.cleanup()
149
+
150
+ def _source_matches_snapshot(self, snapshot) -> bool:
151
+ try:
152
+ return sha256_file(
153
+ snapshot.source_path, expected_identity=snapshot.source_identity
154
+ ) == snapshot.sha256
155
+ except (FileNotFoundError, OSError, SourceChangedError):
156
+ return False
157
+
158
+ def _save_pending(self, snapshot, error: str) -> None:
159
+ logger.warning(
160
+ "Sincronización pendiente para %s; se reintentará: %s",
161
+ snapshot.source_path.name,
162
+ error,
163
+ )
164
+ self.state.save_version(
165
+ path=snapshot.source_path,
166
+ sha256=snapshot.sha256,
167
+ size_bytes=snapshot.size_bytes,
168
+ mtime_ns=snapshot.mtime_ns,
169
+ state="pending",
170
+ flight_id=None,
171
+ last_error=error,
172
+ )
173
+
174
+ def _save_failed(self, snapshot, error: str, flight_id: str | None = None) -> None:
175
+ logger.error("Error al sincronizar %s: %s", snapshot.source_path.name, error)
176
+ self.state.save_version(
177
+ path=snapshot.source_path,
178
+ sha256=snapshot.sha256,
179
+ size_bytes=snapshot.size_bytes,
180
+ mtime_ns=snapshot.mtime_ns,
181
+ state="failed",
182
+ flight_id=flight_id,
183
+ last_error=error,
184
+ )
185
+
186
+ def close(self) -> None:
187
+ self.backend.close()
188
+ self.state.close()
@@ -0,0 +1,71 @@
1
+ """HTTP client for the existing OpenDrone flight API."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+
9
+ class BackendUnavailable(RuntimeError):
10
+ """A transient backend/network error that should leave the version pending."""
11
+
12
+
13
+ class BackendRejected(RuntimeError):
14
+ """A terminal client error returned by the backend."""
15
+
16
+
17
+ class OpenDroneClient:
18
+ def __init__(
19
+ self,
20
+ api_url: str,
21
+ *,
22
+ transport: httpx.BaseTransport | None = None,
23
+ timeout_seconds: float = 30,
24
+ ) -> None:
25
+ self._client = httpx.Client(
26
+ base_url=api_url.rstrip("/"),
27
+ transport=transport,
28
+ timeout=timeout_seconds,
29
+ )
30
+
31
+ def upload_file(self, path: Path, filename: str) -> dict[str, Any]:
32
+ try:
33
+ with path.open("rb") as source:
34
+ response = self._client.post(
35
+ "/api/v1/flights",
36
+ data={"origin": "agent"},
37
+ files={"file": (filename, source, "application/octet-stream")},
38
+ )
39
+ except httpx.RequestError as exc:
40
+ raise BackendUnavailable("Could not reach OpenDrone API") from exc
41
+ return self._read_response(response)
42
+
43
+ def get_flight(self, flight_id: str) -> dict[str, Any]:
44
+ try:
45
+ response = self._client.get(f"/api/v1/flights/{flight_id}")
46
+ except httpx.RequestError as exc:
47
+ raise BackendUnavailable("Could not reach OpenDrone API") from exc
48
+ return self._read_response(response)
49
+
50
+ @staticmethod
51
+ def _read_response(response: httpx.Response) -> dict[str, Any]:
52
+ if response.status_code >= 500 or response.status_code in {408, 429}:
53
+ raise BackendUnavailable(f"OpenDrone API returned HTTP {response.status_code}")
54
+ try:
55
+ body = response.json()
56
+ except ValueError as exc:
57
+ if response.is_error:
58
+ message = f"OpenDrone API returned HTTP {response.status_code}"
59
+ raise BackendRejected(message) from exc
60
+ raise BackendUnavailable("OpenDrone API returned an invalid response") from exc
61
+ if response.is_error:
62
+ detail = body.get("detail") if isinstance(body, dict) else None
63
+ message = detail.get("message") if isinstance(detail, dict) else detail
64
+ safe_message = message or f"OpenDrone API returned HTTP {response.status_code}"
65
+ raise BackendRejected(str(safe_message))
66
+ if not isinstance(body, dict):
67
+ raise BackendUnavailable("OpenDrone API returned an invalid response")
68
+ return body
69
+
70
+ def close(self) -> None:
71
+ self._client.close()
@@ -0,0 +1,90 @@
1
+ """Command-line entry point for the standalone agent."""
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import signal
7
+ import sys
8
+ from collections.abc import Mapping, Sequence
9
+ from threading import Event
10
+
11
+ from opendrone_bin_sync_agent.agent import SyncAgent
12
+ from opendrone_bin_sync_agent.config import AgentConfig
13
+
14
+ logger = logging.getLogger("opendrone_bin_sync_agent")
15
+
16
+
17
+ def parse_options(
18
+ argv: Sequence[str] | None = None,
19
+ *,
20
+ environ: Mapping[str, str] | None = None,
21
+ ) -> tuple[AgentConfig, bool]:
22
+ parser = argparse.ArgumentParser(
23
+ prog="opendrone-bin-sync-agent",
24
+ description="Watch a folder and synchronize stable ArduPilot .BIN logs to OpenDrone.",
25
+ )
26
+ parser.add_argument("--watch-dir", help="Folder containing completed .BIN logs")
27
+ parser.add_argument("--api-url", help="OpenDrone backend base URL")
28
+ parser.add_argument("--state-db", help="Path to the agent's local SQLite database")
29
+ parser.add_argument("--stability-seconds", type=float)
30
+ parser.add_argument("--scan-seconds", type=float)
31
+ parser.add_argument(
32
+ "--once",
33
+ action="store_true",
34
+ help="Scan once and exit (a first observation still needs a later scan to become stable)",
35
+ )
36
+ args = parser.parse_args(argv)
37
+
38
+ values = dict(os.environ if environ is None else environ)
39
+ option_to_env = {
40
+ "watch_dir": "OPENDRONE_SYNC_WATCH_DIR",
41
+ "api_url": "OPENDRONE_API_URL",
42
+ "state_db": "OPENDRONE_SYNC_DB_PATH",
43
+ "stability_seconds": "OPENDRONE_SYNC_STABILITY_SECONDS",
44
+ "scan_seconds": "OPENDRONE_SYNC_SCAN_SECONDS",
45
+ }
46
+ for option_name, env_name in option_to_env.items():
47
+ value = getattr(args, option_name)
48
+ if value is not None:
49
+ values[env_name] = str(value)
50
+ return AgentConfig.from_environment(values), args.once
51
+
52
+
53
+ def main(argv: Sequence[str] | None = None) -> int:
54
+ try:
55
+ config, single_scan = parse_options(argv)
56
+ except ValueError as exc:
57
+ print(f"Configuration error: {exc}", file=sys.stderr)
58
+ return 2
59
+
60
+ agent = SyncAgent(config)
61
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
62
+ stop_requested = Event()
63
+ previous_handlers = {}
64
+
65
+ def request_stop(_signum, _frame):
66
+ stop_requested.set()
67
+
68
+ try:
69
+ logger.info(
70
+ "Listener activo: observando %s y enviando a %s",
71
+ config.watch_dir,
72
+ config.api_url,
73
+ )
74
+ for signum in (signal.SIGINT, signal.SIGTERM):
75
+ previous_handlers[signum] = signal.signal(signum, request_stop)
76
+ while not stop_requested.is_set():
77
+ logger.info("Escaneando archivos .BIN en %s", config.watch_dir)
78
+ agent.scan_once()
79
+ if single_scan:
80
+ break
81
+ stop_requested.wait(config.scan_seconds)
82
+ finally:
83
+ for signum, previous_handler in previous_handlers.items():
84
+ signal.signal(signum, previous_handler)
85
+ agent.close()
86
+ return 0
87
+
88
+
89
+ if __name__ == "__main__":
90
+ raise SystemExit(main())
@@ -0,0 +1,71 @@
1
+ """Validated runtime settings for the independent synchronization agent."""
2
+
3
+ import math
4
+ import os
5
+ from collections.abc import Mapping
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from urllib.parse import urlparse
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class AgentConfig:
13
+ watch_dir: Path
14
+ api_url: str
15
+ state_db_path: Path
16
+ stability_seconds: float = 10
17
+ scan_seconds: float = 5
18
+
19
+ @classmethod
20
+ def from_environment(cls, environ: Mapping[str, str] | None = None) -> "AgentConfig":
21
+ values = os.environ if environ is None else environ
22
+ required = {
23
+ "OPENDRONE_SYNC_WATCH_DIR": values.get("OPENDRONE_SYNC_WATCH_DIR"),
24
+ "OPENDRONE_API_URL": values.get("OPENDRONE_API_URL"),
25
+ "OPENDRONE_SYNC_DB_PATH": values.get("OPENDRONE_SYNC_DB_PATH"),
26
+ }
27
+ missing = [key for key, value in required.items() if not value]
28
+ if missing:
29
+ raise ValueError(f"Missing required configuration: {', '.join(missing)}")
30
+
31
+ watch_dir = Path(required["OPENDRONE_SYNC_WATCH_DIR"] or "").expanduser().resolve()
32
+ if not watch_dir.is_dir():
33
+ raise ValueError(
34
+ f"The watched folder does not exist or is not a directory: {watch_dir}"
35
+ )
36
+
37
+ api_url = (required["OPENDRONE_API_URL"] or "").rstrip("/")
38
+ try:
39
+ parsed_url = urlparse(api_url)
40
+ hostname = parsed_url.hostname
41
+ port = parsed_url.port
42
+ except ValueError as exc:
43
+ raise ValueError("The backend URL must include a valid host and port") from exc
44
+ if (
45
+ parsed_url.scheme not in {"http", "https"}
46
+ or not parsed_url.netloc
47
+ or not hostname
48
+ or (port is not None and not 1 <= port <= 65535)
49
+ ):
50
+ raise ValueError("The backend URL must use http or https and include a host")
51
+
52
+ try:
53
+ stability_seconds = float(values.get("OPENDRONE_SYNC_STABILITY_SECONDS", "10"))
54
+ scan_seconds = float(values.get("OPENDRONE_SYNC_SCAN_SECONDS", "5"))
55
+ except ValueError as exc:
56
+ raise ValueError("Stability and scan intervals must be numbers") from exc
57
+ if not all(
58
+ math.isfinite(interval) and interval > 0
59
+ for interval in (stability_seconds, scan_seconds)
60
+ ):
61
+ raise ValueError("Stability and scan intervals must be finite positive numbers")
62
+
63
+ return cls(
64
+ watch_dir=watch_dir,
65
+ api_url=api_url,
66
+ state_db_path=Path(required["OPENDRONE_SYNC_DB_PATH"] or "")
67
+ .expanduser()
68
+ .resolve(),
69
+ stability_seconds=stability_seconds,
70
+ scan_seconds=scan_seconds,
71
+ )
@@ -0,0 +1,154 @@
1
+ """Watched-folder discovery and metadata-based stability observations."""
2
+
3
+ import hashlib
4
+ import os
5
+ import tempfile
6
+ import time
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ class FolderScanner:
12
+ def __init__(self, watch_dir: Path) -> None:
13
+ self.watch_dir = watch_dir
14
+
15
+ def discover(self) -> list[Path]:
16
+ return sorted(
17
+ (
18
+ path
19
+ for path in self.watch_dir.iterdir()
20
+ if path.suffix.casefold() == ".bin" and path.is_file() and not path.is_symlink()
21
+ ),
22
+ key=lambda path: path.name.casefold(),
23
+ )
24
+
25
+
26
+ class StabilityTracker:
27
+ def __init__(self, stability_seconds: float) -> None:
28
+ self.stability_seconds = stability_seconds
29
+ self._observations: dict[Path, tuple[tuple[int, int, int, int], float]] = {}
30
+
31
+ def stable_identity(self, path: Path, now: float | None = None) -> "FileIdentity | None":
32
+ try:
33
+ stat = path.stat(follow_symlinks=False)
34
+ except FileNotFoundError:
35
+ self._observations.pop(path, None)
36
+ return None
37
+ if not path.is_file() or path.is_symlink():
38
+ self._observations.pop(path, None)
39
+ return None
40
+
41
+ identity = (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns)
42
+ observed_at = time.monotonic() if now is None else now
43
+ previous = self._observations.get(path)
44
+ if previous is None or previous[0] != identity:
45
+ self._observations[path] = (identity, observed_at)
46
+ return None
47
+ if observed_at - previous[1] < self.stability_seconds:
48
+ return None
49
+ return FileIdentity.from_stat(stat)
50
+
51
+ def is_stable(self, path: Path, now: float | None = None) -> bool:
52
+ return self.stable_identity(path, now=now) is not None
53
+
54
+ def invalidate(self, path: Path) -> None:
55
+ self._observations.pop(path, None)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class FileIdentity:
60
+ device: int
61
+ inode: int
62
+ size_bytes: int
63
+ mtime_ns: int
64
+ ctime_ns: int
65
+
66
+ @classmethod
67
+ def from_stat(cls, stat_result: os.stat_result) -> "FileIdentity":
68
+ return cls(
69
+ device=stat_result.st_dev,
70
+ inode=stat_result.st_ino,
71
+ size_bytes=stat_result.st_size,
72
+ mtime_ns=stat_result.st_mtime_ns,
73
+ ctime_ns=stat_result.st_ctime_ns,
74
+ )
75
+
76
+ @classmethod
77
+ def from_path(cls, path: Path) -> "FileIdentity":
78
+ return cls.from_stat(path.stat(follow_symlinks=False))
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class FileSnapshot:
83
+ source_path: Path
84
+ snapshot_path: Path
85
+ sha256: str
86
+ size_bytes: int
87
+ mtime_ns: int
88
+ source_identity: FileIdentity
89
+
90
+ def cleanup(self) -> None:
91
+ self.snapshot_path.unlink(missing_ok=True)
92
+
93
+
94
+ class SourceChangedError(RuntimeError):
95
+ """The watched file changed while a stable snapshot was being read."""
96
+
97
+
98
+ def sha256_file(path: Path, expected_identity: FileIdentity | None = None) -> str:
99
+ digest = hashlib.sha256()
100
+ with path.open("rb") as source:
101
+ opened_identity = FileIdentity.from_stat(os.fstat(source.fileno()))
102
+ if expected_identity is not None and opened_identity != expected_identity:
103
+ raise SourceChangedError("Watched file changed before checksum verification")
104
+ while chunk := source.read(1024 * 1024):
105
+ digest.update(chunk)
106
+ finished_identity = FileIdentity.from_stat(os.fstat(source.fileno()))
107
+ if expected_identity is not None and (
108
+ finished_identity != expected_identity
109
+ or FileIdentity.from_path(path) != expected_identity
110
+ ):
111
+ raise SourceChangedError("Watched file changed during checksum verification")
112
+ return digest.hexdigest()
113
+
114
+
115
+ def create_snapshot(path: Path) -> FileSnapshot:
116
+ """Copy a stable source to a temporary file while hashing the exact upload bytes."""
117
+ source_identity = FileIdentity.from_path(path)
118
+ if path.is_symlink() or not path.is_file():
119
+ raise SourceChangedError("Candidate is no longer a regular file")
120
+
121
+ digest = hashlib.sha256()
122
+ size_bytes = 0
123
+ snapshot_path: Path | None = None
124
+ try:
125
+ with path.open("rb") as source:
126
+ opened_identity = FileIdentity.from_stat(os.fstat(source.fileno()))
127
+ if opened_identity != source_identity:
128
+ raise SourceChangedError("Candidate changed before reading")
129
+ with tempfile.NamedTemporaryFile(
130
+ prefix="opendrone-sync-", suffix=".BIN", delete=False
131
+ ) as copy:
132
+ snapshot_path = Path(copy.name)
133
+ while chunk := source.read(1024 * 1024):
134
+ copy.write(chunk)
135
+ digest.update(chunk)
136
+ size_bytes += len(chunk)
137
+ finished_identity = FileIdentity.from_stat(os.fstat(source.fileno()))
138
+ path_identity = FileIdentity.from_path(path)
139
+ if finished_identity != source_identity or path_identity != source_identity:
140
+ raise SourceChangedError("Candidate changed while reading")
141
+ if size_bytes != source_identity.size_bytes:
142
+ raise SourceChangedError("Candidate size changed while reading")
143
+ return FileSnapshot(
144
+ source_path=path,
145
+ snapshot_path=snapshot_path,
146
+ sha256=digest.hexdigest(),
147
+ size_bytes=size_bytes,
148
+ mtime_ns=source_identity.mtime_ns,
149
+ source_identity=source_identity,
150
+ )
151
+ except BaseException:
152
+ if snapshot_path is not None:
153
+ snapshot_path.unlink(missing_ok=True)
154
+ raise
@@ -0,0 +1,83 @@
1
+ """Durable local records for observed and synchronized file versions."""
2
+
3
+ import sqlite3
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+
8
+ class AgentStateStore:
9
+ def __init__(self, db_path: Path) -> None:
10
+ self.db_path = db_path.expanduser().resolve()
11
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
12
+ self._connection = sqlite3.connect(self.db_path)
13
+ self._connection.row_factory = sqlite3.Row
14
+ self._connection.execute(
15
+ """CREATE TABLE IF NOT EXISTS file_versions (
16
+ path TEXT NOT NULL,
17
+ sha256 TEXT NOT NULL,
18
+ size_bytes INTEGER NOT NULL,
19
+ mtime_ns INTEGER NOT NULL,
20
+ state TEXT NOT NULL,
21
+ flight_id TEXT,
22
+ last_error TEXT,
23
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
24
+ PRIMARY KEY (path, sha256)
25
+ )"""
26
+ )
27
+ self._connection.commit()
28
+
29
+ def save_version(
30
+ self,
31
+ *,
32
+ path: Path,
33
+ sha256: str,
34
+ size_bytes: int,
35
+ mtime_ns: int,
36
+ state: str,
37
+ flight_id: str | None,
38
+ last_error: str | None = None,
39
+ ) -> None:
40
+ self._connection.execute(
41
+ """INSERT INTO file_versions
42
+ (path, sha256, size_bytes, mtime_ns, state, flight_id, last_error)
43
+ VALUES (?, ?, ?, ?, ?, ?, ?)
44
+ ON CONFLICT(path, sha256) DO UPDATE SET
45
+ size_bytes = excluded.size_bytes,
46
+ mtime_ns = excluded.mtime_ns,
47
+ state = excluded.state,
48
+ flight_id = COALESCE(excluded.flight_id, file_versions.flight_id),
49
+ last_error = excluded.last_error,
50
+ updated_at = CURRENT_TIMESTAMP""",
51
+ (str(path.resolve()), sha256, size_bytes, mtime_ns, state, flight_id, last_error),
52
+ )
53
+ self._connection.commit()
54
+
55
+ def get_version(self, path: Path, sha256: str) -> dict[str, Any] | None:
56
+ row = self._connection.execute(
57
+ "SELECT * FROM file_versions WHERE path = ? AND sha256 = ?",
58
+ (str(path.resolve()), sha256),
59
+ ).fetchone()
60
+ return dict(row) if row is not None else None
61
+
62
+ def is_synced(self, path: Path, sha256: str) -> bool:
63
+ row = self._connection.execute(
64
+ "SELECT state FROM file_versions WHERE path = ? AND sha256 = ?",
65
+ (str(path.resolve()), sha256),
66
+ ).fetchone()
67
+ return row is not None and row["state"] == "synced"
68
+
69
+ def pending_versions(self) -> list[dict[str, Any]]:
70
+ rows = self._connection.execute(
71
+ "SELECT * FROM file_versions WHERE state = 'pending' ORDER BY updated_at, path"
72
+ ).fetchall()
73
+ return [dict(row) for row in rows]
74
+
75
+ def recover_interrupted(self) -> None:
76
+ self._connection.execute(
77
+ """UPDATE file_versions SET state = 'pending', updated_at = CURRENT_TIMESTAMP
78
+ WHERE state IN ('uploading', 'processing')"""
79
+ )
80
+ self._connection.commit()
81
+
82
+ def close(self) -> None:
83
+ self._connection.close()
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.5
2
+ Name: opendrone-bin-sync-agent
3
+ Version: 0.1.0
4
+ Summary: Synchronize completed ArduPilot DataFlash logs to OpenDrone
5
+ Requires-Python: >=3.12
6
+ Requires-Dist: httpx<1,>=0.27
@@ -0,0 +1,12 @@
1
+ opendrone_bin_sync_agent/__init__.py,sha256=Gbt5eQqKkd_XH7s7B-hw3QwW52PMCfahUlPdPhBnjCM,60
2
+ opendrone_bin_sync_agent/__main__.py,sha256=7wNG3kxDnMaRHZwrlws-izmxDyh6Z9QOLJe3kAXnnM0,72
3
+ opendrone_bin_sync_agent/agent.py,sha256=kNS3puILa525ee-aRvCbfaPPrdCaza1ghx3ORwPtPyI,6886
4
+ opendrone_bin_sync_agent/backend.py,sha256=K6dbVrftXqI5EcLwiou-I7Pxn7PHVQ4xUKpoYR5QxmI,2676
5
+ opendrone_bin_sync_agent/cli.py,sha256=JB1a___Z6dBYs0frPig1E5HZHDgOiIZ8VEgObxv2vwU,3073
6
+ opendrone_bin_sync_agent/config.py,sha256=_HDkFTO8MuStaUjQlYRqoKi0xdSG54IdbYuCrl70j58,2729
7
+ opendrone_bin_sync_agent/files.py,sha256=_EoDpu9EUo--DVfWkL4D-ruWexZrHrL4dmgPOYBNH34,5580
8
+ opendrone_bin_sync_agent/state.py,sha256=K2ajR1fCtKFC4Gbr6zqiRfdibhqtf1HHe7jYIqPujTs,3145
9
+ opendrone_bin_sync_agent-0.1.0.dist-info/METADATA,sha256=yD84HfrOqJxj0iYfX5kj7VrSo31Q7U-mp18XvnmGs2c,191
10
+ opendrone_bin_sync_agent-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ opendrone_bin_sync_agent-0.1.0.dist-info/entry_points.txt,sha256=3fUiDe67B6CkDE5X19wAKoLyJMV2dd_9RlE6PQqfcjU,79
12
+ opendrone_bin_sync_agent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ opendrone-bin-sync-agent = opendrone_bin_sync_agent.cli:main