Skip to content

Commit ea73c94

Browse files
authored
refactor(api): Improve api resource lifecycle management (#19109)
# Overview This PR contains a few various enhancements that ensure proper resource garbage collection. 0bd7359 - We never explicitly call cleanup in Task Queues, which could be an issue if an exception occurs. 0647e68 - There's a closure here that captures `self`. Removing the closure fixes that.
1 parent 49d038d commit ea73c94

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

api/src/opentrons/protocol_api/protocol_context.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -337,23 +337,24 @@ def clear_commands(self) -> None:
337337
if self._unsubscribe_commands:
338338
self._unsubscribe_commands()
339339

340-
def on_command(message: cmd_types.CommandMessage) -> None:
341-
payload = message.get("payload")
340+
self._unsubscribe_commands = self.broker.subscribe(
341+
cmd_types.COMMAND, self._on_command_callback
342+
)
342343

343-
if payload is None:
344-
return
344+
def _on_command_callback(self, message: cmd_types.CommandMessage) -> None:
345+
"""Callback for command messages."""
346+
payload = message.get("payload")
345347

346-
text = payload.get("text")
348+
if payload is None:
349+
return
347350

348-
if text is None:
349-
return
351+
text = payload.get("text")
350352

351-
if message["$"] == "before":
352-
self._commands.append(text)
353+
if text is None:
354+
return
353355

354-
self._unsubscribe_commands = self.broker.subscribe(
355-
cmd_types.COMMAND, on_command
356-
)
356+
if message["$"] == "before":
357+
self._commands.append(text)
357358

358359
@requires_version(2, 0)
359360
def is_simulating(self) -> bool:

api/src/opentrons/protocol_runner/task_queue.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ async def _run(self) -> None:
8585
except Exception as e:
8686
log.exception("Exception raised by protocol")
8787
error = e
88+
finally:
89+
self._run_func = None
8890

89-
if self._cleanup_func is not None:
90-
await self._cleanup_func(error)
91+
try:
92+
if self._cleanup_func is not None:
93+
await self._cleanup_func(error)
94+
finally:
95+
self._cleanup_func = None

0 commit comments

Comments
 (0)