github_restore.py 113 KB

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