github_restore.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. """Restore Bambuddy data from a Git provider backup (issue #2656).
  2. The backup side (``github_backup.py``) is push-only: it collects a handful of
  3. JSON documents and commits them. This module is the read side — it walks the
  4. backup repository's history, lets a caller inspect what a given commit contains,
  5. and applies selected categories back into the local database (or, for
  6. K-profiles, back onto the printers).
  7. Design notes worth knowing before editing:
  8. * **A restore never reuses the backup's primary keys.** ``spool.id`` and
  9. ``print_archives.id`` are bare autoincrement columns, so the ids in a backup
  10. taken weeks ago very likely belong to unrelated rows today. Rows are matched
  11. on natural keys instead, inserted without an explicit id, and an
  12. ``old_id -> new_id`` map is threaded through so foreign keys in dependent
  13. tables (spool usage history) still line up.
  14. The printer-side ``cali_idx`` behaves the same way and gets the same
  15. treatment. Editing a K-profile in Bambuddy is a delete-then-add on a
  16. single-nozzle printer, which re-keys it, and ``extrusion_cali_set`` aimed at a
  17. slot that no longer exists is silently dropped — so the live index is read
  18. back and matched before writing, never taken from the backup.
  19. * **Categories are applied archives -> spools -> settings -> kprofiles.**
  20. Archives first because spool usage history references ``archive_id``;
  21. K-profiles last because they leave the database and talk to hardware.
  22. * **Cloud profiles are not restorable.** The backup collector never actually
  23. writes ``cloud_profiles/*.json``, and the preset list it would write carries
  24. no setting payload. Tracked separately from #2656.
  25. """
  26. import asyncio
  27. import json
  28. import logging
  29. import re
  30. from datetime import datetime, timezone
  31. import httpx
  32. from sqlalchemy import select
  33. from sqlalchemy.ext.asyncio import AsyncSession
  34. from backend.app.core.database import async_session
  35. from backend.app.models.archive import PrintArchive
  36. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  37. from backend.app.models.printer import Printer
  38. from backend.app.models.project import Project
  39. from backend.app.models.settings import Settings
  40. from backend.app.models.spool import Spool
  41. from backend.app.models.spool_usage_history import SpoolUsageHistory
  42. from backend.app.schemas.github_backup import RestoreCategory
  43. from backend.app.services.git_providers.factory import get_provider_backend
  44. from backend.app.services.printer_manager import printer_manager
  45. logger = logging.getLogger(__name__)
  46. METADATA_PATH = "backup_metadata.json"
  47. SETTINGS_PATH = "settings/app_settings.json"
  48. SPOOLS_PATH = "spools/inventory.json"
  49. SPOOL_USAGE_PATH = "spools/usage_history.json"
  50. ARCHIVES_PATH = "archives/print_history.json"
  51. # kprofiles/{printer_serial}/{nozzle_diameter}.json
  52. _KPROFILE_PATH_RE = re.compile(r"^kprofiles/([^/]+)/([^/]+)\.json$")
  53. # Settings keys the backup collector already refuses to write. Applied again on
  54. # the read side because a backup taken before that denylist existed can still
  55. # contain them, and a restore must not resurrect a stale credential.
  56. _SENSITIVE_SETTING_KEYS = {"bambu_cloud_token", "auth_secret_key"}
  57. # Belt-and-braces for the same reason: any key that looks like a secret is
  58. # skipped even if it isn't in the explicit denylist above.
  59. _SECRET_KEY_HINTS = ("token", "secret", "password", "access_code", "api_key", "passphrase")
  60. # Keys that decide *who can reach the instance* rather than how it behaves. The
  61. # backup collector writes them like any other Settings row, so a backup taken
  62. # before auth was turned on carries auth_enabled=false — and a restore reaches
  63. # the table directly, so honouring them would:
  64. #
  65. # * disable authentication outright. ``set_auth_enabled`` pairs its write with
  66. # ``invalidate_auth_enabled_cache()``; we cannot, so the 30 s TTL in
  67. # core.auth is the only thing between the write and an open instance. That
  68. # cache is built to fail closed — writing the stored value behind its back
  69. # is what would make it fail open.
  70. # * bypass the lockout refusals ``update_settings`` enforces (a
  71. # ``local_login_enabled=false`` with no enabled OIDC provider, or with no
  72. # OIDC link on the caller, is a 400 there — #1589).
  73. # * cross a permission boundary: /github-backup/restore is gated on
  74. # GITHUB_RESTORE alone, so this would be a way to rewrite auth config
  75. # without SETTINGS_UPDATE.
  76. #
  77. # Auth is reconfigured through the auth UI, which has the guards. Restoring it
  78. # from a snapshot has no safe reading.
  79. _PROTECTED_SETTING_KEYS = {
  80. "auth_enabled",
  81. "advanced_auth_enabled",
  82. "local_login_enabled",
  83. "setup_completed",
  84. }
  85. # Nozzle diameters the backup collector iterates. A path outside this set means
  86. # the backup was written by a newer version, so accept it rather than dropping
  87. # data, but keep the list for validation messages.
  88. _KNOWN_NOZZLES = {"0.2", "0.4", "0.6", "0.8"}
  89. def _parse_dt(value) -> datetime | None:
  90. """Best-effort parse of a datetime the backup wrote via ``str(...)``."""
  91. if not value or not isinstance(value, str):
  92. return None
  93. try:
  94. return datetime.fromisoformat(value)
  95. except ValueError:
  96. return None
  97. def _is_blocked_setting_key(key: str) -> bool:
  98. lowered = key.lower()
  99. return key in _SENSITIVE_SETTING_KEYS or any(hint in lowered for hint in _SECRET_KEY_HINTS)
  100. def _is_protected_setting_key(key: str) -> bool:
  101. return key in _PROTECTED_SETTING_KEYS
  102. def _is_skipped_setting_key(key: str) -> bool:
  103. """True for any key ``_restore_settings`` refuses to write, for either reason."""
  104. return _is_blocked_setting_key(key) or _is_protected_setting_key(key)
  105. class _CategoryTally:
  106. """Mutable accumulator matching ``GitHubRestoreCategoryResult``."""
  107. def __init__(self) -> None:
  108. self.restored = 0
  109. self.skipped = 0
  110. self.failed = 0
  111. self.notes: list[str] = []
  112. def note(self, message: str) -> None:
  113. # Notes are surfaced verbatim in the UI, so keep the list bounded rather
  114. # than emitting one line per row for a large backup.
  115. if message not in self.notes and len(self.notes) < 20:
  116. self.notes.append(message)
  117. def as_dict(self) -> dict:
  118. return {"restored": self.restored, "skipped": self.skipped, "failed": self.failed, "notes": self.notes}
  119. class GitHubRestoreService:
  120. """Reads a backup repository and applies selected categories locally."""
  121. def __init__(self) -> None:
  122. self._running_restore: bool = False
  123. self._progress: str | None = None
  124. self._http_client: httpx.AsyncClient | None = None
  125. # Guards the check-then-set on ``_running_restore``. Without it two
  126. # concurrent POSTs can both observe False before either sets it.
  127. self._lock = asyncio.Lock()
  128. async def _get_client(self) -> httpx.AsyncClient:
  129. if self._http_client is None or self._http_client.is_closed:
  130. self._http_client = httpx.AsyncClient(timeout=60.0)
  131. return self._http_client
  132. @property
  133. def is_running(self) -> bool:
  134. return self._running_restore
  135. @property
  136. def progress(self) -> str | None:
  137. return self._progress
  138. # --- Repository reads --------------------------------------------------
  139. async def list_commits(self, config: GitHubBackupConfig, limit: int = 20) -> dict:
  140. """List recent commits on the configured branch."""
  141. backend = get_provider_backend(config.provider)
  142. client = await self._get_client()
  143. result = await backend.list_commits(
  144. repo_url=config.repository_url,
  145. token=config.access_token,
  146. branch=config.branch,
  147. client=client,
  148. limit=limit,
  149. )
  150. result["branch"] = config.branch
  151. return result
  152. async def _resolve_ref(self, config: GitHubBackupConfig, ref: str) -> tuple[str | None, str]:
  153. """Turn ``HEAD`` into a concrete commit SHA.
  154. Done once up front so a preview and the restore that follows it act on
  155. the same commit even if a scheduled backup lands in between.
  156. """
  157. if ref and ref.upper() != "HEAD":
  158. return ref, ""
  159. result = await self.list_commits(config, limit=1)
  160. if not result.get("success"):
  161. return None, result.get("message") or "Could not read the backup repository"
  162. commits = result.get("commits") or []
  163. if not commits:
  164. return None, f"Branch '{config.branch}' has no commits to restore from"
  165. return commits[0]["sha"], ""
  166. def _category_paths(self, category: RestoreCategory, available: list[str]) -> list[str]:
  167. """Return the paths in ``available`` that belong to ``category``."""
  168. if category == RestoreCategory.SETTINGS:
  169. return [p for p in (SETTINGS_PATH,) if p in available]
  170. if category == RestoreCategory.SPOOLS:
  171. return [p for p in (SPOOLS_PATH, SPOOL_USAGE_PATH) if p in available]
  172. if category == RestoreCategory.ARCHIVES:
  173. return [p for p in (ARCHIVES_PATH,) if p in available]
  174. if category == RestoreCategory.KPROFILES:
  175. return sorted(p for p in available if _KPROFILE_PATH_RE.match(p))
  176. return []
  177. @staticmethod
  178. def _parse_json_files(raw: dict[str, str]) -> tuple[dict[str, object], list[str]]:
  179. """Parse each fetched file, collecting paths that failed to parse."""
  180. parsed: dict[str, object] = {}
  181. bad: list[str] = []
  182. for path, text in raw.items():
  183. try:
  184. parsed[path] = json.loads(text)
  185. except (ValueError, TypeError):
  186. bad.append(path)
  187. return parsed, bad
  188. async def preview(self, config: GitHubBackupConfig, ref: str = "HEAD") -> dict:
  189. """Report which categories a commit contains, and how much is in each."""
  190. resolved, error = await self._resolve_ref(config, ref)
  191. if resolved is None:
  192. return {"success": False, "message": error, "ref": ref, "categories": []}
  193. backend = get_provider_backend(config.provider)
  194. client = await self._get_client()
  195. tree = await backend.list_tree(
  196. repo_url=config.repository_url, token=config.access_token, ref=resolved, client=client
  197. )
  198. if not tree.get("success"):
  199. return {"success": False, "message": tree.get("message") or "Could not list the commit", "ref": resolved}
  200. available: list[str] = tree.get("paths") or []
  201. # One batched read covers metadata plus every category payload.
  202. wanted = [METADATA_PATH] if METADATA_PATH in available else []
  203. for category in RestoreCategory:
  204. wanted.extend(self._category_paths(category, available))
  205. fetched = await backend.fetch_files(
  206. repo_url=config.repository_url, token=config.access_token, ref=resolved, paths=wanted, client=client
  207. )
  208. if not fetched.get("success"):
  209. return {
  210. "success": False,
  211. "message": fetched.get("message") or "Could not read the commit contents",
  212. "ref": resolved,
  213. }
  214. parsed, bad_paths = self._parse_json_files(fetched.get("files") or {})
  215. metadata = parsed.get(METADATA_PATH)
  216. metadata_version = metadata.get("version") if isinstance(metadata, dict) else None
  217. categories = []
  218. for category in RestoreCategory:
  219. paths = self._category_paths(category, available)
  220. if not paths:
  221. categories.append(
  222. {
  223. "category": category,
  224. "available": False,
  225. "item_count": 0,
  226. "detail": "Not present in this backup commit",
  227. }
  228. )
  229. continue
  230. unreadable = [p for p in paths if p in bad_paths]
  231. if unreadable:
  232. categories.append(
  233. {
  234. "category": category,
  235. "available": False,
  236. "item_count": 0,
  237. "detail": f"Unreadable JSON: {', '.join(unreadable)}",
  238. }
  239. )
  240. continue
  241. count, detail = self._count_items(category, parsed)
  242. categories.append({"category": category, "available": True, "item_count": count, "detail": detail})
  243. commit_info = None
  244. commits = (await self.list_commits(config, limit=20)).get("commits") or []
  245. for entry in commits:
  246. if entry["sha"] == resolved:
  247. commit_info = entry
  248. break
  249. return {
  250. "success": True,
  251. "message": "OK",
  252. "ref": resolved,
  253. "commit": commit_info,
  254. "metadata_version": metadata_version,
  255. "categories": categories,
  256. }
  257. @staticmethod
  258. def _count_items(category: RestoreCategory, parsed: dict) -> tuple[int, str | None]:
  259. """Count restorable items for ``category`` and describe any caveat."""
  260. if category == RestoreCategory.SETTINGS:
  261. payload = parsed.get(SETTINGS_PATH)
  262. values = payload.get("settings") if isinstance(payload, dict) else None
  263. if not isinstance(values, dict):
  264. return 0, "No settings in payload"
  265. # Both refusals are counted the same way here so the preview's item
  266. # count matches what the restore actually writes; the wording only
  267. # calls out the credential ones, which are what a user might expect
  268. # to come back.
  269. blocked = sum(1 for key in values if _is_blocked_setting_key(key))
  270. skipped = sum(1 for key in values if _is_skipped_setting_key(key))
  271. detail = f"{blocked} credential-like keys will be skipped" if blocked else None
  272. return len(values) - skipped, detail
  273. if category == RestoreCategory.SPOOLS:
  274. payload = parsed.get(SPOOLS_PATH)
  275. spools = payload.get("spools") if isinstance(payload, dict) else None
  276. usage_payload = parsed.get(SPOOL_USAGE_PATH)
  277. usage = usage_payload.get("usage_history") if isinstance(usage_payload, dict) else None
  278. count = len(spools) if isinstance(spools, list) else 0
  279. detail = f"plus {len(usage)} usage records" if isinstance(usage, list) and usage else None
  280. return count, detail
  281. if category == RestoreCategory.ARCHIVES:
  282. payload = parsed.get(ARCHIVES_PATH)
  283. archives = payload.get("archives") if isinstance(payload, dict) else None
  284. count = len(archives) if isinstance(archives, list) else 0
  285. return count, "Metadata only — 3MF files and thumbnails are not in a Git backup"
  286. if category == RestoreCategory.KPROFILES:
  287. total = 0
  288. serials = set()
  289. for path, payload in parsed.items():
  290. match = _KPROFILE_PATH_RE.match(path)
  291. if not match or not isinstance(payload, dict):
  292. continue
  293. serials.add(match.group(1))
  294. profiles = payload.get("profiles")
  295. if isinstance(profiles, list):
  296. total += len(profiles)
  297. detail = f"across {len(serials)} printer(s)" if serials else None
  298. return total, detail
  299. return 0, None
  300. # --- Restore -----------------------------------------------------------
  301. async def run_restore(
  302. self,
  303. config_id: int,
  304. ref: str,
  305. categories: list[RestoreCategory],
  306. overwrite_existing: bool = False,
  307. ) -> dict:
  308. """Apply selected categories from one backup commit."""
  309. # Import locally to avoid a module-level cycle: the backup service takes
  310. # the mirror-image lock against us.
  311. from backend.app.services.github_backup import github_backup_service
  312. # The lock serialises two concurrent restores; the backup side has no
  313. # lock of its own, and relies on this region staying await-free after the
  314. # acquisition. Both flags are plain bools on one event loop, so with no
  315. # suspension point between the two reads and the write, the loop cannot
  316. # slip github_backup.run_backup's mirror-image check in between. Adding an
  317. # `await` below the acquisition and above `self._running_restore = True`
  318. # would let a backup and a restore run at once.
  319. async with self._lock:
  320. if self._running_restore:
  321. return {"success": False, "message": "A restore is already running", "results": {}}
  322. if github_backup_service.is_running:
  323. return {
  324. "success": False,
  325. "message": "A backup is currently running. Wait for it to finish before restoring.",
  326. "results": {},
  327. }
  328. self._running_restore = True
  329. log_id = None
  330. try:
  331. async with async_session() as db:
  332. result = await db.execute(select(GitHubBackupConfig).where(GitHubBackupConfig.id == config_id))
  333. config = result.scalar_one_or_none()
  334. if not config:
  335. return {"success": False, "message": "Configuration not found", "results": {}}
  336. self._progress = "Resolving commit..."
  337. resolved, error = await self._resolve_ref(config, ref)
  338. if resolved is None:
  339. return {"success": False, "message": error, "results": {}}
  340. log = GitHubBackupLog(config_id=config_id, status="running", trigger="restore", commit_sha=resolved)
  341. db.add(log)
  342. await db.commit()
  343. await db.refresh(log)
  344. log_id = log.id
  345. try:
  346. payload, error = await self._read_categories(config, resolved, categories)
  347. if error:
  348. raise RuntimeError(error)
  349. results = await self._apply(db, payload, categories, overwrite_existing)
  350. await db.commit()
  351. total_restored = sum(tally.restored for tally in results.values())
  352. any_failed = any(tally.failed for tally in results.values())
  353. log.status = "failed" if any_failed and total_restored == 0 else "success"
  354. log.completed_at = datetime.now(timezone.utc)
  355. log.files_changed = total_restored
  356. if any_failed:
  357. log.error_message = "Some items could not be restored — see the restore result for detail"
  358. await db.commit()
  359. return {
  360. "success": True,
  361. "message": f"Restored {total_restored} item(s) from {resolved[:7]}",
  362. "log_id": log_id,
  363. "ref": resolved,
  364. "results": {name: tally.as_dict() for name, tally in results.items()},
  365. }
  366. except Exception as e:
  367. # Rolls back whatever is still uncommitted. That is every
  368. # database category unless K-profiles were also selected, in
  369. # which case _apply has already committed them before talking
  370. # to the printers — see the comment there.
  371. logger.exception("Restore failed for config %s ref %s", config_id, resolved)
  372. await db.rollback()
  373. log.status = "failed"
  374. log.completed_at = datetime.now(timezone.utc)
  375. log.error_message = str(e)[:1000]
  376. await db.commit()
  377. return {"success": False, "message": str(e), "log_id": log_id, "ref": resolved, "results": {}}
  378. finally:
  379. self._running_restore = False
  380. self._progress = None
  381. async def _read_categories(
  382. self, config: GitHubBackupConfig, ref: str, categories: list[RestoreCategory]
  383. ) -> tuple[dict, str]:
  384. """Fetch and parse just the files the requested categories need."""
  385. backend = get_provider_backend(config.provider)
  386. client = await self._get_client()
  387. self._progress = "Listing backup contents..."
  388. tree = await backend.list_tree(
  389. repo_url=config.repository_url, token=config.access_token, ref=ref, client=client
  390. )
  391. if not tree.get("success"):
  392. return {}, tree.get("message") or "Could not list the commit"
  393. available: list[str] = tree.get("paths") or []
  394. wanted: list[str] = []
  395. for category in categories:
  396. wanted.extend(self._category_paths(category, available))
  397. if not wanted:
  398. return {}, "None of the selected categories are present in that commit"
  399. self._progress = "Downloading backup files..."
  400. fetched = await backend.fetch_files(
  401. repo_url=config.repository_url, token=config.access_token, ref=ref, paths=wanted, client=client
  402. )
  403. if not fetched.get("success"):
  404. return {}, fetched.get("message") or "Could not read the commit contents"
  405. parsed, bad = self._parse_json_files(fetched.get("files") or {})
  406. if bad:
  407. return {}, f"Backup contains unreadable JSON: {', '.join(sorted(bad))}"
  408. return parsed, ""
  409. async def _apply(
  410. self,
  411. db: AsyncSession,
  412. payload: dict,
  413. categories: list[RestoreCategory],
  414. overwrite: bool,
  415. ) -> dict[str, _CategoryTally]:
  416. """Apply categories in dependency order and return per-category tallies."""
  417. results: dict[str, _CategoryTally] = {}
  418. archive_id_map: dict[int, int] = {}
  419. # Archives first: spool usage history references archive_id.
  420. if RestoreCategory.ARCHIVES in categories:
  421. self._progress = "Restoring print archives..."
  422. tally = _CategoryTally()
  423. await self._restore_archives(db, payload.get(ARCHIVES_PATH), overwrite, tally, archive_id_map)
  424. results[RestoreCategory.ARCHIVES.value] = tally
  425. if RestoreCategory.SPOOLS in categories:
  426. self._progress = "Restoring spool inventory..."
  427. tally = _CategoryTally()
  428. await self._restore_spools(
  429. db,
  430. payload.get(SPOOLS_PATH),
  431. payload.get(SPOOL_USAGE_PATH),
  432. overwrite,
  433. tally,
  434. archive_id_map,
  435. )
  436. results[RestoreCategory.SPOOLS.value] = tally
  437. if RestoreCategory.SETTINGS in categories:
  438. self._progress = "Restoring app settings..."
  439. tally = _CategoryTally()
  440. await self._restore_settings(db, payload.get(SETTINGS_PATH), overwrite, tally)
  441. results[RestoreCategory.SETTINGS.value] = tally
  442. # Last, because it leaves the database and publishes over MQTT.
  443. if RestoreCategory.KPROFILES in categories:
  444. # Commit the database categories FIRST, and not just for tidiness.
  445. # Everything above has already autoflushed its INSERTs, so SQLite is
  446. # holding the single write transaction — and _restore_kprofiles then
  447. # awaits get_kprofiles per printer per nozzle, which is
  448. # timeout=5.0 * max_retries=3, i.e. up to ~15 s each against an
  449. # unresponsive printer. busy_timeout is 15 s (core/database.py), so a
  450. # farm with a couple of sulking printers would hold the writer past
  451. # it and every concurrent writer in the app would fail with
  452. # "database is locked".
  453. #
  454. # The cost is that a K-profile failure no longer rolls back the
  455. # categories that already succeeded. That is the correct trade
  456. # anyway: extrusion_cali_set has left for the printer by then and
  457. # cannot be rolled back either, so a rollback would only have made
  458. # the database disagree with the hardware.
  459. await db.commit()
  460. self._progress = "Sending K-profiles to printers..."
  461. tally = _CategoryTally()
  462. await self._restore_kprofiles(db, payload, tally)
  463. results[RestoreCategory.KPROFILES.value] = tally
  464. return results
  465. # --- Per-category appliers --------------------------------------------
  466. async def _restore_archives(
  467. self,
  468. db: AsyncSession,
  469. payload,
  470. overwrite: bool,
  471. tally: _CategoryTally,
  472. id_map: dict[int, int],
  473. ) -> None:
  474. archives = payload.get("archives") if isinstance(payload, dict) else None
  475. if not isinstance(archives, list):
  476. tally.note("No archive data in this backup")
  477. return
  478. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  479. valid_projects = set((await db.execute(select(Project.id))).scalars().all())
  480. # Only metadata is backed up, never the 3MF/thumbnail bytes, and
  481. # print_archives.file_path is NOT NULL — so inserted rows get an empty
  482. # path and are history-only. Say so once rather than per row.
  483. warned_files = False
  484. for entry in archives:
  485. if not isinstance(entry, dict):
  486. tally.failed += 1
  487. continue
  488. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  489. started_at = _parse_dt(entry.get("started_at"))
  490. existing = await self._find_archive(db, entry, started_at)
  491. fields = {
  492. "print_name": entry.get("print_name"),
  493. "print_time_seconds": entry.get("print_time_seconds"),
  494. "filament_used_grams": entry.get("filament_used_grams"),
  495. "filament_type": entry.get("filament_type"),
  496. "filament_color": entry.get("filament_color"),
  497. "layer_height": entry.get("layer_height"),
  498. "total_layers": entry.get("total_layers"),
  499. "nozzle_diameter": entry.get("nozzle_diameter"),
  500. "bed_temperature": entry.get("bed_temperature"),
  501. "nozzle_temperature": entry.get("nozzle_temperature"),
  502. "sliced_for_model": entry.get("sliced_for_model"),
  503. "status": entry.get("status") or "completed",
  504. "started_at": started_at,
  505. "completed_at": _parse_dt(entry.get("completed_at")),
  506. "makerworld_url": entry.get("makerworld_url"),
  507. "designer": entry.get("designer"),
  508. "external_url": entry.get("external_url"),
  509. "is_favorite": bool(entry.get("is_favorite")),
  510. "tags": entry.get("tags"),
  511. "notes": entry.get("notes"),
  512. "cost": entry.get("cost"),
  513. "failure_reason": entry.get("failure_reason"),
  514. "quantity": entry.get("quantity") or 1,
  515. "energy_kwh": entry.get("energy_kwh"),
  516. "energy_cost": entry.get("energy_cost"),
  517. # A soft-deleted archive is still in the backup (its row is kept
  518. # so stats keep counting it), so carry the flag across or the
  519. # restore turns something the user deleted back into a visible
  520. # archive. Backups written before this key existed have no
  521. # deleted_at, and those rows can only come back live.
  522. "deleted_at": _parse_dt(entry.get("deleted_at")),
  523. }
  524. printer_id = entry.get("printer_id")
  525. if printer_id is not None and printer_id not in valid_printers:
  526. tally.note("Some archives referenced printers that no longer exist — link cleared")
  527. printer_id = None
  528. project_id = entry.get("project_id")
  529. if project_id is not None and project_id not in valid_projects:
  530. tally.note("Some archives referenced projects that no longer exist — link cleared")
  531. project_id = None
  532. fields["printer_id"] = printer_id
  533. fields["project_id"] = project_id
  534. if existing is not None:
  535. if old_id is not None:
  536. id_map[old_id] = existing.id
  537. if not overwrite:
  538. tally.skipped += 1
  539. continue
  540. # Overwrite means "make the local row match the backup", which
  541. # includes un-deleting one the user deleted after the backup was
  542. # taken. Legitimate, but not obvious from a restored/skipped
  543. # count, so say it.
  544. if existing.deleted_at is not None and fields["deleted_at"] is None:
  545. tally.note("Archive(s) deleted since the backup are visible again — overwrite was on")
  546. for key, value in fields.items():
  547. setattr(existing, key, value)
  548. tally.restored += 1
  549. continue
  550. if not warned_files:
  551. tally.note(
  552. "Restored archives carry metadata only — the 3MF and thumbnail files are not in a Git backup"
  553. )
  554. warned_files = True
  555. row = PrintArchive(
  556. filename=entry.get("filename") or "restored-from-backup",
  557. file_path="",
  558. file_size=entry.get("file_size") or 0,
  559. content_hash=entry.get("content_hash"),
  560. **fields,
  561. )
  562. created_at = _parse_dt(entry.get("created_at"))
  563. if created_at is not None:
  564. row.created_at = created_at
  565. db.add(row)
  566. await db.flush()
  567. if old_id is not None:
  568. id_map[old_id] = row.id
  569. tally.restored += 1
  570. async def _find_archive(self, db: AsyncSession, entry: dict, started_at: datetime | None) -> PrintArchive | None:
  571. """Match a backed-up archive to a local row by natural key.
  572. ``started_at`` is nullable and genuinely NULL for a whole class of rows —
  573. the re-slice path in ``library.py`` constructs ``PrintArchive`` without
  574. one — so it cannot be *required* by the key. It narrows the match instead:
  575. a backed-up row with no ``started_at`` matches a local row that has none
  576. either. Requiring it meant those archives never matched, so each restore
  577. re-inserted them as duplicates and overwrite mode could never update them.
  578. ``content_hash`` identifies the sliced file on its own, which is why it is
  579. the branch allowed to run without a ``started_at``; ``filename`` is too
  580. weak for that (re-slices share it) and still requires one. Two backed-up
  581. rows sharing a hash *and* having no ``started_at`` are indistinguishable
  582. in the backup, so they collapse onto one local row — better than
  583. duplicating both on every restore.
  584. Soft-deleted rows are matched deliberately: there is no ``deleted_at``
  585. filter here because the row still exists, and matching it is what stops a
  586. restore inserting a live duplicate of an archive the user has deleted.
  587. """
  588. started_predicate = PrintArchive.started_at == started_at if started_at else PrintArchive.started_at.is_(None)
  589. content_hash = entry.get("content_hash")
  590. if content_hash:
  591. result = await db.execute(
  592. select(PrintArchive).where(PrintArchive.content_hash == content_hash, started_predicate)
  593. )
  594. row = result.scalars().first()
  595. if row is not None:
  596. return row
  597. filename = entry.get("filename")
  598. if filename and started_at:
  599. result = await db.execute(select(PrintArchive).where(PrintArchive.filename == filename, started_predicate))
  600. return result.scalars().first()
  601. return None
  602. async def _restore_spools(
  603. self,
  604. db: AsyncSession,
  605. inventory,
  606. usage_payload,
  607. overwrite: bool,
  608. tally: _CategoryTally,
  609. archive_id_map: dict[int, int],
  610. ) -> None:
  611. spools = inventory.get("spools") if isinstance(inventory, dict) else None
  612. if not isinstance(spools, list):
  613. tally.note("No spool data in this backup")
  614. return
  615. spool_id_map: dict[int, int] = {}
  616. for entry in spools:
  617. if not isinstance(entry, dict):
  618. tally.failed += 1
  619. continue
  620. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  621. existing = await self._find_spool(db, entry)
  622. fields = {
  623. "material": entry.get("material") or "PLA",
  624. "subtype": entry.get("subtype"),
  625. "color_name": entry.get("color_name"),
  626. "rgba": entry.get("rgba"),
  627. "brand": entry.get("brand"),
  628. "label_weight": entry.get("label_weight") or 1000,
  629. "core_weight": entry.get("core_weight") or 250,
  630. "weight_used": entry.get("weight_used") or 0,
  631. "weight_locked": bool(entry.get("weight_locked")),
  632. "slicer_filament": entry.get("slicer_filament"),
  633. "slicer_filament_name": entry.get("slicer_filament_name"),
  634. "nozzle_temp_min": entry.get("nozzle_temp_min"),
  635. "nozzle_temp_max": entry.get("nozzle_temp_max"),
  636. "note": entry.get("note"),
  637. "cost_per_kg": entry.get("cost_per_kg"),
  638. "tag_uid": entry.get("tag_uid"),
  639. "tray_uuid": entry.get("tray_uuid"),
  640. "data_origin": entry.get("data_origin"),
  641. "tag_type": entry.get("tag_type"),
  642. "archived_at": _parse_dt(entry.get("archived_at")),
  643. }
  644. if existing is not None:
  645. if old_id is not None:
  646. spool_id_map[old_id] = existing.id
  647. if not overwrite:
  648. tally.skipped += 1
  649. continue
  650. for key, value in fields.items():
  651. setattr(existing, key, value)
  652. tally.restored += 1
  653. continue
  654. row = Spool(**fields)
  655. # Carry the original created_at across. Without it the row would be
  656. # stamped "now", and the composite fallback in _find_spool (which
  657. # keys on created_at) would miss on a second restore and insert a
  658. # duplicate instead of matching.
  659. created_at = _parse_dt(entry.get("created_at"))
  660. if created_at is not None:
  661. row.created_at = created_at
  662. db.add(row)
  663. await db.flush()
  664. if old_id is not None:
  665. spool_id_map[old_id] = row.id
  666. tally.restored += 1
  667. await self._restore_spool_usage(db, usage_payload, tally, spool_id_map, archive_id_map)
  668. async def _find_spool(self, db: AsyncSession, entry: dict) -> Spool | None:
  669. """Match a backed-up spool to a local row.
  670. Physical identity first (an RFID/Bambu tag is the spool), then a
  671. descriptive composite including ``created_at`` so two otherwise
  672. identical spools added at different times stay distinct.
  673. """
  674. tag_uid = entry.get("tag_uid")
  675. if tag_uid:
  676. result = await db.execute(select(Spool).where(Spool.tag_uid == tag_uid))
  677. row = result.scalars().first()
  678. if row is not None:
  679. return row
  680. tray_uuid = entry.get("tray_uuid")
  681. if tray_uuid:
  682. result = await db.execute(select(Spool).where(Spool.tray_uuid == tray_uuid))
  683. row = result.scalars().first()
  684. if row is not None:
  685. return row
  686. created_at = _parse_dt(entry.get("created_at"))
  687. if created_at is None:
  688. return None
  689. result = await db.execute(
  690. select(Spool).where(
  691. Spool.created_at == created_at,
  692. Spool.material == (entry.get("material") or "PLA"),
  693. Spool.brand == entry.get("brand"),
  694. Spool.subtype == entry.get("subtype"),
  695. Spool.color_name == entry.get("color_name"),
  696. )
  697. )
  698. return result.scalars().first()
  699. async def _restore_spool_usage(
  700. self,
  701. db: AsyncSession,
  702. usage_payload,
  703. tally: _CategoryTally,
  704. spool_id_map: dict[int, int],
  705. archive_id_map: dict[int, int],
  706. ) -> None:
  707. usage = usage_payload.get("usage_history") if isinstance(usage_payload, dict) else None
  708. if not isinstance(usage, list) or not usage:
  709. return
  710. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  711. unresolved = 0
  712. for entry in usage:
  713. if not isinstance(entry, dict):
  714. tally.failed += 1
  715. continue
  716. old_spool_id = entry.get("spool_id")
  717. spool_id = spool_id_map.get(old_spool_id) if isinstance(old_spool_id, int) else None
  718. if spool_id is None:
  719. # The parent spool never made it into the map: the backup's spool
  720. # list didn't include it, or its entry carried no integer id. A
  721. # spool that was merely *skipped* (matched locally, overwrite off)
  722. # is mapped a few lines up in _restore_spools, so it never lands
  723. # here — which is why the note below offers no remedy.
  724. unresolved += 1
  725. tally.skipped += 1
  726. continue
  727. created_at = _parse_dt(entry.get("created_at"))
  728. # Usage history has no natural key of its own, so dedupe on the
  729. # tuple that makes a consumption event unique in practice.
  730. existing = await db.execute(
  731. select(SpoolUsageHistory).where(
  732. SpoolUsageHistory.spool_id == spool_id,
  733. SpoolUsageHistory.created_at == created_at,
  734. SpoolUsageHistory.weight_used == (entry.get("weight_used") or 0),
  735. SpoolUsageHistory.print_name == entry.get("print_name"),
  736. )
  737. )
  738. if existing.scalars().first() is not None:
  739. tally.skipped += 1
  740. continue
  741. printer_id = entry.get("printer_id")
  742. if printer_id is not None and printer_id not in valid_printers:
  743. printer_id = None
  744. old_archive_id = entry.get("archive_id")
  745. archive_id = archive_id_map.get(old_archive_id) if isinstance(old_archive_id, int) else None
  746. row = SpoolUsageHistory(
  747. spool_id=spool_id,
  748. printer_id=printer_id,
  749. print_name=entry.get("print_name"),
  750. archive_id=archive_id,
  751. weight_used=entry.get("weight_used") or 0,
  752. percent_used=entry.get("percent_used") or 0,
  753. status=entry.get("status") or "completed",
  754. cost=entry.get("cost"),
  755. )
  756. if created_at is not None:
  757. row.created_at = created_at
  758. db.add(row)
  759. tally.restored += 1
  760. if unresolved:
  761. tally.note(
  762. f"{unresolved} usage record(s) skipped — their spool is not in this backup's "
  763. "spool list, so there is nothing to attach them to."
  764. )
  765. async def _restore_settings(self, db: AsyncSession, payload, overwrite: bool, tally: _CategoryTally) -> None:
  766. values = payload.get("settings") if isinstance(payload, dict) else None
  767. if not isinstance(values, dict):
  768. tally.note("No settings data in this backup")
  769. return
  770. blocked = 0
  771. protected = 0
  772. for key, value in values.items():
  773. if not isinstance(key, str) or not key:
  774. tally.failed += 1
  775. continue
  776. if _is_blocked_setting_key(key):
  777. blocked += 1
  778. tally.skipped += 1
  779. continue
  780. if _is_protected_setting_key(key):
  781. protected += 1
  782. tally.skipped += 1
  783. continue
  784. if value is None:
  785. tally.skipped += 1
  786. continue
  787. result = await db.execute(select(Settings).where(Settings.key == key))
  788. existing = result.scalar_one_or_none()
  789. if existing is not None:
  790. if not overwrite:
  791. tally.skipped += 1
  792. continue
  793. existing.value = str(value)
  794. tally.restored += 1
  795. continue
  796. db.add(Settings(key=key, value=str(value)))
  797. tally.restored += 1
  798. if blocked:
  799. tally.note(f"{blocked} credential-like key(s) skipped — re-enter secrets manually")
  800. if protected:
  801. tally.note(
  802. f"{protected} authentication setting(s) skipped — change those in Settings > "
  803. "Authentication so the lockout checks still run"
  804. )
  805. async def _restore_kprofiles(self, db: AsyncSession, payload: dict, tally: _CategoryTally) -> None:
  806. by_serial: dict[str, list[tuple[str, dict]]] = {}
  807. for path, content in payload.items():
  808. match = _KPROFILE_PATH_RE.match(path)
  809. if not match or not isinstance(content, dict):
  810. continue
  811. by_serial.setdefault(match.group(1), []).append((match.group(2), content))
  812. if not by_serial:
  813. tally.note("No K-profile data in this backup")
  814. return
  815. result = await db.execute(select(Printer))
  816. printers = {p.serial_number: p for p in result.scalars().all() if p.serial_number}
  817. # Overwrite is not offered for K-profiles: extrusion_cali_set replaces
  818. # the profile occupying a slot, so writing is always an overwrite on the
  819. # printer side.
  820. tally.note("K-profiles always overwrite the matching slot on the printer")
  821. tally.note("The printer's acknowledgement is not reliable — verify the profiles on the printer")
  822. for serial, entries in sorted(by_serial.items()):
  823. profile_total = sum(len(c.get("profiles") or []) for _, c in entries)
  824. printer = printers.get(serial)
  825. if printer is None:
  826. tally.skipped += profile_total
  827. tally.note(f"No printer with serial {serial} — skipped")
  828. continue
  829. client = printer_manager.get_client(printer.id)
  830. if not client or not client.state.connected:
  831. tally.skipped += profile_total
  832. tally.note(f"{printer.name} ({serial}) is not connected — skipped")
  833. continue
  834. for nozzle, content in sorted(entries):
  835. profiles = content.get("profiles")
  836. if not isinstance(profiles, list) or not profiles:
  837. continue
  838. if nozzle not in _KNOWN_NOZZLES:
  839. tally.note(f"Unexpected nozzle diameter {nozzle} for {serial} — sent as-is")
  840. # The backup's slot_id is a cali_idx, and cali_idx is as
  841. # unstable as the autoincrement ids we already refuse to reuse
  842. # for spools and archives: editing a profile in Bambuddy is a
  843. # delete-then-add on a single-nozzle printer, which re-keys it.
  844. # Addressing extrusion_cali_set at a slot that no longer exists
  845. # is a silent no-op — the printer drops it and we would still
  846. # report the profile restored. So resolve the live index first.
  847. current = await self._current_kprofile_index(client, nozzle, serial)
  848. profile_dicts = []
  849. unmatched = 0
  850. for p in profiles:
  851. if not isinstance(p, dict):
  852. continue
  853. match = self._match_kprofile(p, current)
  854. if match is None:
  855. unmatched += 1
  856. profile_dicts.append(
  857. {
  858. "filament_id": p.get("filament_id", ""),
  859. "name": p.get("name", ""),
  860. "k_value": p.get("k_value", "0.020000"),
  861. "nozzle_id": p.get("nozzle_id"),
  862. "extruder_id": p.get("extruder_id", 0),
  863. # Prefer the live setting_id when we matched: it is
  864. # what the printer currently associates with the slot.
  865. "setting_id": (match.setting_id if match else None) or p.get("setting_id"),
  866. # cali_idx -1 tells the printer to add a new profile
  867. # rather than address a slot that isn't there.
  868. "cali_idx": match.slot_id if match else -1,
  869. # Only consulted for the generated-setting_id
  870. # fallback; cali_idx above takes precedence.
  871. "slot_id": 0,
  872. }
  873. )
  874. if not profile_dicts:
  875. continue
  876. if unmatched:
  877. tally.note(
  878. f"{unmatched} profile(s) for {nozzle} had no counterpart on {printer.name} "
  879. "— added as new profiles"
  880. )
  881. try:
  882. sent = client.set_kprofiles_batch(profile_dicts, nozzle)
  883. except Exception as e:
  884. logger.warning("K-profile restore failed for %s nozzle %s: %s", serial, nozzle, e)
  885. sent = False
  886. if sent:
  887. tally.restored += len(profile_dicts)
  888. else:
  889. tally.failed += len(profile_dicts)
  890. tally.note(f"Failed to send {nozzle} profiles to {printer.name} ({serial})")
  891. @staticmethod
  892. async def _current_kprofile_index(client, nozzle: str, serial: str) -> list:
  893. """Read the printer's live profiles for one nozzle.
  894. Best-effort: a read failure degrades to "nothing matched", which makes
  895. every profile an add rather than aborting the restore.
  896. """
  897. try:
  898. return list(await client.get_kprofiles(nozzle_diameter=nozzle) or [])
  899. except Exception as e:
  900. logger.warning("Could not read live K-profiles for %s nozzle %s: %s", serial, nozzle, e)
  901. return []
  902. @staticmethod
  903. def _match_kprofile(entry: dict, current: list):
  904. """Find the live profile a backed-up entry corresponds to.
  905. ``setting_id`` is the filament preset the profile was calibrated for and
  906. is the strongest signal; a delete-then-add edit regenerates it, so fall
  907. back to the display name, which Bambuddy's own editor preserves.
  908. Both are scoped by ``filament_id`` — the same preset on a different
  909. filament is a different profile.
  910. """
  911. filament_id = entry.get("filament_id")
  912. if not filament_id:
  913. return None
  914. candidates = [c for c in current if c.filament_id == filament_id]
  915. if not candidates:
  916. return None
  917. setting_id = entry.get("setting_id")
  918. if setting_id:
  919. for c in candidates:
  920. if c.setting_id == setting_id:
  921. return c
  922. name = entry.get("name")
  923. if name:
  924. for c in candidates:
  925. if c.name == name:
  926. return c
  927. # Exactly one profile for this filament and no better discriminator:
  928. # treat it as the same profile rather than duplicating it.
  929. return candidates[0] if len(candidates) == 1 else None
  930. # Singleton instance
  931. github_restore_service = GitHubRestoreService()