print_log.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. """Service for writing independent print log entries.
  2. Log entries are written to a separate table and never touch archives or queue items.
  3. """
  4. import logging
  5. import uuid
  6. from collections.abc import Set as AbstractSet
  7. from datetime import datetime, timezone
  8. from types import SimpleNamespace
  9. from sqlalchemy import delete, func, or_, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  12. from backend.app.utils.local_time import utcnow_naive
  13. logger = logging.getLogger(__name__)
  14. def wear_cost_for_run(duration_seconds: int | None, wear_cost_per_hour: float | None) -> float | None:
  15. """Printer wear for one run: its duration at the printer's hourly rate (#694).
  16. None when the printer has no rate or the run has no measured duration (a
  17. reconciled run stores 0 because its real end time is unknown).
  18. """
  19. if not isinstance(wear_cost_per_hour, int | float) or not isinstance(duration_seconds, int):
  20. return None
  21. if wear_cost_per_hour <= 0 or duration_seconds <= 0:
  22. return None
  23. return round(duration_seconds / 3600 * wear_cost_per_hour, 3)
  24. async def write_log_entry(
  25. db: AsyncSession,
  26. *,
  27. status: str,
  28. archive_id: int | None = None,
  29. queue_item_id: int | None = None,
  30. print_name: str | None = None,
  31. plate_id: int | None = None,
  32. printer_name: str | None = None,
  33. printer_id: int | None = None,
  34. started_at: datetime | None = None,
  35. completed_at: datetime | None = None,
  36. filament_type: str | None = None,
  37. filament_color: str | None = None,
  38. filament_used_grams: float | None = None,
  39. cost: float | None = None,
  40. energy_kwh: float | None = None,
  41. energy_cost: float | None = None,
  42. wear_cost_per_hour: float | None = None,
  43. failure_reason: str | None = None,
  44. thumbnail_path: str | None = None,
  45. created_by_id: int | None = None,
  46. created_by_username: str | None = None,
  47. reconciled: bool = False,
  48. duration_unmeasured: bool = False,
  49. ended_offline: bool = False,
  50. replaces_offline_stop: bool = False,
  51. ) -> PrintLogEntry:
  52. """Write a print log entry.
  53. ``reconciled`` marks a synthetic completion written when a stale
  54. ``status="printing"`` archive is closed out at reconnect. Its real end time
  55. is unknown — the print stopped somewhere during the disconnect and
  56. ``completed_at`` is only the reconnect moment — so ``completed_at -
  57. started_at`` would bank the entire disconnect gap as print time, adding
  58. hundreds of fictitious hours across a farm of stale rows (#2592). For those
  59. entries we store an explicit ``0`` ("no measured runtime") rather than a
  60. fabricated duration; the stats total trusts a stored 0 instead of
  61. recomputing from the stale timestamps.
  62. ``duration_unmeasured`` marks a run closed at reconnect, whose times were
  63. not measured (#3310): ``completed_at`` is its start plus the slicer's
  64. estimate, or the reconnect. The time accuracy leaves it out.
  65. ``ended_offline`` marks a run logged by a stop that could not reach the
  66. printer. A print's end passes ``replaces_offline_stop``: it may then fill
  67. such a run of its printer, the printer's latest, which its archive's start
  68. (another plate's since, maybe) and its closed queue item no longer find.
  69. """
  70. if replaces_offline_stop:
  71. entry = await run_being_ended(db, archive_id, printer_id, started_at)
  72. else:
  73. entry = await _entry_of_this_run(db, archive_id, printer_id, started_at)
  74. filling_open_run = entry is not None and entry.status == RUN_OPEN
  75. if entry is not None and entry.started_at is not None:
  76. # The run's own start. The archive's is its latest run's: another
  77. # plate of it may have started on another printer since.
  78. started_at = entry.started_at
  79. if reconciled:
  80. duration: int | None = 0
  81. elif started_at and completed_at:
  82. duration = int((_utc(completed_at) - _utc(started_at)).total_seconds())
  83. else:
  84. duration = None
  85. fields = {
  86. "archive_id": archive_id,
  87. "queue_item_id": queue_item_id,
  88. "print_name": print_name,
  89. "plate_id": plate_id,
  90. "printer_name": printer_name,
  91. "printer_id": printer_id,
  92. "status": status,
  93. "started_at": started_at,
  94. "completed_at": completed_at,
  95. "duration_seconds": duration,
  96. "filament_type": filament_type,
  97. "filament_color": filament_color,
  98. "filament_used_grams": filament_used_grams,
  99. "cost": cost,
  100. "energy_kwh": energy_kwh,
  101. "energy_cost": energy_cost,
  102. "wear_cost": wear_cost_for_run(duration, wear_cost_per_hour),
  103. "duration_unmeasured": True if duration_unmeasured else None,
  104. "failure_reason": failure_reason,
  105. "thumbnail_path": thumbnail_path,
  106. "created_by_id": created_by_id,
  107. "created_by_username": created_by_username,
  108. "ended_offline": True if ended_offline else None,
  109. }
  110. if filling_open_run:
  111. # When the run was logged, as a run written at its end always was:
  112. # the date ranges of statistics and the print log go by it.
  113. fields["created_at"] = utcnow_naive()
  114. if entry is None:
  115. if archive_id is not None and started_at is not None and status != RUN_OPEN:
  116. # Shadow check while the run's start moves over (archive redesign):
  117. # every print start that binds an archive opens its run, so a run
  118. # ending without one is a start path that does not yet.
  119. logger.info("[RUN] Archive %s: no run was opened when the print started; written at its end", archive_id)
  120. entry = PrintLogEntry(**fields)
  121. db.add(entry)
  122. elif entry.status != status:
  123. if entry.status == RUN_OPEN and None not in (entry.plate_id, plate_id) and entry.plate_id != plate_id:
  124. logger.warning(
  125. "[RUN] Archive %s: the run opened for plate %s ends as plate %s", archive_id, entry.plate_id, plate_id
  126. )
  127. # The run ended differently from how it was first logged: a print
  128. # stopped while its printer was offline that finished after all. The
  129. # real outcome replaces the stop rather than counting the run twice.
  130. for name, value in fields.items():
  131. if value is None and name in _KEPT_WHEN_NOT_REPORTED:
  132. continue
  133. setattr(entry, name, value)
  134. # The same outcome reported again (a repeated completion after a reconnect)
  135. # changes nothing: the repeat no longer has the run's tracked usage, and the
  136. # entry may have been edited or given its energy since.
  137. await db.flush()
  138. if archive_id is not None:
  139. await mirror_latest_run(db, archive_id)
  140. return entry
  141. # What the archive card shows of its prints, its latest run's.
  142. _MIRRORED_FROM_RUN = ("status", "started_at", "completed_at", "failure_reason")
  143. async def mirror_latest_run(db: AsyncSession, archive_id: int) -> None:
  144. """Give the archive its latest run's outcome, by start: status, times,
  145. failure reason, plate and verdict. Only once none of its runs is printing: until
  146. the print's start, end, reconcile and timelapse look their print up by
  147. its run, they still go by the archive's printer, status and start, which
  148. a print running elsewhere must not move under them. While one prints,
  149. the archive keeps what its prints' starts and ends wrote. An archive
  150. without runs keeps its own (uploaded, or printed before runs were
  151. logged). Does not commit."""
  152. from backend.app.models.archive import PrintArchive
  153. archive = await db.get(PrintArchive, archive_id)
  154. if archive is None:
  155. return
  156. runs = select(PrintLogEntry).where(PrintLogEntry.archive_id == archive_id)
  157. still_printing = await db.scalar(
  158. runs.with_only_columns(PrintLogEntry.id)
  159. .where(PrintLogEntry.status == RUN_OPEN)
  160. .limit(1)
  161. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  162. )
  163. if still_printing is not None:
  164. return
  165. latest = await db.scalar(
  166. runs.order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc()).limit(1)
  167. )
  168. if latest is None:
  169. return
  170. for name in _MIRRORED_FROM_RUN:
  171. setattr(archive, name, getattr(latest, name))
  172. if latest.plate_id is not None:
  173. archive.plate_id = latest.plate_id
  174. # Its outcome verdict too (#1898), once the run holds its own: it has one,
  175. # or was opened at its start with its opt-in. A run logged before then
  176. # may never have been given the archive's, which stays. Runs logged
  177. # before they kept the verdict's provenance have only its value: the
  178. # archive's own provenance stays with that same verdict.
  179. owns_verdict = latest.user_verdict is not None or latest.confirm_requested is not None
  180. if owns_verdict and (latest.user_verdict != archive.user_verdict or latest.user_verdict_source is not None):
  181. archive.user_verdict = latest.user_verdict
  182. archive.user_verdict_source = latest.user_verdict_source
  183. archive.user_verdict_at = latest.user_verdict_at
  184. async def mirror_archive_cost(
  185. db: AsyncSession, archive, previous_cost: float | None, *, skip_runs: AbstractSet[int] = frozenset()
  186. ) -> None:
  187. """Give the archive's newest run the archive's new cost, if it had the old one.
  188. Statistics, project totals and batch sums read a run's cost. A completed
  189. run without its own spool price took the archive's (or none), so a new
  190. archive cost belongs to it too. A run its spools priced keeps that price,
  191. and a failed or cancelled run keeps its own: it printed only part of it.
  192. A run in ``skip_runs`` was given its own new cost already.
  193. """
  194. entry = await db.scalar(
  195. select(PrintLogEntry).where(PrintLogEntry.archive_id == archive.id).order_by(PrintLogEntry.id.desc()).limit(1)
  196. )
  197. if entry is None or entry.id in skip_runs:
  198. return
  199. if entry.status == "completed" and entry.cost in (None, previous_cost):
  200. entry.cost = archive.cost
  201. async def other_runs_of(db: AsyncSession, archive) -> int:
  202. """How many log entries *archive* has from runs other than its current one.
  203. The archive card keeps its first run's figures; a run whose own entry is
  204. already written (its stop, logged while the printer was offline) is still
  205. the first run.
  206. """
  207. # Without a start time or printer on the archive, ``!= None`` reads as
  208. # ``IS NOT NULL``: every entry is another run's.
  209. query = select(func.count(PrintLogEntry.id)).where(
  210. PrintLogEntry.archive_id == archive.id,
  211. or_(
  212. PrintLogEntry.started_at.is_(None),
  213. PrintLogEntry.started_at != archive.started_at,
  214. PrintLogEntry.printer_id.is_(None),
  215. PrintLogEntry.printer_id != archive.printer_id,
  216. ),
  217. )
  218. return await db.scalar(query) or 0
  219. # Who and what the run was, which a repeated report may no longer know: a
  220. # completion that finds the queue item already closed reports none. Its
  221. # outcome (status, reason, grams, cost) is replaced as reported.
  222. _KEPT_WHEN_NOT_REPORTED = frozenset(
  223. {
  224. "queue_item_id",
  225. "print_name",
  226. "plate_id",
  227. "printer_name",
  228. "thumbnail_path",
  229. "created_by_id",
  230. "created_by_username",
  231. }
  232. )
  233. def _utc(moment: datetime) -> datetime:
  234. """Naive UTC, as the columns store it; an aware time is converted first."""
  235. return moment.astimezone(timezone.utc).replace(tzinfo=None) if moment.tzinfo else moment
  236. async def _entry_of_this_run(
  237. db: AsyncSession,
  238. archive_id: int | None,
  239. printer_id: int | None,
  240. started_at: datetime | None,
  241. *,
  242. exact: bool = False,
  243. ) -> PrintLogEntry | None:
  244. """The entry already written for this run, if any.
  245. A run is its archive, printer and start time together: plates of one
  246. archive printing on two printers share the archive row (and can share its
  247. start time), and a reprint starts at a new time. The queue item is not
  248. part of it: a repeated completion finds the item already closed and
  249. reports none. Without an archive or printer a run can't be told apart,
  250. so nothing is matched.
  251. A run opened at its start is also found as the archive's run open on the
  252. printer, unless ``exact``: the archive's start is its latest run's, and
  253. another plate of it may have started on another printer since.
  254. """
  255. if archive_id is None or printer_id is None:
  256. return None
  257. if started_at is None:
  258. return None if exact else await _open_run_on(db, archive_id, printer_id)
  259. query = (
  260. select(PrintLogEntry)
  261. .where(
  262. PrintLogEntry.archive_id == archive_id,
  263. PrintLogEntry.printer_id == printer_id,
  264. PrintLogEntry.started_at == started_at,
  265. )
  266. # The run opened when the print started is the one this fills in.
  267. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  268. )
  269. entry = (await db.scalars(query.order_by(PrintLogEntry.id.desc()).limit(1))).first()
  270. # The archive's start is its latest run's. With another plate of it
  271. # started on another printer since, this printer's run is found as the
  272. # one open there.
  273. if entry is not None or exact:
  274. return entry
  275. return await _open_run_on(db, archive_id, printer_id)
  276. async def run_being_ended(
  277. db: AsyncSession, archive_id: int | None, printer_id: int | None, started_at: datetime | None
  278. ) -> PrintLogEntry | None:
  279. """The run a print's end fills in (``write_log_entry`` with
  280. ``replaces_offline_stop``): the one written for it, else the one a stop
  281. logged while the printer was offline. Billing charges the same run."""
  282. entry = await _entry_of_this_run(db, archive_id, printer_id, started_at)
  283. if entry is None and archive_id is not None and printer_id is not None:
  284. entry = await _stopped_while_offline(db, archive_id, printer_id)
  285. return entry
  286. async def _stopped_while_offline(db: AsyncSession, archive_id: int, printer_id: int) -> PrintLogEntry | None:
  287. """The run a print's real end replaces after a stop logged while the
  288. printer was offline: the printer's latest run, when it is of this
  289. archive and was ended that way. A printer prints one thing at a time, so
  290. any later run there, of any file, means that print is long over."""
  291. latest = await db.scalar(
  292. select(PrintLogEntry)
  293. .where(PrintLogEntry.printer_id == printer_id)
  294. .order_by(PrintLogEntry.started_at.desc().nulls_last(), PrintLogEntry.id.desc())
  295. .limit(1)
  296. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  297. )
  298. if latest is not None and latest.archive_id == archive_id and latest.ended_offline:
  299. return latest
  300. return None
  301. async def _open_run_on(db: AsyncSession, archive_id: int, printer_id: int) -> PrintLogEntry | None:
  302. """The run of the archive open on the printer: there is one at most, a
  303. printer prints one thing at a time (``open_run``)."""
  304. return await db.scalar(
  305. select(PrintLogEntry)
  306. .where(
  307. PrintLogEntry.archive_id == archive_id,
  308. PrintLogEntry.printer_id == printer_id,
  309. PrintLogEntry.status == RUN_OPEN,
  310. )
  311. .order_by(PrintLogEntry.id.desc())
  312. .limit(1)
  313. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  314. )
  315. async def open_run_on_printer(
  316. db: AsyncSession, printer_id: int, *, subtask_id: str | None = None
  317. ) -> PrintLogEntry | None:
  318. """The run open on the printer: the print it is running now, which
  319. Bambuddy saw start. One at most (``open_run``). With ``subtask_id``, only
  320. a run of that job."""
  321. query = select(PrintLogEntry).where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  322. if subtask_id is not None:
  323. query = query.where(PrintLogEntry.subtask_id == subtask_id)
  324. return await db.scalar(
  325. query.order_by(PrintLogEntry.id.desc()).limit(1).execution_options(**{INCLUDE_OPEN_RUNS: True})
  326. )
  327. async def discard_open_runs(db: AsyncSession, printer_id: int) -> None:
  328. """Drop the runs left open on the printer by prints that ended without
  329. their end reaching a run: cancelled at the next start as stale, or whose
  330. archive was deleted. As before runs were opened at the start, such a
  331. print leaves no run. Does not commit."""
  332. await db.execute(
  333. delete(PrintLogEntry)
  334. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  335. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  336. )
  337. async def open_run(
  338. db: AsyncSession,
  339. archive,
  340. *,
  341. printer_id: int,
  342. printer_name: str | None = None,
  343. plate_id: int | None = None,
  344. subtask_id: str | None = None,
  345. ) -> PrintLogEntry | None:
  346. """The run of the print that just started on ``archive``, written now with
  347. the open status; its end fills it in (``write_log_entry``).
  348. Idempotent: a print start seen again (a restart resuming the print, a
  349. repeated report) finds the run it opened: by the printer's job
  350. (``subtask_id``) when it has one, else keyed as its end will key it, by
  351. archive, printer and start time. The queue item running it, if any, gives
  352. the dispatch's own billing run and cost centre; a run without one gets its
  353. own billing run id, so each print of the archive is charged as its own.
  354. Does not commit.
  355. """
  356. from backend.app.models.print_queue import PrintQueueItem
  357. if archive.started_at is None:
  358. return None
  359. if subtask_id:
  360. # The same job seen again: its run, though another plate of the
  361. # archive may have started on another printer since and moved the
  362. # archive's start.
  363. running = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  364. if running is not None and running.archive_id == archive.id:
  365. return running
  366. # Only the run of this very start: one still open on the printer from an
  367. # earlier start of the archive is of a print that ended unseen.
  368. entry = await _entry_of_this_run(db, archive.id, printer_id, archive.started_at, exact=True)
  369. if entry is not None:
  370. return entry
  371. # A printer prints one thing at a time: a run still open on it is of a
  372. # print that ended without its end reaching it.
  373. await discard_open_runs(db, printer_id)
  374. item = await db.scalar(
  375. select(PrintQueueItem)
  376. .where(
  377. PrintQueueItem.archive_id == archive.id,
  378. PrintQueueItem.printer_id == printer_id,
  379. PrintQueueItem.status == "printing",
  380. )
  381. .order_by(PrintQueueItem.id.desc())
  382. .limit(1)
  383. )
  384. entry = PrintLogEntry(
  385. status=RUN_OPEN,
  386. archive_id=archive.id,
  387. queue_item_id=item.id if item is not None else None,
  388. print_name=archive.print_name,
  389. plate_id=plate_id if plate_id is not None else archive.plate_id,
  390. printer_name=printer_name,
  391. printer_id=printer_id,
  392. started_at=archive.started_at,
  393. filament_type=archive.filament_type,
  394. filament_color=archive.filament_color,
  395. thumbnail_path=archive.thumbnail_path,
  396. created_by_id=archive.created_by_id,
  397. subtask_id=archive.subtask_id,
  398. # Not the archive's: that is the latest dispatch's, or the id an
  399. # earlier print of the archive was charged under.
  400. billing_run_id=(item.billing_run_id if item is not None else None) or str(uuid.uuid4()),
  401. cost_center_id=(item.cost_center_id if item is not None else None) or archive.cost_center_id,
  402. confirm_requested=archive.confirm_requested,
  403. quantity=archive.quantity,
  404. )
  405. db.add(entry)
  406. await db.flush()
  407. return entry
  408. async def mirror_energy_start(db: AsyncSession, archive, *, printer_id: int) -> None:
  409. """Copy the archive's energy start reading onto the run it was taken for.
  410. Does not commit."""
  411. entry = await _entry_of_this_run(db, archive.id, printer_id, archive.started_at)
  412. if entry is None or entry.status != RUN_OPEN:
  413. return
  414. for name in _ENERGY_START:
  415. setattr(entry, name, getattr(archive, name))
  416. _ENERGY_START = ("energy_start_kwh", "energy_start_at", "energy_start_plug_id", "energy_start_price")
  417. def _reading_taken_for(archive, entry: PrintLogEntry) -> bool:
  418. """Whether the archive's energy start reading was taken for this run: the
  419. archive's latest start is this run's (another plate of it started since
  420. takes the reading), and it was read at or after it (an earlier print's is
  421. older). A reading without its time (taken before #1251) goes by the
  422. start alone."""
  423. if archive.energy_start_kwh is None:
  424. return False
  425. if entry.started_at is None or archive.started_at is None:
  426. return False
  427. if _utc(archive.started_at) != _utc(entry.started_at):
  428. return False
  429. return archive.energy_start_at is None or _utc(archive.energy_start_at) >= _utc(entry.started_at)
  430. async def run_needs_energy_start(db: AsyncSession, archive, *, printer_id: int) -> bool:
  431. """Whether the print running on the archive still lacks its energy start
  432. reading, at a resume. Its run's, or the archive's taken for it (copied
  433. onto the run then), counts; the archive's of an earlier print does not.
  434. Without a run, the archive's, as before. Does not commit."""
  435. entry = await _entry_of_this_run(db, archive.id, printer_id, archive.started_at)
  436. if entry is None or entry.status != RUN_OPEN:
  437. return archive.energy_start_kwh is None
  438. if entry.energy_start_kwh is not None:
  439. return False
  440. if _reading_taken_for(archive, entry):
  441. for name in _ENERGY_START:
  442. setattr(entry, name, getattr(archive, name))
  443. return False
  444. return True
  445. def energy_start_of(entry: PrintLogEntry | None, archive) -> SimpleNamespace | None:
  446. """The energy start reading of the run that ended: its own. Without one,
  447. the archive's only when taken for this run (a run written only at its
  448. end, or none written): another plate of the archive may have started on
  449. another printer since and taken it."""
  450. source = None
  451. if entry is not None and entry.energy_start_kwh is not None:
  452. source = entry
  453. elif entry is None or _reading_taken_for(archive, entry):
  454. source = archive
  455. if source is None or source.energy_start_kwh is None:
  456. return None
  457. return SimpleNamespace(
  458. kwh=source.energy_start_kwh,
  459. at=source.energy_start_at,
  460. plug_id=source.energy_start_plug_id,
  461. price=source.energy_start_price,
  462. )
  463. async def record_archive_wear(db: AsyncSession, archive, entry: PrintLogEntry) -> None:
  464. """Copy a run's wear cost onto its archive when it is the archive's first run.
  465. Same rule as energy (#1378): the archive shows its first print, and a
  466. reprint's wear stays on its own log entry (#694). ``entry`` must already be
  467. flushed, so it counts as one of the archive's runs.
  468. """
  469. if entry.wear_cost is None:
  470. return
  471. runs = await db.scalar(select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive.id))
  472. if (runs or 0) <= 1:
  473. archive.wear_cost = entry.wear_cost