github_restore.py 107 KB

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