github_restore.py 80 KB

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