github_restore.py 95 KB

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