github_restore.py 84 KB

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