github_restore.py 98 KB

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