github_restore.py 106 KB

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