github_restore.py 43 KB

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