11import json
22import logging
33from importlib .metadata import entry_points
4- from typing import Any
4+ from typing import TYPE_CHECKING , Any
55
66from sqlmodel import Session as SQLModelSession , select
77
1111 GridSquareParameters ,
1212 LamellaSiteInfo ,
1313 MillingStepInfo ,
14+ MillingSteps ,
15+ StagePositionInfo ,
1416 StagePositionValues ,
1517)
1618
19+ if TYPE_CHECKING :
20+ from murfey .server .ispyb import TransportManager
21+
22+
1723logger = logging .getLogger ("murfey.workflows.fib.register_milling_progress" )
1824
1925
2026def _ensure_prerequisites (
2127 session_id : int ,
2228 instrument_name : str ,
2329 visit_name : str ,
24- site_info : LamellaSiteInfo ,
30+ project_name : str ,
31+ slot_number : int ,
32+ site_number : int ,
33+ transport_object : "TransportManager" ,
2534 murfey_db : SQLModelSession ,
2635):
2736 """
2837 Uses the FIB milling metadata provided to create the necessary DataCollectionGroup,
2938 Atlas, and GridSquare placeholders in Murfey if they don't already exist
3039
3140 """
32- # Skip this step if no TransportManager object is configured
33- if _transport_object is None :
34- logger .error ("No TransportManager object was configured" )
35- return None
36-
37- # Early exits if information needed to construct lookup tags are missing
38- if site_info .project_name is None :
39- logger .error ("Could not construct lookup tags; 'project_name' is missing" )
40- return None
41- if site_info .site_number is None :
42- logger .error ("Could not construct lookup tags; 'site_number' is missing" )
43- return None
44- site_number = site_info .site_number
45- if site_info .stage_info is None :
46- logger .error ("Could not construct lookup tags; 'stage_info' is missing" )
47- return None
48- if site_info .stage_info .preparation_site is None :
49- logger .error ("Could not construct lookup tags; 'preparation_site' is missing" )
50- return None
51- if site_info .stage_info .preparation_site .slot_number is None :
52- logger .error ("Could not construct lookup tags; 'slot_number' is missing" )
53- return None
54- slot_number = site_info .stage_info .preparation_site .slot_number
55- if site_info .site_name is None :
56- logger .error ("Could not construct lookup tags; 'site_name' is missing" )
57- return None
58-
5941 # Construct the DataCollectionGroup and GridSquare lookup tags
60- dcg_tag = f"{ site_info . project_name } --slot_{ slot_number } "
42+ dcg_tag = f"{ project_name } --slot_{ slot_number } "
6143
6244 # Determine variables to register data collection group and atlas with
6345 proposal_code = "" .join (char for char in visit_name .split ("-" )[0 ] if char .isalpha ())
@@ -111,7 +93,7 @@ def _ensure_prerequisites(
11193 .where (MurfeyDB .DataCollectionGroup .session_id == session_id )
11294 .where (MurfeyDB .DataCollectionGroup .tag == dcg_tag )
11395 ).one ()
114- grid_square_ispyb_result = _transport_object .do_insert_grid_square (
96+ grid_square_ispyb_result = transport_object .do_insert_grid_square (
11597 atlas_id = dcg_entry .atlas_id ,
11698 grid_square_id = site_number ,
11799 grid_square_parameters = GridSquareParameters (
@@ -180,27 +162,17 @@ def _ensure_prerequisites(
180162
181163
182164def _register_milling_step (
183- site_info : LamellaSiteInfo ,
165+ milling_steps : MillingSteps ,
166+ stage_info : StagePositionInfo ,
184167 grid_square : MurfeyDB .GridSquare ,
168+ transport_object : "TransportManager" ,
185169 murfey_db : SQLModelSession ,
186170):
187171 """
188172 Registers FIB milling metadata for the current lamella site as MillingStep entries
189173 in ISPyB. If successful, will proceed to create a backup copy of the inserted row
190174 in Murfey.
191175 """
192-
193- # Check if TransportManager has been configured
194- if _transport_object is None :
195- logger .error ("No TransportManager object was configured" )
196- return None
197- # Check information for milling steps is present
198- if site_info .steps is None :
199- logger .error ("No milling step info found in current message" )
200- return None
201- if site_info .stage_info is None :
202- logger .error ("No stage info found in current message" )
203- return None
204176 # Check that GridSquare has ID (for type checking)
205177 if grid_square .id is None :
206178 logger .error ("Current GridSquare entry has no ID" )
@@ -209,7 +181,7 @@ def _register_milling_step(
209181 # Iteratively go through the LamellaSiteInfo model and insert for each step
210182 for steps , stage_name in MILLING_STEP_LOOKUP :
211183 for step_name in steps :
212- step_info : MillingStepInfo | None = site_info . steps .__getattribute__ (
184+ step_info : MillingStepInfo | None = milling_steps .__getattribute__ (
213185 step_name
214186 )
215187 # Early continues if key information is missing
@@ -223,8 +195,8 @@ def _register_milling_step(
223195 logger .debug (f"No step name found for { step_name } " )
224196 continue
225197
226- stage_values : StagePositionValues | None = (
227- site_info . stage_info . __getattribute__ ( stage_name )
198+ stage_values : StagePositionValues | None = stage_info . __getattribute__ (
199+ stage_name
228200 )
229201 if stage_values is None :
230202 stage_values = StagePositionValues ()
@@ -239,7 +211,7 @@ def _register_milling_step(
239211
240212 if milling_step_entry is None :
241213 # Create a new ISPyB entry if no Murfey one is found
242- result = _transport_object .do_insert_milling_step (
214+ result = transport_object .do_insert_milling_step (
243215 # IDs
244216 recipe_name = step_info .recipe_name ,
245217 activity_name = step_info .step_name ,
@@ -301,7 +273,7 @@ def _register_milling_step(
301273 )
302274 else :
303275 # Update the existing ISPyB one if it already exists
304- result = _transport_object .do_update_milling_step (
276+ result = transport_object .do_update_milling_step (
305277 milling_step_id = milling_step_entry .id ,
306278 is_enabled = step_info .is_enabled ,
307279 status = step_info .status ,
@@ -368,20 +340,60 @@ def _register_milling_step(
368340
369341
370342def run (message : dict [str , Any ], murfey_db : SQLModelSession ):
371- # Outer try-finally block to handle database cleanup
343+ # Early exit if no TransportManager was set up
344+ if _transport_object is None :
345+ logger .error ("No TransportManager object was configured" )
346+ return {"success" : False , "requeue" : False }
347+
372348 try :
373- try :
374- # Parse and unpack incoming message
375- session_id = int (message ["session_id" ])
376- site_info = LamellaSiteInfo (** message ["site_info" ])
377- logger .debug (
378- "Received the following FIB metadata for registration:\n "
379- f"{ json .dumps (site_info .model_dump (exclude_none = True ), indent = 2 , default = str )} "
380- )
381- except Exception :
382- logger .error ("Error parsing contents of message" , exc_info = True )
383- return {"success" : False , "requeue" : False }
349+ # Parse and unpack incoming message
350+ session_id = int (message ["session_id" ])
351+ site_info = LamellaSiteInfo (** message ["site_info" ])
352+ logger .debug (
353+ "Received the following FIB metadata for registration:\n "
354+ f"{ json .dumps (site_info .model_dump (exclude_none = True ), indent = 2 , default = str )} "
355+ )
356+ except Exception :
357+ logger .error ("Error parsing contents of message" , exc_info = True )
358+ return {"success" : False , "requeue" : False }
359+
360+ # Early exits if information needed to construct lookup tags are missing
361+ # Project and site values
362+ if site_info .project_name is None :
363+ logger .error ("Could not construct lookup tags; 'project_name' is missing" )
364+ return {"success" : False , "requeue" : False }
365+ project_name = site_info .project_name
366+ if site_info .site_number is None :
367+ logger .error ("Could not construct lookup tags; 'site_number' is missing" )
368+ return {"success" : False , "requeue" : False }
369+ site_number = site_info .site_number
370+ if site_info .site_name is None :
371+ logger .error ("Could not construct lookup tags; 'site_name' is missing" )
372+ return {"success" : False , "requeue" : False }
373+ site_name = site_info .site_name
374+
375+ # Stage information
376+ if site_info .stage_info is None :
377+ logger .error ("Could not construct lookup tags; 'stage_info' is missing" )
378+ return {"success" : False , "requeue" : False }
379+ stage_info = site_info .stage_info
380+ if stage_info .preparation_site is None :
381+ logger .error ("Could not construct lookup tags; 'preparation_site' is missing" )
382+ return {"success" : False , "requeue" : False }
383+ preparation_site = stage_info .preparation_site
384+ if preparation_site .slot_number is None :
385+ logger .error ("Could not construct lookup tags; 'slot_number' is missing" )
386+ return {"success" : False , "requeue" : False }
387+ slot_number = preparation_site .slot_number
388+
389+ # Milling step information
390+ if site_info .steps is None :
391+ logger .error ("No milling step info found in current message" )
392+ return None
393+ milling_steps = site_info .steps
384394
395+ # Outer try-finally block to handle database cleanup
396+ try :
385397 try :
386398 # Load instrument name and visit ID
387399 murfey_session = murfey_db .exec (
@@ -401,7 +413,10 @@ def run(message: dict[str, Any], murfey_db: SQLModelSession):
401413 session_id = session_id ,
402414 instrument_name = instrument_name ,
403415 visit_name = visit_name ,
404- site_info = site_info ,
416+ project_name = project_name ,
417+ slot_number = slot_number ,
418+ site_number = site_number ,
419+ transport_object = _transport_object ,
405420 murfey_db = murfey_db ,
406421 )
407422 except Exception :
@@ -412,15 +427,17 @@ def run(message: dict[str, Any], murfey_db: SQLModelSession):
412427 return {"success" : False , "requeue" : False }
413428 if grid_square_entry is None :
414429 logger .error (
415- f"Could not create GridSquare database entry for site { site_info . site_name } "
430+ f"Could not create GridSquare database entry for site { site_name } "
416431 )
417432 return {"success" : False , "requeue" : False }
418433
419434 try :
420435 # Insert or update MillingStep entries
421436 _register_milling_step (
422- site_info = site_info ,
437+ milling_steps = milling_steps ,
438+ stage_info = stage_info ,
423439 grid_square = grid_square_entry ,
440+ transport_object = _transport_object ,
424441 murfey_db = murfey_db ,
425442 )
426443 except Exception :
@@ -429,9 +446,7 @@ def run(message: dict[str, Any], murfey_db: SQLModelSession):
429446 exc_info = True ,
430447 )
431448 return {"success" : False , "requeue" : False }
432- logger .info (
433- f"Successfully registered milling progress of site { site_info .site_name } "
434- )
449+ logger .info (f"Successfully registered milling progress of site { site_name } " )
435450 return {"success" : True }
436451 finally :
437452 murfey_db .close ()
0 commit comments