github_restore.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. logger.exception("Restore failed for config %s ref %s", config_id, resolved)
  368. await db.rollback()
  369. log.status = "failed"
  370. log.completed_at = datetime.now(timezone.utc)
  371. log.error_message = str(e)[:1000]
  372. await db.commit()
  373. return {"success": False, "message": str(e), "log_id": log_id, "ref": resolved, "results": {}}
  374. finally:
  375. self._running_restore = False
  376. self._progress = None
  377. async def _read_categories(
  378. self, config: GitHubBackupConfig, ref: str, categories: list[RestoreCategory]
  379. ) -> tuple[dict, str]:
  380. """Fetch and parse just the files the requested categories need."""
  381. backend = get_provider_backend(config.provider)
  382. client = await self._get_client()
  383. self._progress = "Listing backup contents..."
  384. tree = await backend.list_tree(
  385. repo_url=config.repository_url, token=config.access_token, ref=ref, client=client
  386. )
  387. if not tree.get("success"):
  388. return {}, tree.get("message") or "Could not list the commit"
  389. available: list[str] = tree.get("paths") or []
  390. wanted: list[str] = []
  391. for category in categories:
  392. wanted.extend(self._category_paths(category, available))
  393. if not wanted:
  394. return {}, "None of the selected categories are present in that commit"
  395. self._progress = "Downloading backup files..."
  396. fetched = await backend.fetch_files(
  397. repo_url=config.repository_url, token=config.access_token, ref=ref, paths=wanted, client=client
  398. )
  399. if not fetched.get("success"):
  400. return {}, fetched.get("message") or "Could not read the commit contents"
  401. parsed, bad = self._parse_json_files(fetched.get("files") or {})
  402. if bad:
  403. return {}, f"Backup contains unreadable JSON: {', '.join(sorted(bad))}"
  404. return parsed, ""
  405. async def _apply(
  406. self,
  407. db: AsyncSession,
  408. payload: dict,
  409. categories: list[RestoreCategory],
  410. overwrite: bool,
  411. ) -> dict[str, _CategoryTally]:
  412. """Apply categories in dependency order and return per-category tallies."""
  413. results: dict[str, _CategoryTally] = {}
  414. archive_id_map: dict[int, int] = {}
  415. # Archives first: spool usage history references archive_id.
  416. if RestoreCategory.ARCHIVES in categories:
  417. self._progress = "Restoring print archives..."
  418. tally = _CategoryTally()
  419. await self._restore_archives(db, payload.get(ARCHIVES_PATH), overwrite, tally, archive_id_map)
  420. results[RestoreCategory.ARCHIVES.value] = tally
  421. if RestoreCategory.SPOOLS in categories:
  422. self._progress = "Restoring spool inventory..."
  423. tally = _CategoryTally()
  424. await self._restore_spools(
  425. db,
  426. payload.get(SPOOLS_PATH),
  427. payload.get(SPOOL_USAGE_PATH),
  428. overwrite,
  429. tally,
  430. archive_id_map,
  431. )
  432. results[RestoreCategory.SPOOLS.value] = tally
  433. if RestoreCategory.SETTINGS in categories:
  434. self._progress = "Restoring app settings..."
  435. tally = _CategoryTally()
  436. await self._restore_settings(db, payload.get(SETTINGS_PATH), overwrite, tally)
  437. results[RestoreCategory.SETTINGS.value] = tally
  438. # Last, because it leaves the database and publishes over MQTT.
  439. if RestoreCategory.KPROFILES in categories:
  440. self._progress = "Sending K-profiles to printers..."
  441. tally = _CategoryTally()
  442. await self._restore_kprofiles(db, payload, tally)
  443. results[RestoreCategory.KPROFILES.value] = tally
  444. return results
  445. # --- Per-category appliers --------------------------------------------
  446. async def _restore_archives(
  447. self,
  448. db: AsyncSession,
  449. payload,
  450. overwrite: bool,
  451. tally: _CategoryTally,
  452. id_map: dict[int, int],
  453. ) -> None:
  454. archives = payload.get("archives") if isinstance(payload, dict) else None
  455. if not isinstance(archives, list):
  456. tally.note("No archive data in this backup")
  457. return
  458. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  459. valid_projects = set((await db.execute(select(Project.id))).scalars().all())
  460. # Only metadata is backed up, never the 3MF/thumbnail bytes, and
  461. # print_archives.file_path is NOT NULL — so inserted rows get an empty
  462. # path and are history-only. Say so once rather than per row.
  463. warned_files = False
  464. for entry in archives:
  465. if not isinstance(entry, dict):
  466. tally.failed += 1
  467. continue
  468. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  469. started_at = _parse_dt(entry.get("started_at"))
  470. existing = await self._find_archive(db, entry, started_at)
  471. fields = {
  472. "print_name": entry.get("print_name"),
  473. "print_time_seconds": entry.get("print_time_seconds"),
  474. "filament_used_grams": entry.get("filament_used_grams"),
  475. "filament_type": entry.get("filament_type"),
  476. "filament_color": entry.get("filament_color"),
  477. "layer_height": entry.get("layer_height"),
  478. "total_layers": entry.get("total_layers"),
  479. "nozzle_diameter": entry.get("nozzle_diameter"),
  480. "bed_temperature": entry.get("bed_temperature"),
  481. "nozzle_temperature": entry.get("nozzle_temperature"),
  482. "sliced_for_model": entry.get("sliced_for_model"),
  483. "status": entry.get("status") or "completed",
  484. "started_at": started_at,
  485. "completed_at": _parse_dt(entry.get("completed_at")),
  486. "makerworld_url": entry.get("makerworld_url"),
  487. "designer": entry.get("designer"),
  488. "external_url": entry.get("external_url"),
  489. "is_favorite": bool(entry.get("is_favorite")),
  490. "tags": entry.get("tags"),
  491. "notes": entry.get("notes"),
  492. "cost": entry.get("cost"),
  493. "failure_reason": entry.get("failure_reason"),
  494. "quantity": entry.get("quantity") or 1,
  495. "energy_kwh": entry.get("energy_kwh"),
  496. "energy_cost": entry.get("energy_cost"),
  497. # A soft-deleted archive is still in the backup (its row is kept
  498. # so stats keep counting it), so carry the flag across or the
  499. # restore turns something the user deleted back into a visible
  500. # archive. Backups written before this key existed have no
  501. # deleted_at, and those rows can only come back live.
  502. "deleted_at": _parse_dt(entry.get("deleted_at")),
  503. }
  504. printer_id = entry.get("printer_id")
  505. if printer_id is not None and printer_id not in valid_printers:
  506. tally.note("Some archives referenced printers that no longer exist — link cleared")
  507. printer_id = None
  508. project_id = entry.get("project_id")
  509. if project_id is not None and project_id not in valid_projects:
  510. tally.note("Some archives referenced projects that no longer exist — link cleared")
  511. project_id = None
  512. fields["printer_id"] = printer_id
  513. fields["project_id"] = project_id
  514. if existing is not None:
  515. if old_id is not None:
  516. id_map[old_id] = existing.id
  517. if not overwrite:
  518. tally.skipped += 1
  519. continue
  520. # Overwrite means "make the local row match the backup", which
  521. # includes un-deleting one the user deleted after the backup was
  522. # taken. Legitimate, but not obvious from a restored/skipped
  523. # count, so say it.
  524. if existing.deleted_at is not None and fields["deleted_at"] is None:
  525. tally.note("Archive(s) deleted since the backup are visible again — overwrite was on")
  526. for key, value in fields.items():
  527. setattr(existing, key, value)
  528. tally.restored += 1
  529. continue
  530. if not warned_files:
  531. tally.note(
  532. "Restored archives carry metadata only — the 3MF and thumbnail files are not in a Git backup"
  533. )
  534. warned_files = True
  535. row = PrintArchive(
  536. filename=entry.get("filename") or "restored-from-backup",
  537. file_path="",
  538. file_size=entry.get("file_size") or 0,
  539. content_hash=entry.get("content_hash"),
  540. **fields,
  541. )
  542. created_at = _parse_dt(entry.get("created_at"))
  543. if created_at is not None:
  544. row.created_at = created_at
  545. db.add(row)
  546. await db.flush()
  547. if old_id is not None:
  548. id_map[old_id] = row.id
  549. tally.restored += 1
  550. async def _find_archive(self, db: AsyncSession, entry: dict, started_at: datetime | None) -> PrintArchive | None:
  551. """Match a backed-up archive to a local row by natural key.
  552. ``started_at`` is nullable and genuinely NULL for a whole class of rows —
  553. the re-slice path in ``library.py`` constructs ``PrintArchive`` without
  554. one — so it cannot be *required* by the key. It narrows the match instead:
  555. a backed-up row with no ``started_at`` matches a local row that has none
  556. either. Requiring it meant those archives never matched, so each restore
  557. re-inserted them as duplicates and overwrite mode could never update them.
  558. ``content_hash`` identifies the sliced file on its own, which is why it is
  559. the branch allowed to run without a ``started_at``; ``filename`` is too
  560. weak for that (re-slices share it) and still requires one. Two backed-up
  561. rows sharing a hash *and* having no ``started_at`` are indistinguishable
  562. in the backup, so they collapse onto one local row — better than
  563. duplicating both on every restore.
  564. Soft-deleted rows are matched deliberately: there is no ``deleted_at``
  565. filter here because the row still exists, and matching it is what stops a
  566. restore inserting a live duplicate of an archive the user has deleted.
  567. """
  568. started_predicate = PrintArchive.started_at == started_at if started_at else PrintArchive.started_at.is_(None)
  569. content_hash = entry.get("content_hash")
  570. if content_hash:
  571. result = await db.execute(
  572. select(PrintArchive).where(PrintArchive.content_hash == content_hash, started_predicate)
  573. )
  574. row = result.scalars().first()
  575. if row is not None:
  576. return row
  577. filename = entry.get("filename")
  578. if filename and started_at:
  579. result = await db.execute(select(PrintArchive).where(PrintArchive.filename == filename, started_predicate))
  580. return result.scalars().first()
  581. return None
  582. async def _restore_spools(
  583. self,
  584. db: AsyncSession,
  585. inventory,
  586. usage_payload,
  587. overwrite: bool,
  588. tally: _CategoryTally,
  589. archive_id_map: dict[int, int],
  590. ) -> None:
  591. spools = inventory.get("spools") if isinstance(inventory, dict) else None
  592. if not isinstance(spools, list):
  593. tally.note("No spool data in this backup")
  594. return
  595. spool_id_map: dict[int, int] = {}
  596. for entry in spools:
  597. if not isinstance(entry, dict):
  598. tally.failed += 1
  599. continue
  600. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  601. existing = await self._find_spool(db, entry)
  602. fields = {
  603. "material": entry.get("material") or "PLA",
  604. "subtype": entry.get("subtype"),
  605. "color_name": entry.get("color_name"),
  606. "rgba": entry.get("rgba"),
  607. "brand": entry.get("brand"),
  608. "label_weight": entry.get("label_weight") or 1000,
  609. "core_weight": entry.get("core_weight") or 250,
  610. "weight_used": entry.get("weight_used") or 0,
  611. "weight_locked": bool(entry.get("weight_locked")),
  612. "slicer_filament": entry.get("slicer_filament"),
  613. "slicer_filament_name": entry.get("slicer_filament_name"),
  614. "nozzle_temp_min": entry.get("nozzle_temp_min"),
  615. "nozzle_temp_max": entry.get("nozzle_temp_max"),
  616. "note": entry.get("note"),
  617. "cost_per_kg": entry.get("cost_per_kg"),
  618. "tag_uid": entry.get("tag_uid"),
  619. "tray_uuid": entry.get("tray_uuid"),
  620. "data_origin": entry.get("data_origin"),
  621. "tag_type": entry.get("tag_type"),
  622. "archived_at": _parse_dt(entry.get("archived_at")),
  623. }
  624. if existing is not None:
  625. if old_id is not None:
  626. spool_id_map[old_id] = existing.id
  627. if not overwrite:
  628. tally.skipped += 1
  629. continue
  630. for key, value in fields.items():
  631. setattr(existing, key, value)
  632. tally.restored += 1
  633. continue
  634. row = Spool(**fields)
  635. # Carry the original created_at across. Without it the row would be
  636. # stamped "now", and the composite fallback in _find_spool (which
  637. # keys on created_at) would miss on a second restore and insert a
  638. # duplicate instead of matching.
  639. created_at = _parse_dt(entry.get("created_at"))
  640. if created_at is not None:
  641. row.created_at = created_at
  642. db.add(row)
  643. await db.flush()
  644. if old_id is not None:
  645. spool_id_map[old_id] = row.id
  646. tally.restored += 1
  647. await self._restore_spool_usage(db, usage_payload, tally, spool_id_map, archive_id_map)
  648. async def _find_spool(self, db: AsyncSession, entry: dict) -> Spool | None:
  649. """Match a backed-up spool to a local row.
  650. Physical identity first (an RFID/Bambu tag is the spool), then a
  651. descriptive composite including ``created_at`` so two otherwise
  652. identical spools added at different times stay distinct.
  653. """
  654. tag_uid = entry.get("tag_uid")
  655. if tag_uid:
  656. result = await db.execute(select(Spool).where(Spool.tag_uid == tag_uid))
  657. row = result.scalars().first()
  658. if row is not None:
  659. return row
  660. tray_uuid = entry.get("tray_uuid")
  661. if tray_uuid:
  662. result = await db.execute(select(Spool).where(Spool.tray_uuid == tray_uuid))
  663. row = result.scalars().first()
  664. if row is not None:
  665. return row
  666. created_at = _parse_dt(entry.get("created_at"))
  667. if created_at is None:
  668. return None
  669. result = await db.execute(
  670. select(Spool).where(
  671. Spool.created_at == created_at,
  672. Spool.material == (entry.get("material") or "PLA"),
  673. Spool.brand == entry.get("brand"),
  674. Spool.subtype == entry.get("subtype"),
  675. Spool.color_name == entry.get("color_name"),
  676. )
  677. )
  678. return result.scalars().first()
  679. async def _restore_spool_usage(
  680. self,
  681. db: AsyncSession,
  682. usage_payload,
  683. tally: _CategoryTally,
  684. spool_id_map: dict[int, int],
  685. archive_id_map: dict[int, int],
  686. ) -> None:
  687. usage = usage_payload.get("usage_history") if isinstance(usage_payload, dict) else None
  688. if not isinstance(usage, list) or not usage:
  689. return
  690. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  691. unresolved = 0
  692. for entry in usage:
  693. if not isinstance(entry, dict):
  694. tally.failed += 1
  695. continue
  696. old_spool_id = entry.get("spool_id")
  697. spool_id = spool_id_map.get(old_spool_id) if isinstance(old_spool_id, int) else None
  698. if spool_id is None:
  699. # The parent spool never made it into the map: the backup's spool
  700. # list didn't include it, or its entry carried no integer id. A
  701. # spool that was merely *skipped* (matched locally, overwrite off)
  702. # is mapped a few lines up in _restore_spools, so it never lands
  703. # here — which is why the note below offers no remedy.
  704. unresolved += 1
  705. tally.skipped += 1
  706. continue
  707. created_at = _parse_dt(entry.get("created_at"))
  708. # Usage history has no natural key of its own, so dedupe on the
  709. # tuple that makes a consumption event unique in practice.
  710. existing = await db.execute(
  711. select(SpoolUsageHistory).where(
  712. SpoolUsageHistory.spool_id == spool_id,
  713. SpoolUsageHistory.created_at == created_at,
  714. SpoolUsageHistory.weight_used == (entry.get("weight_used") or 0),
  715. SpoolUsageHistory.print_name == entry.get("print_name"),
  716. )
  717. )
  718. if existing.scalars().first() is not None:
  719. tally.skipped += 1
  720. continue
  721. printer_id = entry.get("printer_id")
  722. if printer_id is not None and printer_id not in valid_printers:
  723. printer_id = None
  724. old_archive_id = entry.get("archive_id")
  725. archive_id = archive_id_map.get(old_archive_id) if isinstance(old_archive_id, int) else None
  726. row = SpoolUsageHistory(
  727. spool_id=spool_id,
  728. printer_id=printer_id,
  729. print_name=entry.get("print_name"),
  730. archive_id=archive_id,
  731. weight_used=entry.get("weight_used") or 0,
  732. percent_used=entry.get("percent_used") or 0,
  733. status=entry.get("status") or "completed",
  734. cost=entry.get("cost"),
  735. )
  736. if created_at is not None:
  737. row.created_at = created_at
  738. db.add(row)
  739. tally.restored += 1
  740. if unresolved:
  741. tally.note(
  742. f"{unresolved} usage record(s) skipped — their spool is not in this backup's "
  743. "spool list, so there is nothing to attach them to."
  744. )
  745. async def _restore_settings(self, db: AsyncSession, payload, overwrite: bool, tally: _CategoryTally) -> None:
  746. values = payload.get("settings") if isinstance(payload, dict) else None
  747. if not isinstance(values, dict):
  748. tally.note("No settings data in this backup")
  749. return
  750. blocked = 0
  751. protected = 0
  752. for key, value in values.items():
  753. if not isinstance(key, str) or not key:
  754. tally.failed += 1
  755. continue
  756. if _is_blocked_setting_key(key):
  757. blocked += 1
  758. tally.skipped += 1
  759. continue
  760. if _is_protected_setting_key(key):
  761. protected += 1
  762. tally.skipped += 1
  763. continue
  764. if value is None:
  765. tally.skipped += 1
  766. continue
  767. result = await db.execute(select(Settings).where(Settings.key == key))
  768. existing = result.scalar_one_or_none()
  769. if existing is not None:
  770. if not overwrite:
  771. tally.skipped += 1
  772. continue
  773. existing.value = str(value)
  774. tally.restored += 1
  775. continue
  776. db.add(Settings(key=key, value=str(value)))
  777. tally.restored += 1
  778. if blocked:
  779. tally.note(f"{blocked} credential-like key(s) skipped — re-enter secrets manually")
  780. if protected:
  781. tally.note(
  782. f"{protected} authentication setting(s) skipped — change those in Settings > "
  783. "Authentication so the lockout checks still run"
  784. )
  785. async def _restore_kprofiles(self, db: AsyncSession, payload: dict, tally: _CategoryTally) -> None:
  786. by_serial: dict[str, list[tuple[str, dict]]] = {}
  787. for path, content in payload.items():
  788. match = _KPROFILE_PATH_RE.match(path)
  789. if not match or not isinstance(content, dict):
  790. continue
  791. by_serial.setdefault(match.group(1), []).append((match.group(2), content))
  792. if not by_serial:
  793. tally.note("No K-profile data in this backup")
  794. return
  795. result = await db.execute(select(Printer))
  796. printers = {p.serial_number: p for p in result.scalars().all() if p.serial_number}
  797. # Overwrite is not offered for K-profiles: extrusion_cali_set replaces
  798. # the profile occupying a slot, so writing is always an overwrite on the
  799. # printer side.
  800. tally.note("K-profiles always overwrite the matching slot on the printer")
  801. tally.note("The printer's acknowledgement is not reliable — verify the profiles on the printer")
  802. for serial, entries in sorted(by_serial.items()):
  803. profile_total = sum(len(c.get("profiles") or []) for _, c in entries)
  804. printer = printers.get(serial)
  805. if printer is None:
  806. tally.skipped += profile_total
  807. tally.note(f"No printer with serial {serial} — skipped")
  808. continue
  809. client = printer_manager.get_client(printer.id)
  810. if not client or not client.state.connected:
  811. tally.skipped += profile_total
  812. tally.note(f"{printer.name} ({serial}) is not connected — skipped")
  813. continue
  814. for nozzle, content in sorted(entries):
  815. profiles = content.get("profiles")
  816. if not isinstance(profiles, list) or not profiles:
  817. continue
  818. if nozzle not in _KNOWN_NOZZLES:
  819. tally.note(f"Unexpected nozzle diameter {nozzle} for {serial} — sent as-is")
  820. # The backup's slot_id is a cali_idx, and cali_idx is as
  821. # unstable as the autoincrement ids we already refuse to reuse
  822. # for spools and archives: editing a profile in Bambuddy is a
  823. # delete-then-add on a single-nozzle printer, which re-keys it.
  824. # Addressing extrusion_cali_set at a slot that no longer exists
  825. # is a silent no-op — the printer drops it and we would still
  826. # report the profile restored. So resolve the live index first.
  827. current = await self._current_kprofile_index(client, nozzle, serial)
  828. profile_dicts = []
  829. unmatched = 0
  830. for p in profiles:
  831. if not isinstance(p, dict):
  832. continue
  833. match = self._match_kprofile(p, current)
  834. if match is None:
  835. unmatched += 1
  836. profile_dicts.append(
  837. {
  838. "filament_id": p.get("filament_id", ""),
  839. "name": p.get("name", ""),
  840. "k_value": p.get("k_value", "0.020000"),
  841. "nozzle_id": p.get("nozzle_id"),
  842. "extruder_id": p.get("extruder_id", 0),
  843. # Prefer the live setting_id when we matched: it is
  844. # what the printer currently associates with the slot.
  845. "setting_id": (match.setting_id if match else None) or p.get("setting_id"),
  846. # cali_idx -1 tells the printer to add a new profile
  847. # rather than address a slot that isn't there.
  848. "cali_idx": match.slot_id if match else -1,
  849. # Only consulted for the generated-setting_id
  850. # fallback; cali_idx above takes precedence.
  851. "slot_id": 0,
  852. }
  853. )
  854. if not profile_dicts:
  855. continue
  856. if unmatched:
  857. tally.note(
  858. f"{unmatched} profile(s) for {nozzle} had no counterpart on {printer.name} "
  859. "— added as new profiles"
  860. )
  861. try:
  862. sent = client.set_kprofiles_batch(profile_dicts, nozzle)
  863. except Exception as e:
  864. logger.warning("K-profile restore failed for %s nozzle %s: %s", serial, nozzle, e)
  865. sent = False
  866. if sent:
  867. tally.restored += len(profile_dicts)
  868. else:
  869. tally.failed += len(profile_dicts)
  870. tally.note(f"Failed to send {nozzle} profiles to {printer.name} ({serial})")
  871. @staticmethod
  872. async def _current_kprofile_index(client, nozzle: str, serial: str) -> list:
  873. """Read the printer's live profiles for one nozzle.
  874. Best-effort: a read failure degrades to "nothing matched", which makes
  875. every profile an add rather than aborting the restore.
  876. """
  877. try:
  878. return list(await client.get_kprofiles(nozzle_diameter=nozzle) or [])
  879. except Exception as e:
  880. logger.warning("Could not read live K-profiles for %s nozzle %s: %s", serial, nozzle, e)
  881. return []
  882. @staticmethod
  883. def _match_kprofile(entry: dict, current: list):
  884. """Find the live profile a backed-up entry corresponds to.
  885. ``setting_id`` is the filament preset the profile was calibrated for and
  886. is the strongest signal; a delete-then-add edit regenerates it, so fall
  887. back to the display name, which Bambuddy's own editor preserves.
  888. Both are scoped by ``filament_id`` — the same preset on a different
  889. filament is a different profile.
  890. """
  891. filament_id = entry.get("filament_id")
  892. if not filament_id:
  893. return None
  894. candidates = [c for c in current if c.filament_id == filament_id]
  895. if not candidates:
  896. return None
  897. setting_id = entry.get("setting_id")
  898. if setting_id:
  899. for c in candidates:
  900. if c.setting_id == setting_id:
  901. return c
  902. name = entry.get("name")
  903. if name:
  904. for c in candidates:
  905. if c.name == name:
  906. return c
  907. # Exactly one profile for this filament and no better discriminator:
  908. # treat it as the same profile rather than duplicating it.
  909. return candidates[0] if len(candidates) == 1 else None
  910. # Singleton instance
  911. github_restore_service = GitHubRestoreService()