print_queue.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from datetime import datetime
  2. from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text, func
  3. from sqlalchemy.orm import Mapped, mapped_column, relationship
  4. from backend.app.core.database import Base
  5. class PrintQueueItem(Base):
  6. """Print queue item for scheduled/queued prints."""
  7. __tablename__ = "print_queue"
  8. id: Mapped[int] = mapped_column(primary_key=True)
  9. # Links
  10. printer_id: Mapped[int | None] = mapped_column(ForeignKey("printers.id", ondelete="CASCADE"), nullable=True)
  11. # Target printer model for model-based assignment (mutually exclusive with printer_id)
  12. # When set, scheduler assigns to any idle printer of matching model
  13. target_model: Mapped[str | None] = mapped_column(String(50), nullable=True)
  14. # Target location filter for model-based assignment (only used with target_model)
  15. # When set, only printers in this location are considered
  16. target_location: Mapped[str | None] = mapped_column(String(100), nullable=True)
  17. # Required filament types for model-based assignment (JSON array, e.g., '["PLA", "PETG"]')
  18. # Used by scheduler to validate printer has compatible filaments loaded
  19. required_filament_types: Mapped[str | None] = mapped_column(Text, nullable=True)
  20. # Waiting reason - explains why a model-based job hasn't started yet
  21. # Set by scheduler when no matching printer is available
  22. waiting_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
  23. # Either archive_id OR library_file_id must be set (archive created at print start from library file)
  24. archive_id: Mapped[int | None] = mapped_column(ForeignKey("print_archives.id", ondelete="CASCADE"), nullable=True)
  25. library_file_id: Mapped[int | None] = mapped_column(
  26. ForeignKey("library_files.id", ondelete="CASCADE"), nullable=True
  27. )
  28. cost_center_id: Mapped[int | None] = mapped_column(
  29. ForeignKey("cost_centers.id", ondelete="SET NULL"), nullable=True
  30. )
  31. estimated_cost: Mapped[float | None] = mapped_column(Float, nullable=True)
  32. project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id", ondelete="SET NULL"), nullable=True)
  33. batch_id: Mapped[int | None] = mapped_column(ForeignKey("print_batches.id", ondelete="SET NULL"), nullable=True)
  34. # Scheduling
  35. position: Mapped[int] = mapped_column(Integer, default=0) # Queue order
  36. scheduled_time: Mapped[datetime | None] = mapped_column(DateTime, nullable=True) # None = ASAP
  37. manual_start: Mapped[bool] = mapped_column(Boolean, default=False) # Requires manual trigger to start
  38. # Conditions
  39. require_previous_success: Mapped[bool] = mapped_column(Boolean, default=False)
  40. # Power management
  41. auto_off_after: Mapped[bool] = mapped_column(Boolean, default=False) # Power off printer after print
  42. # AMS mapping: JSON array of global tray IDs for each filament slot
  43. # Format: "[5, -1, 2, -1]" where position = slot_id-1, value = global tray ID (-1 = unused)
  44. ams_mapping: Mapped[str | None] = mapped_column(Text, nullable=True)
  45. # Filament overrides for model-based assignment: JSON array of override objects
  46. # Format: '[{"slot_id": 1, "type": "PLA", "color": "#FFFFFF"}]'
  47. # Only slots with overrides are included (sparse). null = use original 3MF values.
  48. filament_overrides: Mapped[str | None] = mapped_column(Text, nullable=True)
  49. # Plate ID for multi-plate 3MF files (1-indexed, None = auto-detect/plate 1)
  50. plate_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  51. # Shortest-job-first scheduling
  52. print_time_seconds: Mapped[int | None] = mapped_column(Integer, nullable=True) # Cached from archive/library
  53. been_jumped: Mapped[bool] = mapped_column(Boolean, default=False) # Starvation guard for SJF
  54. # Auto-print G-code injection (#422)
  55. gcode_injection: Mapped[bool] = mapped_column(Boolean, default=False)
  56. # How many times the start-watchdog has reverted this item from 'printing'
  57. # back to 'pending' (#2555). A printer that accepts project_file but never
  58. # starts (#1678) used to be retried forever: upload, wait out the watchdog,
  59. # revert, upload again — burning a full 3MF transfer per cycle and, with
  60. # the queue dispatching serially, dragging every other printer's start time
  61. # out with it. The counter bounds that loop; see DISPATCH_MAX_ATTEMPTS.
  62. dispatch_attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
  63. # H2C dual-nozzle-rack slicer pick preservation (#1780). BambuStudio's
  64. # project_file MQTT command for rack-swap-capable models (O1C2 today)
  65. # carries per-filament physical nozzle position IDs in `nozzle_mapping`,
  66. # forwarded verbatim through the queue and replayed by the dispatcher so
  67. # the firmware honours the user's pick instead of falling back to
  68. # "last matching nozzle type" auto-pick. Stored as opaque JSON string
  69. # (list[int]); NULL on every other model. `nozzles_info` is a deprecated
  70. # column from the original #1780 attempt — kept nullable so old rows still
  71. # load; never written to or read from.
  72. nozzle_mapping: Mapped[str | None] = mapped_column(Text, nullable=True)
  73. nozzles_info: Mapped[str | None] = mapped_column(Text, nullable=True)
  74. # Printer-card direct uploads create transient library rows. When this is
  75. # true, the scheduler deletes the source row/files after archiving a copy.
  76. cleanup_library_after_dispatch: Mapped[bool] = mapped_column(Boolean, default=False)
  77. # Print options. bed_levelling / flow_cali / nozzle_offset_cali are tri-state
  78. # strings (off/on/auto) matching BambuStudio; "auto" = skip if recently done.
  79. # The remaining three stay boolean (BambuStudio exposes no auto for them).
  80. bed_levelling: Mapped[str] = mapped_column(String(8), default="auto")
  81. flow_cali: Mapped[str] = mapped_column(String(8), default="auto")
  82. vibration_cali: Mapped[bool] = mapped_column(Boolean, default=True)
  83. layer_inspect: Mapped[bool] = mapped_column(Boolean, default=False)
  84. timelapse: Mapped[bool] = mapped_column(Boolean, default=False)
  85. use_ams: Mapped[bool] = mapped_column(Boolean, default=True)
  86. # Nozzle offset calibration — dual-nozzle printers only, MQTT-gated (#1682)
  87. nozzle_offset_cali: Mapped[str] = mapped_column(String(8), default="auto")
  88. # Preheat / heat-soak override (#1468). 'inherit' uses the global
  89. # preheat_enabled setting; 'on' / 'off' force the per-item decision. The
  90. # chamber target falls through: per-item override → max(filament-map[loaded
  91. # tray type]) → 0 (skips chamber phase). 'inherit' + global off + override
  92. # null = no preheat. Default 'inherit' so existing queue items behave
  93. # exactly as before the migration.
  94. preheat_override: Mapped[str] = mapped_column(String(10), default="inherit")
  95. preheat_chamber_target_override: Mapped[int | None] = mapped_column(Integer, nullable=True)
  96. # Status: pending, printing, completed, failed, skipped, cancelled
  97. status: Mapped[str] = mapped_column(String(20), default="pending")
  98. # Dispatch claim (#2615). Set atomically by the scheduler the moment it
  99. # begins dispatching this row and cleared when dispatch ends. The row stays
  100. # `status='pending'` throughout the (slow) FTP upload, which left a window
  101. # where a concurrent PATCH could reassign printer_id mid-upload and split the
  102. # queue row from the archive/expected-print/physical command. While this is
  103. # set the edit routes reject changes (409) and the scheduler won't re-select
  104. # the row. Startup reconciliation clears any left over by a crash mid-dispatch
  105. # (no coroutine survives a restart), so a stale claim never wedges an item.
  106. dispatching_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  107. # Cleared by the per-printer "Resume after failure" action (#1818) so the
  108. # scheduler's `_check_previous_success` lookback skips this row. Without
  109. # this, a single `failed` or `aborted` print poisoned every later
  110. # `require_previous_success` item on the same printer forever — the
  111. # lookback excluded `skipped` but had no way to dismiss the originating
  112. # failure. The flag is per-item, not per-printer, so a fresh failure
  113. # after a resume re-gates downstream items independently.
  114. gate_acknowledged: Mapped[bool] = mapped_column(Boolean, default=False)
  115. # Set by the dispatch scheduler when the assigned spool can't satisfy
  116. # this print's per-slot filament weight (#1496). Display-only flag — the
  117. # actual deficit is recomputed live every time the user clicks ▶, so
  118. # swapping a spool to a fuller one between flag and dispatch clears the
  119. # block automatically.
  120. filament_short: Mapped[bool] = mapped_column(Boolean, default=False)
  121. # User has acknowledged the filament-shortage warning for this item
  122. # ("Print Anyway"). Set by the start route when the user passes
  123. # skip_filament_check=true, or at queue-creation time if PrintModal's
  124. # frontend deficit warning was acknowledged. Survives scheduler ticks so
  125. # the dispatch no longer bounces between "user said anyway" and
  126. # "scheduler re-flagged" (#1698-followup).
  127. skip_filament_check: Mapped[bool] = mapped_column(Boolean, default=False)
  128. # Tracking
  129. started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  130. completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
  131. error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
  132. # Timestamps
  133. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  134. # User tracking (who added this to the queue)
  135. created_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
  136. # Relationships
  137. printer: Mapped["Printer"] = relationship()
  138. archive: Mapped["PrintArchive | None"] = relationship()
  139. library_file: Mapped["LibraryFile | None"] = relationship()
  140. cost_center: Mapped["CostCenter | None"] = relationship()
  141. project: Mapped["Project | None"] = relationship(back_populates="queue_items")
  142. batch: Mapped["PrintBatch | None"] = relationship(back_populates="queue_items")
  143. created_by: Mapped["User | None"] = relationship()
  144. variants: Mapped[list["PrintQueueVariant"]] = relationship(
  145. back_populates="queue_item",
  146. cascade="all, delete-orphan",
  147. order_by="PrintQueueVariant.position",
  148. )
  149. class PrintQueueVariant(Base):
  150. """One candidate file for a queue item that may print on several models (#671).
  151. A user with an H2S and an H2C slices the same job twice and does not care
  152. which machine runs it. Each slice becomes a variant; the scheduler walks them
  153. in ``position`` order and takes the first whose model has an idle printer.
  154. **This is a snapshot, not a pointer.** The candidate list is copied from the
  155. library's variant group when the item is queued, and every per-file setting
  156. the dispatcher needs is copied with it. Two reasons:
  157. - Editing the library group afterwards must not silently change a job that is
  158. already waiting in the queue.
  159. - The per-file settings genuinely differ between candidates and are choices
  160. the user made for *this* job, not properties of the file. An H2C slice is
  161. dual-nozzle and will not have the same slot count, AMS mapping or nozzle
  162. mapping as the H2S slice of the same model.
  163. On a match the winning variant's fields are written onto the queue row before
  164. the dispatch commit, so everything downstream — upload, archive creation,
  165. print history, reprint — sees an ordinary single-file item and needs no
  166. knowledge that variants exist.
  167. Variants reference library files only. An archive records a print that already
  168. happened, of one specific file, so it is never a candidate for "which of these
  169. should we run".
  170. """
  171. __tablename__ = "print_queue_variants"
  172. id: Mapped[int] = mapped_column(primary_key=True)
  173. queue_item_id: Mapped[int] = mapped_column(
  174. ForeignKey("print_queue.id", ondelete="CASCADE"), nullable=False, index=True
  175. )
  176. # User's priority order. When two printers are idle in the same scheduler
  177. # pass, the lowest position wins — so the choice is reproducible instead of
  178. # depending on which match the matcher happened to find first.
  179. position: Mapped[int] = mapped_column(Integer, default=0)
  180. # CASCADE: deleting the file drops this candidate but leaves the item and its
  181. # other candidates alone. Losing the *last* candidate is handled by the
  182. # resolver, which holds the item pending with an explicit waiting_reason
  183. # rather than letting it sit there looking dispatchable forever.
  184. library_file_id: Mapped[int] = mapped_column(ForeignKey("library_files.id", ondelete="CASCADE"), nullable=False)
  185. # Normalized short name ("H2S"), taken from the file's own sliced_for_model
  186. # at creation, or picked by the user for a legacy file that declares none.
  187. target_model: Mapped[str] = mapped_column(String(50), nullable=False)
  188. # Per-file dispatch settings, same semantics as the identically named columns
  189. # on PrintQueueItem — see there for the formats.
  190. plate_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
  191. ams_mapping: Mapped[str | None] = mapped_column(Text, nullable=True)
  192. nozzle_mapping: Mapped[str | None] = mapped_column(Text, nullable=True)
  193. filament_overrides: Mapped[str | None] = mapped_column(Text, nullable=True)
  194. required_filament_types: Mapped[str | None] = mapped_column(Text, nullable=True)
  195. print_time_seconds: Mapped[int | None] = mapped_column(Integer, nullable=True)
  196. # How many times this candidate has been dispatched and bounced back to
  197. # pending by the start-watchdog. The resolver tries least-attempted first, so
  198. # a printer that accepts the file and never starts (#1678) hands the job to
  199. # the other machine on the next lap instead of burning the item's whole
  200. # DISPATCH_MAX_ATTEMPTS budget against the same wedged printer — which is the
  201. # entire reason the user queued an alternative.
  202. attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
  203. created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
  204. queue_item: Mapped["PrintQueueItem"] = relationship(back_populates="variants")
  205. library_file: Mapped["LibraryFile"] = relationship()
  206. from backend.app.models.archive import PrintArchive # noqa: E402
  207. from backend.app.models.finance import CostCenter # noqa: E402
  208. from backend.app.models.library import LibraryFile # noqa: E402
  209. from backend.app.models.print_batch import PrintBatch # noqa: E402
  210. from backend.app.models.printer import Printer # noqa: E402
  211. from backend.app.models.project import Project # noqa: E402
  212. from backend.app.models.user import User # noqa: E402