github_restore.py 93 KB

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