github_restore.py 109 KB

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