github_restore.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  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 os
  30. import re
  31. from dataclasses import dataclass, field as dataclasses_field
  32. from datetime import datetime, timezone
  33. import httpx
  34. from sqlalchemy import select
  35. from sqlalchemy.ext.asyncio import AsyncSession
  36. from backend.app.core.database import async_session
  37. from backend.app.models.archive import PrintArchive
  38. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  39. from backend.app.models.printer import Printer
  40. from backend.app.models.project import Project
  41. from backend.app.models.settings import Settings
  42. from backend.app.models.spool import Spool
  43. from backend.app.models.spool_usage_history import SpoolUsageHistory
  44. from backend.app.models.user import User
  45. from backend.app.schemas.github_backup import RestoreCategory
  46. from backend.app.services.git_providers.factory import get_provider_backend
  47. from backend.app.services.printer_manager import printer_manager
  48. logger = logging.getLogger(__name__)
  49. METADATA_PATH = "backup_metadata.json"
  50. SETTINGS_PATH = "settings/app_settings.json"
  51. SPOOLS_PATH = "spools/inventory.json"
  52. SPOOL_USAGE_PATH = "spools/usage_history.json"
  53. ARCHIVES_PATH = "archives/print_history.json"
  54. # kprofiles/{printer_serial}/{nozzle_diameter}.json
  55. _KPROFILE_PATH_RE = re.compile(r"^kprofiles/([^/]+)/([^/]+)\.json$")
  56. # Settings keys the backup collector already refuses to write. Applied again on
  57. # the read side because a backup taken before that denylist existed can still
  58. # contain them, and a restore must not resurrect a stale credential.
  59. _SENSITIVE_SETTING_KEYS = {"bambu_cloud_token", "auth_secret_key"}
  60. # Belt-and-braces for the same reason: any key that looks like a secret is
  61. # skipped even if it isn't in the explicit denylist above.
  62. _SECRET_KEY_HINTS = ("token", "secret", "password", "access_code", "api_key", "passphrase")
  63. # Settings the MQTT relay reads only when it is (re)configured, so restoring the
  64. # rows is not enough on its own. Mirrors the set the settings PUT handler
  65. # watches. mqtt_password is in here for the configure() payload's sake — the
  66. # credential blocklist means a restore never writes it.
  67. _MQTT_SETTING_KEYS = {
  68. "mqtt_enabled",
  69. "mqtt_broker",
  70. "mqtt_port",
  71. "mqtt_username",
  72. "mqtt_password",
  73. "mqtt_topic_prefix",
  74. "mqtt_use_tls",
  75. }
  76. # Keys that decide *who can reach the instance* rather than how it behaves. The
  77. # backup collector writes them like any other Settings row, so a backup taken
  78. # before auth was turned on carries auth_enabled=false — and a restore reaches
  79. # the table directly, so honouring them would:
  80. #
  81. # * disable authentication outright. ``set_auth_enabled`` pairs its write with
  82. # ``invalidate_auth_enabled_cache()``; we cannot, so the 30 s TTL in
  83. # core.auth is the only thing between the write and an open instance. That
  84. # cache is built to fail closed — writing the stored value behind its back
  85. # is what would make it fail open.
  86. # * bypass the lockout refusals ``update_settings`` enforces (a
  87. # ``local_login_enabled=false`` with no enabled OIDC provider, or with no
  88. # OIDC link on the caller, is a 400 there — #1589).
  89. # * cross a permission boundary: /github-backup/restore is gated on
  90. # GITHUB_RESTORE alone, so this would be a way to rewrite auth config
  91. # without SETTINGS_UPDATE.
  92. #
  93. # Auth is reconfigured through the auth UI, which has the guards. Restoring it
  94. # from a snapshot has no safe reading.
  95. _PROTECTED_SETTING_KEYS = {
  96. "auth_enabled",
  97. "advanced_auth_enabled",
  98. "local_login_enabled",
  99. "setup_completed",
  100. }
  101. # Nozzle diameters the backup collector iterates. A path outside this set means
  102. # the backup was written by a newer version, so accept it rather than dropping
  103. # data, but keep the list for validation messages.
  104. _KNOWN_NOZZLES = {"0.2", "0.4", "0.6", "0.8"}
  105. def _parse_dt(value) -> datetime | None:
  106. """Best-effort parse of a datetime the backup wrote via ``str(...)``."""
  107. if not value or not isinstance(value, str):
  108. return None
  109. try:
  110. return datetime.fromisoformat(value)
  111. except ValueError:
  112. return None
  113. def _is_blocked_setting_key(key: str) -> bool:
  114. lowered = key.lower()
  115. return key in _SENSITIVE_SETTING_KEYS or any(hint in lowered for hint in _SECRET_KEY_HINTS)
  116. def _is_protected_setting_key(key: str) -> bool:
  117. return key in _PROTECTED_SETTING_KEYS
  118. # There used to be an ``_is_skipped_setting_key`` here, the union of the two
  119. # predicates above, shared by the preview and the restore so neither could drift
  120. # from the other. It is gone because a name is no longer enough to decide: the
  121. # third refusal below depends on the payload's *other* values and on local
  122. # database state. ``_plan_settings`` is the shared classifier now, and it covers
  123. # all three reasons.
  124. # Toggles whose *safety* depends on a companion credential that the blocklist
  125. # above refuses to restore. Writing the toggle alone is not a partial restore,
  126. # it is a downgrade:
  127. #
  128. # * prometheus_enabled with no token opens /api/v1/metrics. The route is on
  129. # PUBLIC_API_ROUTES and its own gate is ``if token:`` (api/routes/metrics.py),
  130. # so an empty or absent token means no authentication at all — a full,
  131. # unauthenticated dump of the instance to anyone who can reach the port. On
  132. # an instance that never enabled Prometheus there is no token row, so
  133. # overwrite-off alone is enough to do it.
  134. # * the other four switch an integration on with no way to authenticate to it,
  135. # which breaks the login path (LDAP) or the connection (MQTT, HA).
  136. #
  137. # virtual_printer_enabled is largely vestigial post-migration — core/database.py
  138. # copies the rows into the virtual_printers table — but it is the same shape, and
  139. # refusing a vestigial toggle is a harmless no-op.
  140. _COMPANION_CREDENTIALS = {
  141. "prometheus_enabled": "prometheus_token",
  142. "ldap_enabled": "ldap_bind_password",
  143. "mqtt_enabled": "mqtt_password",
  144. "ha_enabled": "ha_token",
  145. "virtual_printer_enabled": "virtual_printer_access_code",
  146. }
  147. # Companion credentials a reader takes from the environment rather than from a
  148. # Settings row. ha_token is the only one: get_homeassistant_settings prefers
  149. # HA_TOKEN over the row, and auto-enables ha_enabled when HA_URL and HA_TOKEN are
  150. # both set, so an env-configured instance has a usable credential and no row.
  151. _COMPANION_CREDENTIAL_ENV = {"ha_token": "HA_TOKEN"}
  152. def _setting_value_is_true(value: object) -> bool:
  153. """True if a settings *payload* value would be stored as "on".
  154. Deliberately as narrow as ``api.routes.settings.setting_is_true``: a restore
  155. writes ``str(value)`` verbatim and no reader in the codebase treats "1",
  156. "on" or "yes" as on, so restoring one of those cannot switch anything on.
  157. Bool-tolerant because a backup's JSON can carry a real boolean.
  158. """
  159. if isinstance(value, bool):
  160. return value
  161. if value is None:
  162. return False
  163. return str(value).strip().lower() == "true"
  164. def _is_usable_credential(value: object) -> bool:
  165. """True if a credential value is present and not blank.
  166. A present-but-*blank* ``prometheus_token`` row counts as unusable, because an
  167. empty token is exactly the ``if token:`` hole the companion rule exists to
  168. stop a restore from opening.
  169. """
  170. return value is not None and bool(str(value).strip())
  171. @dataclass(frozen=True)
  172. class _SettingsPlan:
  173. """Which keys of a settings payload will not be written, and why.
  174. Built once, before anything is added to the session, and shared by the
  175. preview and the restore so the two cannot disagree about what a commit will
  176. change. The companion bucket is why this needs a session at all: unlike the
  177. two name-based buckets it depends on local database state.
  178. The three buckets are disjoint — a key is classified once, in order.
  179. """
  180. blocked: tuple[str, ...] = ()
  181. protected: tuple[str, ...] = ()
  182. companion: tuple[str, ...] = ()
  183. @property
  184. def refused(self) -> frozenset[str]:
  185. return frozenset(self.blocked) | frozenset(self.protected) | frozenset(self.companion)
  186. @property
  187. def refused_count(self) -> int:
  188. return len(self.blocked) + len(self.protected) + len(self.companion)
  189. @dataclass(frozen=True)
  190. class _Detail:
  191. """A preview caveat, as a translation code plus its English rendering.
  192. Same contract as a note: the client translates ``code`` with ``params`` and
  193. falls back to ``message``.
  194. """
  195. code: str
  196. message: str
  197. params: dict[str, str | int] = dataclasses_field(default_factory=dict)
  198. class _CategoryTally:
  199. """Mutable accumulator matching ``GitHubRestoreCategoryResult``."""
  200. def __init__(self) -> None:
  201. self.restored = 0
  202. self.skipped = 0
  203. self.failed = 0
  204. self.notes: list[dict] = []
  205. def note(self, code: str, message: str, **params) -> None:
  206. """Record a note as a translation code, its params and an English fallback.
  207. Deduped on ``(code, params)`` rather than on the rendered text, which is
  208. the same thing today but keeps two notes that differ only in a printer
  209. name from collapsing into one. Bounded for the reason it always was: the
  210. UI renders every note, so a large backup must not emit one per row.
  211. """
  212. if any(existing["code"] == code and existing["params"] == params for existing in self.notes):
  213. return
  214. if len(self.notes) >= 20:
  215. return
  216. self.notes.append({"code": code, "params": params, "message": message})
  217. def as_dict(self) -> dict:
  218. return {"restored": self.restored, "skipped": self.skipped, "failed": self.failed, "notes": self.notes}
  219. class GitHubRestoreService:
  220. """Reads a backup repository and applies selected categories locally."""
  221. def __init__(self) -> None:
  222. self._running_restore: bool = False
  223. self._progress: str | None = None
  224. self._http_client: httpx.AsyncClient | None = None
  225. # Guards the check-then-set on ``_running_restore``. Without it two
  226. # concurrent POSTs can both observe False before either sets it.
  227. self._lock = asyncio.Lock()
  228. async def _get_client(self) -> httpx.AsyncClient:
  229. if self._http_client is None or self._http_client.is_closed:
  230. self._http_client = httpx.AsyncClient(timeout=60.0)
  231. return self._http_client
  232. @property
  233. def is_running(self) -> bool:
  234. return self._running_restore
  235. @property
  236. def progress(self) -> str | None:
  237. return self._progress
  238. # --- Repository reads --------------------------------------------------
  239. async def list_commits(self, config: GitHubBackupConfig, limit: int = 20) -> dict:
  240. """List recent commits on the configured branch."""
  241. backend = get_provider_backend(config.provider)
  242. client = await self._get_client()
  243. result = await backend.list_commits(
  244. repo_url=config.repository_url,
  245. token=config.access_token,
  246. branch=config.branch,
  247. client=client,
  248. limit=limit,
  249. )
  250. result["branch"] = config.branch
  251. return result
  252. async def _resolve_ref(self, config: GitHubBackupConfig, ref: str) -> tuple[str | None, str, dict | None]:
  253. """Turn ``HEAD`` into a concrete commit SHA.
  254. Done once up front so a preview and the restore that follows it act on
  255. the same commit even if a scheduled backup lands in between.
  256. The third element is the commit entry, when resolving already fetched
  257. one. ``preview`` displays it, and taking it from here means the ``HEAD``
  258. case — by far the common one — costs one ``list_commits`` call rather
  259. than two.
  260. """
  261. if ref and ref.upper() != "HEAD":
  262. return ref, "", None
  263. result = await self.list_commits(config, limit=1)
  264. if not result.get("success"):
  265. return None, result.get("message") or "Could not read the backup repository", None
  266. commits = result.get("commits") or []
  267. if not commits:
  268. return None, f"Branch '{config.branch}' has no commits to restore from", None
  269. return commits[0]["sha"], "", commits[0]
  270. async def _describe_commit(self, config: GitHubBackupConfig, resolved: str) -> dict | None:
  271. """Find the display metadata for one commit SHA.
  272. Two things used to leave ``commit: null`` in a preview, and the second is
  273. the one that bit in practice:
  274. * the commit is older than the 20 the picker lists, so it is not in the
  275. scan at all — that is what ``get_commit`` is for;
  276. * ``REF_PATTERN`` accepts a 7-character ref while providers return the
  277. full 40, so an exact ``==`` never matched an abbreviated SHA *even when
  278. the commit was in the window*. Hence the prefix comparison.
  279. Best-effort throughout: this is a subject line and a date, so a failure
  280. returns None and the preview renders without them rather than failing.
  281. """
  282. commits = (await self.list_commits(config, limit=20)).get("commits") or []
  283. for entry in commits:
  284. sha = entry.get("sha") or ""
  285. if sha == resolved or sha.startswith(resolved) or resolved.startswith(sha):
  286. return entry
  287. backend = get_provider_backend(config.provider)
  288. client = await self._get_client()
  289. result = await backend.get_commit(
  290. repo_url=config.repository_url, token=config.access_token, ref=resolved, client=client
  291. )
  292. return result.get("commit") if result.get("success") else None
  293. def _category_paths(self, category: RestoreCategory, available: list[str]) -> list[str]:
  294. """Return the paths in ``available`` that belong to ``category``."""
  295. if category == RestoreCategory.SETTINGS:
  296. return [p for p in (SETTINGS_PATH,) if p in available]
  297. if category == RestoreCategory.SPOOLS:
  298. return [p for p in (SPOOLS_PATH, SPOOL_USAGE_PATH) if p in available]
  299. if category == RestoreCategory.ARCHIVES:
  300. return [p for p in (ARCHIVES_PATH,) if p in available]
  301. if category == RestoreCategory.KPROFILES:
  302. return sorted(p for p in available if _KPROFILE_PATH_RE.match(p))
  303. return []
  304. @staticmethod
  305. def _parse_json_files(raw: dict[str, str]) -> tuple[dict[str, object], list[str]]:
  306. """Parse each fetched file, collecting paths that failed to parse."""
  307. parsed: dict[str, object] = {}
  308. bad: list[str] = []
  309. for path, text in raw.items():
  310. try:
  311. parsed[path] = json.loads(text)
  312. except (ValueError, TypeError):
  313. bad.append(path)
  314. return parsed, bad
  315. @staticmethod
  316. async def _plan_settings(db: AsyncSession, values: dict) -> _SettingsPlan:
  317. """Classify every key of a settings payload into its refusal bucket.
  318. Keys with an unusable name land in no bucket: they are the restore's
  319. ``failed``, not a refusal, and the preview counts them because the run
  320. will still report on them.
  321. Reads local state, so it must run before anything is added to the
  322. session — otherwise "does this instance already have a credential" would
  323. see the restore's own writes.
  324. """
  325. blocked: list[str] = []
  326. protected: list[str] = []
  327. # Toggle -> credential for the pairs that survived the payload-only
  328. # conditions and still need local state to judge.
  329. candidates: dict[str, str] = {}
  330. for key, value in values.items():
  331. if not isinstance(key, str) or not key:
  332. continue
  333. if _is_blocked_setting_key(key):
  334. blocked.append(key)
  335. continue
  336. if _is_protected_setting_key(key):
  337. protected.append(key)
  338. continue
  339. credential = _COMPANION_CREDENTIALS.get(key)
  340. if credential is None:
  341. continue
  342. # Turning something *off* is always safe to write.
  343. if not _setting_value_is_true(value):
  344. continue
  345. # Expressed as the predicate rather than assumed, so the map cannot
  346. # go quietly inert if _SECRET_KEY_HINTS is ever edited: a credential
  347. # the restore is willing to write travels with its toggle.
  348. if not _is_blocked_setting_key(credential):
  349. continue
  350. # The backup itself carried no credential here. An anonymous MQTT
  351. # broker and an anonymous LDAP bind are both legitimate configs
  352. # (mqtt_relay.py and ldap_service.py pass empty credentials straight
  353. # through), so refusing this toggle would be a false positive — the
  354. # restore is not producing anything weaker than the backup.
  355. if not _is_usable_credential(values.get(credential)):
  356. continue
  357. candidates[key] = credential
  358. if not candidates:
  359. return _SettingsPlan(blocked=tuple(blocked), protected=tuple(protected))
  360. # One SELECT covering both halves of every candidate pair.
  361. wanted = set(candidates) | set(candidates.values())
  362. rows = await db.execute(select(Settings).where(Settings.key.in_(wanted)))
  363. local = {row.key: row.value for row in rows.scalars().all()}
  364. companion: list[str] = []
  365. for toggle, credential in candidates.items():
  366. if _is_usable_credential(local.get(credential)):
  367. continue
  368. env_name = _COMPANION_CREDENTIAL_ENV.get(credential)
  369. if env_name and _is_usable_credential(os.environ.get(env_name)):
  370. continue
  371. # Already on locally with no credential: the exposure pre-dates this
  372. # restore, so refusing changes nothing and "left switched off" would
  373. # be a lie.
  374. if _setting_value_is_true(local.get(toggle)):
  375. continue
  376. companion.append(toggle)
  377. return _SettingsPlan(
  378. blocked=tuple(blocked),
  379. protected=tuple(protected),
  380. companion=tuple(companion),
  381. )
  382. async def preview(self, db: AsyncSession, config: GitHubBackupConfig, ref: str = "HEAD") -> dict:
  383. """Report which categories a commit contains, and how much is in each.
  384. Takes a session because the settings count depends on local state — see
  385. ``_plan_settings``. ``ref`` stays keyword-friendly for callers.
  386. """
  387. resolved, error, commit_info = await self._resolve_ref(config, ref)
  388. if resolved is None:
  389. return {"success": False, "message": error, "ref": ref, "categories": []}
  390. backend = get_provider_backend(config.provider)
  391. client = await self._get_client()
  392. tree = await backend.list_tree(
  393. repo_url=config.repository_url, token=config.access_token, ref=resolved, client=client
  394. )
  395. if not tree.get("success"):
  396. return {"success": False, "message": tree.get("message") or "Could not list the commit", "ref": resolved}
  397. available: list[str] = tree.get("paths") or []
  398. # One batched read covers metadata plus every category payload.
  399. wanted = [METADATA_PATH] if METADATA_PATH in available else []
  400. for category in RestoreCategory:
  401. wanted.extend(self._category_paths(category, available))
  402. fetched = await backend.fetch_files(
  403. repo_url=config.repository_url,
  404. token=config.access_token,
  405. ref=resolved,
  406. paths=wanted,
  407. client=client,
  408. # The listing above already built this map; without it the GitHub
  409. # family would GET the same recursive tree a second time.
  410. blob_shas=tree.get("blob_shas") or None,
  411. )
  412. if not fetched.get("success"):
  413. return {
  414. "success": False,
  415. "message": fetched.get("message") or "Could not read the commit contents",
  416. "ref": resolved,
  417. }
  418. parsed, bad_paths = self._parse_json_files(fetched.get("files") or {})
  419. metadata = parsed.get(METADATA_PATH)
  420. metadata_version = metadata.get("version") if isinstance(metadata, dict) else None
  421. categories = []
  422. for category in RestoreCategory:
  423. paths = self._category_paths(category, available)
  424. if not paths:
  425. categories.append(
  426. self._category_entry(category, False, 0, _Detail("notPresent", "Not present in this backup commit"))
  427. )
  428. continue
  429. unreadable = [p for p in paths if p in bad_paths]
  430. if unreadable:
  431. joined = ", ".join(unreadable)
  432. categories.append(
  433. self._category_entry(
  434. category,
  435. False,
  436. 0,
  437. _Detail("unreadableJson", f"Unreadable JSON: {joined}", {"paths": joined}),
  438. )
  439. )
  440. continue
  441. count, detail = await self._count_items(db, category, parsed)
  442. categories.append(self._category_entry(category, True, count, detail))
  443. if commit_info is None:
  444. commit_info = await self._describe_commit(config, resolved)
  445. return {
  446. "success": True,
  447. "message": "OK",
  448. "ref": resolved,
  449. "commit": commit_info,
  450. "metadata_version": metadata_version,
  451. "categories": categories,
  452. }
  453. @staticmethod
  454. def _category_entry(category: RestoreCategory, available: bool, item_count: int, detail: _Detail | None) -> dict:
  455. """Shape one ``GitHubRestorePreviewCategory``, translated detail included."""
  456. return {
  457. "category": category,
  458. "available": available,
  459. "item_count": item_count,
  460. "detail": detail.message if detail else None,
  461. "detail_code": detail.code if detail else None,
  462. "detail_params": detail.params if detail else {},
  463. }
  464. async def _count_items(
  465. self, db: AsyncSession, category: RestoreCategory, parsed: dict
  466. ) -> tuple[int, _Detail | None]:
  467. """Count restorable items for ``category`` and describe any caveat."""
  468. if category == RestoreCategory.SETTINGS:
  469. payload = parsed.get(SETTINGS_PATH)
  470. values = payload.get("settings") if isinstance(payload, dict) else None
  471. if not isinstance(values, dict):
  472. return 0, _Detail("settingsNoPayload", "No settings in payload")
  473. # Every refusal is subtracted so the count matches what the restore
  474. # actually writes. The wording calls out the credential ones (what a
  475. # user might expect to come back) and the companion ones (a
  476. # behaviour change worth explaining before it happens); the auth
  477. # policy keys stay unmentioned on purpose.
  478. plan = await self._plan_settings(db, values)
  479. detail = None
  480. if plan.companion:
  481. detail = _Detail(
  482. "settingsCompanionWillSkip",
  483. f"{len(plan.blocked)} credential-like key(s) will be skipped, and "
  484. f"{len(plan.companion)} switch(es) that depend on them will be left off",
  485. {"count": len(plan.blocked), "companion": len(plan.companion)},
  486. )
  487. elif plan.blocked:
  488. detail = _Detail(
  489. "settingsCredentialsWillSkip",
  490. f"{len(plan.blocked)} credential-like keys will be skipped",
  491. {"count": len(plan.blocked)},
  492. )
  493. return len(values) - plan.refused_count, detail
  494. if category == RestoreCategory.SPOOLS:
  495. payload = parsed.get(SPOOLS_PATH)
  496. spools = payload.get("spools") if isinstance(payload, dict) else None
  497. usage_payload = parsed.get(SPOOL_USAGE_PATH)
  498. usage = usage_payload.get("usage_history") if isinstance(usage_payload, dict) else None
  499. count = len(spools) if isinstance(spools, list) else 0
  500. detail = None
  501. if isinstance(usage, list) and usage:
  502. detail = _Detail("spoolsUsageCount", f"plus {len(usage)} usage records", {"count": len(usage)})
  503. return count, detail
  504. if category == RestoreCategory.ARCHIVES:
  505. payload = parsed.get(ARCHIVES_PATH)
  506. archives = payload.get("archives") if isinstance(payload, dict) else None
  507. count = len(archives) if isinstance(archives, list) else 0
  508. return count, _Detail(
  509. "archivesMetadataOnly", "Metadata only — 3MF files and thumbnails are not in a Git backup"
  510. )
  511. if category == RestoreCategory.KPROFILES:
  512. total = 0
  513. serials = set()
  514. for path, payload in parsed.items():
  515. match = _KPROFILE_PATH_RE.match(path)
  516. if not match or not isinstance(payload, dict):
  517. continue
  518. serials.add(match.group(1))
  519. profiles = payload.get("profiles")
  520. if isinstance(profiles, list):
  521. total += len(profiles)
  522. detail = None
  523. if serials:
  524. detail = _Detail("kprofilesPrinterCount", f"across {len(serials)} printer(s)", {"count": len(serials)})
  525. return total, detail
  526. return 0, None
  527. # --- Restore -----------------------------------------------------------
  528. async def run_restore(
  529. self,
  530. config_id: int,
  531. ref: str,
  532. categories: list[RestoreCategory],
  533. overwrite_existing: bool = False,
  534. ) -> dict:
  535. """Apply selected categories from one backup commit."""
  536. # Import locally to avoid a module-level cycle: the backup service takes
  537. # the mirror-image lock against us.
  538. from backend.app.services.github_backup import github_backup_service
  539. # The lock serialises two concurrent restores; the backup side has no
  540. # lock of its own, and relies on this region staying await-free after the
  541. # acquisition. Both flags are plain bools on one event loop, so with no
  542. # suspension point between the two reads and the write, the loop cannot
  543. # slip github_backup.run_backup's mirror-image check in between. Adding an
  544. # `await` below the acquisition and above `self._running_restore = True`
  545. # would let a backup and a restore run at once.
  546. async with self._lock:
  547. if self._running_restore:
  548. return {"success": False, "message": "A restore is already running", "results": {}}
  549. if github_backup_service.is_running:
  550. return {
  551. "success": False,
  552. "message": "A backup is currently running. Wait for it to finish before restoring.",
  553. "results": {},
  554. }
  555. self._running_restore = True
  556. log_id = None
  557. try:
  558. async with async_session() as db:
  559. result = await db.execute(select(GitHubBackupConfig).where(GitHubBackupConfig.id == config_id))
  560. config = result.scalar_one_or_none()
  561. if not config:
  562. return {"success": False, "message": "Configuration not found", "results": {}}
  563. self._progress = "Resolving commit..."
  564. resolved, error, _ = await self._resolve_ref(config, ref)
  565. if resolved is None:
  566. return {"success": False, "message": error, "results": {}}
  567. log = GitHubBackupLog(config_id=config_id, status="running", trigger="restore", commit_sha=resolved)
  568. db.add(log)
  569. await db.commit()
  570. await db.refresh(log)
  571. log_id = log.id
  572. try:
  573. payload, error = await self._read_categories(config, resolved, categories)
  574. if error:
  575. raise RuntimeError(error)
  576. settings_keys_written: set[str] = set()
  577. results = await self._apply(db, payload, categories, overwrite_existing, settings_keys_written)
  578. await db.commit()
  579. # After the commit: this reconnects the relay, which is not
  580. # something to do on values that could still roll back.
  581. settings_tally = results.get(RestoreCategory.SETTINGS.value)
  582. if settings_tally is not None:
  583. self._progress = "Reconnecting the MQTT relay..."
  584. await self._reconfigure_mqtt_relay(db, settings_keys_written, settings_tally)
  585. total_restored = sum(tally.restored for tally in results.values())
  586. any_failed = any(tally.failed for tally in results.values())
  587. log.status = "failed" if any_failed and total_restored == 0 else "success"
  588. log.completed_at = datetime.now(timezone.utc)
  589. log.files_changed = total_restored
  590. if any_failed:
  591. log.error_message = "Some items could not be restored — see the restore result for detail"
  592. await db.commit()
  593. return {
  594. "success": True,
  595. "message": f"Restored {total_restored} item(s) from {resolved[:7]}",
  596. "log_id": log_id,
  597. "ref": resolved,
  598. "results": {name: tally.as_dict() for name, tally in results.items()},
  599. }
  600. except Exception as e:
  601. # Rolls back whatever is still uncommitted. That is every
  602. # database category unless K-profiles were also selected, in
  603. # which case _apply has already committed them before talking
  604. # to the printers — see the comment there.
  605. logger.exception("Restore failed for config %s ref %s", config_id, resolved)
  606. await db.rollback()
  607. log.status = "failed"
  608. log.completed_at = datetime.now(timezone.utc)
  609. log.error_message = str(e)[:1000]
  610. await db.commit()
  611. return {"success": False, "message": str(e), "log_id": log_id, "ref": resolved, "results": {}}
  612. finally:
  613. self._running_restore = False
  614. self._progress = None
  615. async def _read_categories(
  616. self, config: GitHubBackupConfig, ref: str, categories: list[RestoreCategory]
  617. ) -> tuple[dict, str]:
  618. """Fetch and parse just the files the requested categories need."""
  619. backend = get_provider_backend(config.provider)
  620. client = await self._get_client()
  621. self._progress = "Listing backup contents..."
  622. tree = await backend.list_tree(
  623. repo_url=config.repository_url, token=config.access_token, ref=ref, client=client
  624. )
  625. if not tree.get("success"):
  626. return {}, tree.get("message") or "Could not list the commit"
  627. available: list[str] = tree.get("paths") or []
  628. wanted: list[str] = []
  629. for category in categories:
  630. wanted.extend(self._category_paths(category, available))
  631. if not wanted:
  632. return {}, "None of the selected categories are present in that commit"
  633. self._progress = "Downloading backup files..."
  634. fetched = await backend.fetch_files(
  635. repo_url=config.repository_url,
  636. token=config.access_token,
  637. ref=ref,
  638. paths=wanted,
  639. client=client,
  640. blob_shas=tree.get("blob_shas") or None,
  641. )
  642. if not fetched.get("success"):
  643. return {}, fetched.get("message") or "Could not read the commit contents"
  644. parsed, bad = self._parse_json_files(fetched.get("files") or {})
  645. if bad:
  646. return {}, f"Backup contains unreadable JSON: {', '.join(sorted(bad))}"
  647. return parsed, ""
  648. async def _apply(
  649. self,
  650. db: AsyncSession,
  651. payload: dict,
  652. categories: list[RestoreCategory],
  653. overwrite: bool,
  654. settings_keys_written: set[str] | None = None,
  655. ) -> dict[str, _CategoryTally]:
  656. """Apply categories in dependency order and return per-category tallies.
  657. ``settings_keys_written``, if given, collects the setting keys actually
  658. written, for the caller's post-commit side effects (see
  659. ``_reconfigure_mqtt_relay``).
  660. """
  661. results: dict[str, _CategoryTally] = {}
  662. archive_id_map: dict[int, int] = {}
  663. # Archives first: spool usage history references archive_id.
  664. if RestoreCategory.ARCHIVES in categories:
  665. self._progress = "Restoring print archives..."
  666. tally = _CategoryTally()
  667. await self._restore_archives(db, payload.get(ARCHIVES_PATH), overwrite, tally, archive_id_map)
  668. results[RestoreCategory.ARCHIVES.value] = tally
  669. if RestoreCategory.SPOOLS in categories:
  670. self._progress = "Restoring spool inventory..."
  671. tally = _CategoryTally()
  672. await self._restore_spools(
  673. db,
  674. payload.get(SPOOLS_PATH),
  675. payload.get(SPOOL_USAGE_PATH),
  676. overwrite,
  677. tally,
  678. archive_id_map,
  679. )
  680. results[RestoreCategory.SPOOLS.value] = tally
  681. if RestoreCategory.SETTINGS in categories:
  682. self._progress = "Restoring app settings..."
  683. tally = _CategoryTally()
  684. await self._restore_settings(
  685. db, payload.get(SETTINGS_PATH), overwrite, tally, keys_written=settings_keys_written
  686. )
  687. results[RestoreCategory.SETTINGS.value] = tally
  688. # Last, because it leaves the database and publishes over MQTT.
  689. if RestoreCategory.KPROFILES in categories:
  690. # Commit the database categories FIRST, and not just for tidiness.
  691. # Everything above has already autoflushed its INSERTs, so SQLite is
  692. # holding the single write transaction — and _restore_kprofiles then
  693. # awaits get_kprofiles per printer per nozzle, which is
  694. # timeout=5.0 * max_retries=3, i.e. up to ~15 s each against an
  695. # unresponsive printer. busy_timeout is 15 s (core/database.py), so a
  696. # farm with a couple of sulking printers would hold the writer past
  697. # it and every concurrent writer in the app would fail with
  698. # "database is locked".
  699. #
  700. # The cost is that a K-profile failure no longer rolls back the
  701. # categories that already succeeded. That is the correct trade
  702. # anyway: extrusion_cali_set has left for the printer by then and
  703. # cannot be rolled back either, so a rollback would only have made
  704. # the database disagree with the hardware.
  705. await db.commit()
  706. self._progress = "Sending K-profiles to printers..."
  707. tally = _CategoryTally()
  708. await self._restore_kprofiles(db, payload, tally)
  709. results[RestoreCategory.KPROFILES.value] = tally
  710. return results
  711. # --- Per-category appliers --------------------------------------------
  712. async def _restore_archives(
  713. self,
  714. db: AsyncSession,
  715. payload,
  716. overwrite: bool,
  717. tally: _CategoryTally,
  718. id_map: dict[int, int],
  719. ) -> None:
  720. archives = payload.get("archives") if isinstance(payload, dict) else None
  721. if not isinstance(archives, list):
  722. tally.note("noData", "No data of this kind in this backup")
  723. return
  724. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  725. valid_projects = set((await db.execute(select(Project.id))).scalars().all())
  726. # Ownership decides visibility, not just attribution: an archive with a
  727. # NULL created_by_id is a 404 to every caller without archives:read_all
  728. # (_ensure_archive_visible fails closed on it) and never appears in the
  729. # ownership-scoped list queries. Hoisted like the two above.
  730. #
  731. # Note this is the one place a raw backup id is reused, against the
  732. # module's own rule at the top of the file. Users have no natural key the
  733. # backup carries today, and the id is validated rather than trusted, so a
  734. # *stale* id clears instead of pointing somewhere wrong. What it cannot
  735. # catch is a live id belonging to a different person on a different
  736. # instance. Collecting username and resolving on that would close it;
  737. # raised with the maintainer rather than decided here.
  738. valid_users = set((await db.execute(select(User.id))).scalars().all())
  739. # Only metadata is backed up, never the 3MF/thumbnail bytes, and
  740. # print_archives.file_path is NOT NULL — so inserted rows get an empty
  741. # path and are history-only. Say so once rather than per row.
  742. warned_files = False
  743. for entry in archives:
  744. if not isinstance(entry, dict):
  745. tally.failed += 1
  746. continue
  747. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  748. started_at = _parse_dt(entry.get("started_at"))
  749. existing = await self._find_archive(db, entry, started_at)
  750. fields = {
  751. "print_name": entry.get("print_name"),
  752. "print_time_seconds": entry.get("print_time_seconds"),
  753. "filament_used_grams": entry.get("filament_used_grams"),
  754. "filament_type": entry.get("filament_type"),
  755. "filament_color": entry.get("filament_color"),
  756. "layer_height": entry.get("layer_height"),
  757. "total_layers": entry.get("total_layers"),
  758. "nozzle_diameter": entry.get("nozzle_diameter"),
  759. "bed_temperature": entry.get("bed_temperature"),
  760. "nozzle_temperature": entry.get("nozzle_temperature"),
  761. "sliced_for_model": entry.get("sliced_for_model"),
  762. "status": entry.get("status") or "completed",
  763. "started_at": started_at,
  764. "completed_at": _parse_dt(entry.get("completed_at")),
  765. "makerworld_url": entry.get("makerworld_url"),
  766. "designer": entry.get("designer"),
  767. "external_url": entry.get("external_url"),
  768. "is_favorite": bool(entry.get("is_favorite")),
  769. "tags": entry.get("tags"),
  770. "notes": entry.get("notes"),
  771. "cost": entry.get("cost"),
  772. "failure_reason": entry.get("failure_reason"),
  773. "quantity": entry.get("quantity") or 1,
  774. "energy_kwh": entry.get("energy_kwh"),
  775. "energy_cost": entry.get("energy_cost"),
  776. # A soft-deleted archive is still in the backup (its row is kept
  777. # so stats keep counting it), so carry the flag across or the
  778. # restore turns something the user deleted back into a visible
  779. # archive. Backups written before this key existed have no
  780. # deleted_at, and those rows can only come back live.
  781. "deleted_at": _parse_dt(entry.get("deleted_at")),
  782. }
  783. printer_id = entry.get("printer_id")
  784. if printer_id is not None and printer_id not in valid_printers:
  785. tally.note(
  786. "archivesPrinterMissing", "Some archives referenced printers that no longer exist — link cleared"
  787. )
  788. printer_id = None
  789. project_id = entry.get("project_id")
  790. if project_id is not None and project_id not in valid_projects:
  791. tally.note(
  792. "archivesProjectMissing", "Some archives referenced projects that no longer exist — link cleared"
  793. )
  794. project_id = None
  795. created_by_id = entry.get("created_by_id")
  796. if created_by_id is not None and created_by_id not in valid_users:
  797. # Coerced rather than failing the row: the archive is still worth
  798. # having, and an admin can reassign it. Said out loud because a
  799. # cleared owner is not silent-safe — the archive becomes visible
  800. # only to archives:read_all until someone does.
  801. tally.note(
  802. "archivesOwnerCleared",
  803. "Some archives referenced users that no longer exist — owner cleared, so they are "
  804. "visible only to users with the archives:read_all permission until an admin reassigns them",
  805. )
  806. created_by_id = None
  807. fields["printer_id"] = printer_id
  808. fields["project_id"] = project_id
  809. fields["created_by_id"] = created_by_id
  810. if existing is not None:
  811. if old_id is not None:
  812. id_map[old_id] = existing.id
  813. if not overwrite:
  814. tally.skipped += 1
  815. continue
  816. # Overwrite means "make the local row match the backup", which
  817. # includes un-deleting one the user deleted after the backup was
  818. # taken. Legitimate, but not obvious from a restored/skipped
  819. # count, so say it.
  820. if existing.deleted_at is not None and fields["deleted_at"] is None:
  821. tally.note(
  822. "archivesUndeleted",
  823. "Archive(s) deleted since the backup are visible again — overwrite was on",
  824. )
  825. for key, value in fields.items():
  826. setattr(existing, key, value)
  827. tally.restored += 1
  828. continue
  829. if not warned_files:
  830. tally.note(
  831. "archivesMetadataOnly",
  832. "Restored archives carry metadata only — the 3MF and thumbnail files are not in a Git backup",
  833. )
  834. warned_files = True
  835. row = PrintArchive(
  836. filename=entry.get("filename") or "restored-from-backup",
  837. file_path="",
  838. file_size=entry.get("file_size") or 0,
  839. content_hash=entry.get("content_hash"),
  840. **fields,
  841. )
  842. created_at = _parse_dt(entry.get("created_at"))
  843. if created_at is not None:
  844. row.created_at = created_at
  845. db.add(row)
  846. await db.flush()
  847. if old_id is not None:
  848. id_map[old_id] = row.id
  849. tally.restored += 1
  850. async def _find_archive(self, db: AsyncSession, entry: dict, started_at: datetime | None) -> PrintArchive | None:
  851. """Match a backed-up archive to a local row by natural key.
  852. ``started_at`` is nullable and genuinely NULL for a whole class of rows —
  853. the re-slice path in ``library.py`` constructs ``PrintArchive`` without
  854. one — so it cannot be *required* by the key. It narrows the match instead:
  855. a backed-up row with no ``started_at`` matches a local row that has none
  856. either. Requiring it meant those archives never matched, so each restore
  857. re-inserted them as duplicates and overwrite mode could never update them.
  858. ``content_hash`` identifies the sliced file on its own, which is why it is
  859. the branch allowed to run without a ``started_at``; ``filename`` is too
  860. weak for that (re-slices share it) and still requires one. Two backed-up
  861. rows sharing a hash *and* having no ``started_at`` are indistinguishable
  862. in the backup, so they collapse onto one local row — better than
  863. duplicating both on every restore.
  864. Soft-deleted rows are matched deliberately: there is no ``deleted_at``
  865. filter here because the row still exists, and matching it is what stops a
  866. restore inserting a live duplicate of an archive the user has deleted.
  867. """
  868. started_predicate = PrintArchive.started_at == started_at if started_at else PrintArchive.started_at.is_(None)
  869. content_hash = entry.get("content_hash")
  870. if content_hash:
  871. result = await db.execute(
  872. select(PrintArchive).where(PrintArchive.content_hash == content_hash, started_predicate)
  873. )
  874. row = result.scalars().first()
  875. if row is not None:
  876. return row
  877. filename = entry.get("filename")
  878. if filename and started_at:
  879. result = await db.execute(select(PrintArchive).where(PrintArchive.filename == filename, started_predicate))
  880. return result.scalars().first()
  881. return None
  882. async def _restore_spools(
  883. self,
  884. db: AsyncSession,
  885. inventory,
  886. usage_payload,
  887. overwrite: bool,
  888. tally: _CategoryTally,
  889. archive_id_map: dict[int, int],
  890. ) -> None:
  891. spools = inventory.get("spools") if isinstance(inventory, dict) else None
  892. if not isinstance(spools, list):
  893. tally.note("noData", "No data of this kind in this backup")
  894. return
  895. spool_id_map: dict[int, int] = {}
  896. tags_kept = 0
  897. for entry in spools:
  898. if not isinstance(entry, dict):
  899. tally.failed += 1
  900. continue
  901. old_id = entry.get("id") if isinstance(entry.get("id"), int) else None
  902. existing, matched_on = await self._find_spool(db, entry)
  903. fields = {
  904. "material": entry.get("material") or "PLA",
  905. "subtype": entry.get("subtype"),
  906. "color_name": entry.get("color_name"),
  907. "rgba": entry.get("rgba"),
  908. "brand": entry.get("brand"),
  909. "label_weight": entry.get("label_weight") or 1000,
  910. "core_weight": entry.get("core_weight") or 250,
  911. "weight_used": entry.get("weight_used") or 0,
  912. "weight_locked": bool(entry.get("weight_locked")),
  913. "slicer_filament": entry.get("slicer_filament"),
  914. "slicer_filament_name": entry.get("slicer_filament_name"),
  915. "nozzle_temp_min": entry.get("nozzle_temp_min"),
  916. "nozzle_temp_max": entry.get("nozzle_temp_max"),
  917. "note": entry.get("note"),
  918. "cost_per_kg": entry.get("cost_per_kg"),
  919. "tag_uid": entry.get("tag_uid"),
  920. "tray_uuid": entry.get("tray_uuid"),
  921. "data_origin": entry.get("data_origin"),
  922. "tag_type": entry.get("tag_type"),
  923. "archived_at": _parse_dt(entry.get("archived_at")),
  924. }
  925. if existing is not None:
  926. if old_id is not None:
  927. spool_id_map[old_id] = existing.id
  928. if not overwrite:
  929. tally.skipped += 1
  930. continue
  931. tags_kept += await self._guard_tag_overwrite(db, existing, fields, matched_on)
  932. for key, value in fields.items():
  933. setattr(existing, key, value)
  934. tally.restored += 1
  935. continue
  936. row = Spool(**fields)
  937. # Carry the original created_at across. Without it the row would be
  938. # stamped "now", and the composite fallback in _find_spool (which
  939. # keys on created_at) would miss on a second restore and insert a
  940. # duplicate instead of matching.
  941. created_at = _parse_dt(entry.get("created_at"))
  942. if created_at is not None:
  943. row.created_at = created_at
  944. db.add(row)
  945. await db.flush()
  946. if old_id is not None:
  947. spool_id_map[old_id] = row.id
  948. tally.restored += 1
  949. if tags_kept:
  950. tally.note(
  951. "spoolTagKept",
  952. f"{tags_kept} spool tag(s) left as they are — the backup would have cleared a tag that "
  953. "has since been scanned, or moved one onto a second spool.",
  954. count=tags_kept,
  955. )
  956. await self._restore_spool_usage(db, usage_payload, tally, spool_id_map, archive_id_map)
  957. async def _find_spool(self, db: AsyncSession, entry: dict) -> tuple[Spool | None, str | None]:
  958. """Match a backed-up spool to a local row, and say which key matched.
  959. Physical identity first (an RFID/Bambu tag is the spool), then a
  960. descriptive composite including ``created_at`` so two otherwise
  961. identical spools added at different times stay distinct.
  962. The second element names the column that matched — ``"tag_uid"``,
  963. ``"tray_uuid"`` or ``None`` for the composite. ``_guard_tag_overwrite``
  964. needs it: the matched column holds the incoming value by definition, so
  965. it is the *other* one that overwrite can corrupt.
  966. """
  967. tag_uid = entry.get("tag_uid")
  968. if tag_uid:
  969. result = await db.execute(select(Spool).where(Spool.tag_uid == tag_uid))
  970. row = result.scalars().first()
  971. if row is not None:
  972. return row, "tag_uid"
  973. tray_uuid = entry.get("tray_uuid")
  974. if tray_uuid:
  975. result = await db.execute(select(Spool).where(Spool.tray_uuid == tray_uuid))
  976. row = result.scalars().first()
  977. if row is not None:
  978. return row, "tray_uuid"
  979. created_at = _parse_dt(entry.get("created_at"))
  980. if created_at is None:
  981. return None, None
  982. result = await db.execute(
  983. select(Spool).where(
  984. Spool.created_at == created_at,
  985. Spool.material == (entry.get("material") or "PLA"),
  986. Spool.brand == entry.get("brand"),
  987. Spool.subtype == entry.get("subtype"),
  988. Spool.color_name == entry.get("color_name"),
  989. )
  990. )
  991. return result.scalars().first(), None
  992. @staticmethod
  993. async def _guard_tag_overwrite(db: AsyncSession, existing: Spool, fields: dict, matched_on: str | None) -> int:
  994. """Remove tag columns from ``fields`` that an overwrite would corrupt.
  995. ``tag_uid`` and ``tray_uuid`` are both in ``fields`` and overwrite is a
  996. blanket ``setattr`` loop, so a spool matched on one key gets the backup's
  997. *other* key written onto it. Neither column has a unique constraint
  998. (``models/spool.py``, and no unique index in the migrations), so nothing
  999. errors — a duplicate tag simply appears, after which ``_find_spool``'s
  1000. ``.first()`` is non-deterministic and an AMS tag lookup resolves to an
  1001. arbitrary one of the two spools. The same loop can also *clear* a tag the
  1002. user has scanned since the backup was taken, when the backup entry holds
  1003. ``None``.
  1004. Two refusals, and the row is otherwise overwritten as normal:
  1005. * the incoming value is empty and the local row has one — the backup
  1006. predates the scan, so the local tag is the newer fact;
  1007. * the incoming value is already held by a different local spool — writing
  1008. it would create the duplicate described above.
  1009. Returns how many columns were left alone, so the caller can say so in the
  1010. tally rather than doing it silently.
  1011. """
  1012. kept = 0
  1013. for column in ("tag_uid", "tray_uuid"):
  1014. # The column we matched on already holds the incoming value.
  1015. if column == matched_on:
  1016. continue
  1017. incoming = fields.get(column)
  1018. current = getattr(existing, column)
  1019. if incoming == current:
  1020. continue
  1021. if not incoming:
  1022. if current:
  1023. fields.pop(column)
  1024. kept += 1
  1025. continue
  1026. clash = await db.execute(
  1027. select(Spool.id).where(getattr(Spool, column) == incoming, Spool.id != existing.id)
  1028. )
  1029. if clash.scalars().first() is not None:
  1030. fields.pop(column)
  1031. kept += 1
  1032. return kept
  1033. async def _restore_spool_usage(
  1034. self,
  1035. db: AsyncSession,
  1036. usage_payload,
  1037. tally: _CategoryTally,
  1038. spool_id_map: dict[int, int],
  1039. archive_id_map: dict[int, int],
  1040. ) -> None:
  1041. usage = usage_payload.get("usage_history") if isinstance(usage_payload, dict) else None
  1042. if not isinstance(usage, list) or not usage:
  1043. return
  1044. valid_printers = set((await db.execute(select(Printer.id))).scalars().all())
  1045. unresolved = 0
  1046. unlinked_archives = 0
  1047. for entry in usage:
  1048. if not isinstance(entry, dict):
  1049. tally.failed += 1
  1050. continue
  1051. old_spool_id = entry.get("spool_id")
  1052. spool_id = spool_id_map.get(old_spool_id) if isinstance(old_spool_id, int) else None
  1053. if spool_id is None:
  1054. # The parent spool never made it into the map: the backup's spool
  1055. # list didn't include it, or its entry carried no integer id. A
  1056. # spool that was merely *skipped* (matched locally, overwrite off)
  1057. # is mapped a few lines up in _restore_spools, so it never lands
  1058. # here — which is why the note below offers no remedy.
  1059. unresolved += 1
  1060. tally.skipped += 1
  1061. continue
  1062. created_at = _parse_dt(entry.get("created_at"))
  1063. # Usage history has no natural key of its own, so dedupe on the
  1064. # tuple that makes a consumption event unique in practice.
  1065. existing = await db.execute(
  1066. select(SpoolUsageHistory).where(
  1067. SpoolUsageHistory.spool_id == spool_id,
  1068. SpoolUsageHistory.created_at == created_at,
  1069. SpoolUsageHistory.weight_used == (entry.get("weight_used") or 0),
  1070. SpoolUsageHistory.print_name == entry.get("print_name"),
  1071. )
  1072. )
  1073. if existing.scalars().first() is not None:
  1074. tally.skipped += 1
  1075. continue
  1076. printer_id = entry.get("printer_id")
  1077. if printer_id is not None and printer_id not in valid_printers:
  1078. printer_id = None
  1079. old_archive_id = entry.get("archive_id")
  1080. archive_id = archive_id_map.get(old_archive_id) if isinstance(old_archive_id, int) else None
  1081. if archive_id is None and isinstance(old_archive_id, int):
  1082. # Restoring spools without archives leaves archive_id_map empty,
  1083. # so every "this print consumed that spool" link is dropped — the
  1084. # local archive may well exist, but its payload wasn't fetched,
  1085. # so there is no natural key here to match it on. Nor is it
  1086. # repairable by a later archives-only restore: the dedupe key
  1087. # above doesn't include archive_id, so these rows are recognised
  1088. # as already-present and skipped. Worth telling the user while
  1089. # they can still redo the run with both categories ticked.
  1090. unlinked_archives += 1
  1091. row = SpoolUsageHistory(
  1092. spool_id=spool_id,
  1093. printer_id=printer_id,
  1094. print_name=entry.get("print_name"),
  1095. archive_id=archive_id,
  1096. weight_used=entry.get("weight_used") or 0,
  1097. percent_used=entry.get("percent_used") or 0,
  1098. status=entry.get("status") or "completed",
  1099. cost=entry.get("cost"),
  1100. )
  1101. if created_at is not None:
  1102. row.created_at = created_at
  1103. db.add(row)
  1104. tally.restored += 1
  1105. if unresolved:
  1106. tally.note(
  1107. "spoolUsageUnresolved",
  1108. f"{unresolved} usage record(s) skipped — their spool is not in this backup's "
  1109. "spool list, so there is nothing to attach them to.",
  1110. count=unresolved,
  1111. )
  1112. if unlinked_archives:
  1113. tally.note(
  1114. "spoolUsageUnlinked",
  1115. f"{unlinked_archives} usage record(s) restored without their print-history link — "
  1116. "select Print archives alongside Spool inventory to keep it.",
  1117. count=unlinked_archives,
  1118. )
  1119. async def _restore_settings(
  1120. self,
  1121. db: AsyncSession,
  1122. payload,
  1123. overwrite: bool,
  1124. tally: _CategoryTally,
  1125. keys_written: set[str] | None = None,
  1126. ) -> None:
  1127. values = payload.get("settings") if isinstance(payload, dict) else None
  1128. if not isinstance(values, dict):
  1129. tally.note("noData", "No data of this kind in this backup")
  1130. return
  1131. # Planned before the first write, so the companion rule reads genuinely
  1132. # pre-restore local state, and so the preview and this run classify the
  1133. # payload identically.
  1134. plan = await self._plan_settings(db, values)
  1135. refused = plan.refused
  1136. for key, value in values.items():
  1137. if not isinstance(key, str) or not key:
  1138. tally.failed += 1
  1139. continue
  1140. if key in refused:
  1141. # Refusals are reported in the notes and nowhere else. They are
  1142. # already outside the preview's item count, and the preview is
  1143. # the number the user was shown, so counting them here would
  1144. # make restored + skipped + failed exceed it. The two skips
  1145. # below stay counted because they depend on this run's flags,
  1146. # which the preview cannot see.
  1147. continue
  1148. if value is None:
  1149. tally.skipped += 1
  1150. continue
  1151. result = await db.execute(select(Settings).where(Settings.key == key))
  1152. existing = result.scalar_one_or_none()
  1153. if existing is not None:
  1154. if not overwrite:
  1155. tally.skipped += 1
  1156. continue
  1157. existing.value = str(value)
  1158. tally.restored += 1
  1159. if keys_written is not None:
  1160. keys_written.add(key)
  1161. continue
  1162. db.add(Settings(key=key, value=str(value)))
  1163. tally.restored += 1
  1164. if keys_written is not None:
  1165. keys_written.add(key)
  1166. if plan.blocked:
  1167. tally.note(
  1168. "settingsCredentialsSkipped",
  1169. f"{len(plan.blocked)} credential-like key(s) skipped — re-enter secrets manually",
  1170. count=len(plan.blocked),
  1171. )
  1172. if plan.protected:
  1173. tally.note(
  1174. "settingsAuthSkipped",
  1175. f"{len(plan.protected)} authentication setting(s) skipped — change those in Settings > "
  1176. "Authentication so the lockout checks still run",
  1177. count=len(plan.protected),
  1178. )
  1179. if plan.companion:
  1180. keys = ", ".join(sorted(plan.companion))
  1181. tally.note(
  1182. "settingsCompanionSkipped",
  1183. f"{keys} left switched off — the credential each one needs cannot be restored from a "
  1184. "backup and this instance has none stored, so switching them on would leave the "
  1185. "integration unauthenticated",
  1186. keys=keys,
  1187. count=len(plan.companion),
  1188. )
  1189. async def _reconfigure_mqtt_relay(self, db: AsyncSession, keys_written: set[str], tally: _CategoryTally) -> None:
  1190. """Push restored mqtt_* settings into the live relay.
  1191. The relay reads its broker config once, at configure() time — the
  1192. settings PUT handler reconfigures it for exactly this reason
  1193. (api/routes/settings.py). Writing the rows alone left the relay on the
  1194. pre-restore broker until the next backend restart while the UI showed
  1195. the restored values, which is the one way a restore could look applied
  1196. and not be.
  1197. Called after the commit, never before: configure() tears the connection
  1198. down and rebuilds it, so it must not run against values a later failure
  1199. could roll back. Only mqtt_password can't come back this way (the
  1200. credential blocklist skips it) — the row already in the database is
  1201. reused, so an unchanged broker keeps working.
  1202. """
  1203. if not _MQTT_SETTING_KEYS & keys_written:
  1204. return
  1205. try:
  1206. from backend.app.services.mqtt_relay import mqtt_relay
  1207. rows = await db.execute(select(Settings).where(Settings.key.in_(_MQTT_SETTING_KEYS)))
  1208. stored = {s.key: s.value for s in rows.scalars().all()}
  1209. # Same shape and defaults the settings PUT handler builds.
  1210. await mqtt_relay.configure(
  1211. {
  1212. "mqtt_enabled": (stored.get("mqtt_enabled") or "false") == "true",
  1213. "mqtt_broker": stored.get("mqtt_broker") or "",
  1214. "mqtt_port": int(stored.get("mqtt_port") or "1883"),
  1215. "mqtt_username": stored.get("mqtt_username") or "",
  1216. "mqtt_password": stored.get("mqtt_password") or "",
  1217. "mqtt_topic_prefix": stored.get("mqtt_topic_prefix") or "bambuddy",
  1218. "mqtt_use_tls": (stored.get("mqtt_use_tls") or "false") == "true",
  1219. }
  1220. )
  1221. except Exception:
  1222. # Same call is best-effort in the settings PUT handler: the rows are
  1223. # committed either way, and a broker that refuses the new config
  1224. # must not turn a successful restore into a failed one. Noted rather
  1225. # than swallowed silently, so the user knows to restart.
  1226. logger.warning("Could not reconfigure the MQTT relay after a settings restore", exc_info=True)
  1227. tally.note(
  1228. "settingsMqttRelayFailed",
  1229. "MQTT settings restored, but the relay could not be reconnected — restart Bambuddy",
  1230. )
  1231. async def _restore_kprofiles(self, db: AsyncSession, payload: dict, tally: _CategoryTally) -> None:
  1232. by_serial: dict[str, list[tuple[str, dict]]] = {}
  1233. for path, content in payload.items():
  1234. match = _KPROFILE_PATH_RE.match(path)
  1235. if not match or not isinstance(content, dict):
  1236. continue
  1237. by_serial.setdefault(match.group(1), []).append((match.group(2), content))
  1238. if not by_serial:
  1239. tally.note("noData", "No data of this kind in this backup")
  1240. return
  1241. result = await db.execute(select(Printer))
  1242. printers = {p.serial_number: p for p in result.scalars().all() if p.serial_number}
  1243. # Overwrite is not offered for K-profiles: extrusion_cali_set replaces
  1244. # the profile occupying a slot, so writing is always an overwrite on the
  1245. # printer side.
  1246. tally.note("kprofilesAlwaysOverwrite", "K-profiles always overwrite the matching slot on the printer")
  1247. tally.note(
  1248. "kprofilesAckUnreliable",
  1249. "The printer's acknowledgement is not reliable — verify the profiles on the printer",
  1250. )
  1251. for serial, entries in sorted(by_serial.items()):
  1252. profile_total = sum(len(c.get("profiles") or []) for _, c in entries)
  1253. printer = printers.get(serial)
  1254. if printer is None:
  1255. tally.skipped += profile_total
  1256. tally.note("kprofilesPrinterMissing", f"No printer with serial {serial} — skipped", serial=serial)
  1257. continue
  1258. client = printer_manager.get_client(printer.id)
  1259. if not client or not client.state.connected:
  1260. tally.skipped += profile_total
  1261. tally.note(
  1262. "kprofilesPrinterOffline",
  1263. f"{printer.name} ({serial}) is not connected — skipped",
  1264. printer=printer.name,
  1265. serial=serial,
  1266. )
  1267. continue
  1268. for nozzle, content in sorted(entries):
  1269. profiles = content.get("profiles")
  1270. if not isinstance(profiles, list) or not profiles:
  1271. continue
  1272. if nozzle not in _KNOWN_NOZZLES:
  1273. tally.note(
  1274. "kprofilesUnknownNozzle",
  1275. f"Unexpected nozzle diameter {nozzle} for {serial} — sent as-is",
  1276. nozzle=nozzle,
  1277. serial=serial,
  1278. )
  1279. # The backup's slot_id is a cali_idx, and cali_idx is as
  1280. # unstable as the autoincrement ids we already refuse to reuse
  1281. # for spools and archives: editing a profile in Bambuddy is a
  1282. # delete-then-add on a single-nozzle printer, which re-keys it.
  1283. # Addressing extrusion_cali_set at a slot that no longer exists
  1284. # is a silent no-op — the printer drops it and we would still
  1285. # report the profile restored. So resolve the live index first.
  1286. current = await self._current_kprofile_index(client, nozzle, serial)
  1287. profile_dicts = []
  1288. unmatched = 0
  1289. for p in profiles:
  1290. if not isinstance(p, dict):
  1291. continue
  1292. match = self._match_kprofile(p, current)
  1293. if match is None:
  1294. unmatched += 1
  1295. profile_dicts.append(
  1296. {
  1297. "filament_id": p.get("filament_id", ""),
  1298. "name": p.get("name", ""),
  1299. "k_value": p.get("k_value", "0.020000"),
  1300. "nozzle_id": p.get("nozzle_id"),
  1301. "extruder_id": p.get("extruder_id", 0),
  1302. # Prefer the live setting_id when we matched: it is
  1303. # what the printer currently associates with the slot.
  1304. "setting_id": (match.setting_id if match else None) or p.get("setting_id"),
  1305. # cali_idx -1 tells the printer to add a new profile
  1306. # rather than address a slot that isn't there.
  1307. "cali_idx": match.slot_id if match else -1,
  1308. # Only consulted for the generated-setting_id
  1309. # fallback; cali_idx above takes precedence.
  1310. "slot_id": 0,
  1311. }
  1312. )
  1313. if not profile_dicts:
  1314. continue
  1315. if unmatched:
  1316. tally.note(
  1317. "kprofilesUnmatched",
  1318. f"{unmatched} profile(s) for {nozzle} had no counterpart on {printer.name} "
  1319. "— added as new profiles",
  1320. count=unmatched,
  1321. nozzle=nozzle,
  1322. printer=printer.name,
  1323. )
  1324. try:
  1325. sent = client.set_kprofiles_batch(profile_dicts, nozzle)
  1326. except Exception as e:
  1327. logger.warning("K-profile restore failed for %s nozzle %s: %s", serial, nozzle, e)
  1328. sent = False
  1329. if sent:
  1330. tally.restored += len(profile_dicts)
  1331. else:
  1332. tally.failed += len(profile_dicts)
  1333. tally.note(
  1334. "kprofilesSendFailed",
  1335. f"Failed to send {nozzle} profiles to {printer.name} ({serial})",
  1336. nozzle=nozzle,
  1337. printer=printer.name,
  1338. serial=serial,
  1339. )
  1340. @staticmethod
  1341. async def _current_kprofile_index(client, nozzle: str, serial: str) -> list:
  1342. """Read the printer's live profiles for one nozzle.
  1343. Best-effort: a read failure degrades to "nothing matched", which makes
  1344. every profile an add rather than aborting the restore.
  1345. """
  1346. try:
  1347. return list(await client.get_kprofiles(nozzle_diameter=nozzle) or [])
  1348. except Exception as e:
  1349. logger.warning("Could not read live K-profiles for %s nozzle %s: %s", serial, nozzle, e)
  1350. return []
  1351. @staticmethod
  1352. def _match_kprofile(entry: dict, current: list):
  1353. """Find the live profile a backed-up entry corresponds to.
  1354. ``setting_id`` is the filament preset the profile was calibrated for and
  1355. is the strongest signal; a delete-then-add edit regenerates it, so fall
  1356. back to the display name, which Bambuddy's own editor preserves.
  1357. Both are scoped by ``filament_id`` — the same preset on a different
  1358. filament is a different profile.
  1359. """
  1360. filament_id = entry.get("filament_id")
  1361. if not filament_id:
  1362. return None
  1363. candidates = [c for c in current if c.filament_id == filament_id]
  1364. if not candidates:
  1365. return None
  1366. setting_id = entry.get("setting_id")
  1367. if setting_id:
  1368. for c in candidates:
  1369. if c.setting_id == setting_id:
  1370. return c
  1371. name = entry.get("name")
  1372. if name:
  1373. for c in candidates:
  1374. if c.name == name:
  1375. return c
  1376. # Exactly one profile for this filament and no better discriminator:
  1377. # treat it as the same profile rather than duplicating it.
  1378. return candidates[0] if len(candidates) == 1 else None
  1379. # Singleton instance
  1380. github_restore_service = GitHubRestoreService()