print_log.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. from datetime import datetime
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from backend.app.models.print_log import PrintLogEntry
  8. logger = logging.getLogger(__name__)
  9. async def write_log_entry(
  10. db: AsyncSession,
  11. *,
  12. status: str,
  13. archive_id: int | None = None,
  14. print_name: str | None = None,
  15. printer_name: str | None = None,
  16. printer_id: int | None = None,
  17. started_at: datetime | None = None,
  18. completed_at: datetime | None = None,
  19. filament_type: str | None = None,
  20. filament_color: str | None = None,
  21. filament_used_grams: float | None = None,
  22. cost: float | None = None,
  23. energy_kwh: float | None = None,
  24. energy_cost: float | None = None,
  25. failure_reason: str | None = None,
  26. thumbnail_path: str | None = None,
  27. created_by_id: int | None = None,
  28. created_by_username: str | None = None,
  29. reconciled: bool = False,
  30. ) -> PrintLogEntry:
  31. """Write a print log entry.
  32. ``reconciled`` marks a synthetic completion written when a stale
  33. ``status="printing"`` archive is closed out at reconnect. Its real end time
  34. is unknown — the print stopped somewhere during the disconnect and
  35. ``completed_at`` is only the reconnect moment — so ``completed_at -
  36. started_at`` would bank the entire disconnect gap as print time, adding
  37. hundreds of fictitious hours across a farm of stale rows (#2592). For those
  38. entries we store an explicit ``0`` ("no measured runtime") rather than a
  39. fabricated duration; the stats total trusts a stored 0 instead of
  40. recomputing from the stale timestamps.
  41. """
  42. if reconciled:
  43. duration: int | None = 0
  44. elif started_at and completed_at:
  45. duration = int((completed_at - started_at).total_seconds())
  46. else:
  47. duration = None
  48. entry = PrintLogEntry(
  49. archive_id=archive_id,
  50. print_name=print_name,
  51. printer_name=printer_name,
  52. printer_id=printer_id,
  53. status=status,
  54. started_at=started_at,
  55. completed_at=completed_at,
  56. duration_seconds=duration,
  57. filament_type=filament_type,
  58. filament_color=filament_color,
  59. filament_used_grams=filament_used_grams,
  60. cost=cost,
  61. energy_kwh=energy_kwh,
  62. energy_cost=energy_cost,
  63. failure_reason=failure_reason,
  64. thumbnail_path=thumbnail_path,
  65. created_by_id=created_by_id,
  66. created_by_username=created_by_username,
  67. )
  68. db.add(entry)
  69. await db.flush()
  70. return entry