Skip to content

Commit

Permalink
[1.x] Implement stop_extension() (#566)
Browse files Browse the repository at this point in the history
* implement stop_extension()

* update error log msg
  • Loading branch information
dlqqq authored Jan 5, 2024
1 parent f8583c2 commit d91e9bb
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions packages/jupyter-ai/jupyter_ai/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def initialize_settings(self):
# requires the event loop to be running on init. So instead we schedule
# this as a task that is run as soon as the loop starts, and pass
# consumers a Future that resolves to the Dask client when awaited.
dask_client_future = loop.create_task(self._get_dask_client())
self.settings["dask_client_future"] = loop.create_task(self._get_dask_client())

eps = entry_points()
# initialize chat handlers
Expand All @@ -178,7 +178,7 @@ def initialize_settings(self):
"root_chat_handlers": self.settings["jai_root_chat_handlers"],
"chat_history": self.settings["chat_history"],
"root_dir": self.serverapp.root_dir,
"dask_client_future": dask_client_future,
"dask_client_future": self.settings["dask_client_future"],
"model_parameters": self.settings["model_parameters"],
}
default_chat_handler = DefaultChatHandler(**chat_handler_kwargs)
Expand Down Expand Up @@ -263,3 +263,27 @@ def initialize_settings(self):

async def _get_dask_client(self):
return DaskClient(processes=False, asynchronous=True)

async def stop_extension(self):
"""
Public method called by Jupyter Server when the server is stopping.
This calls the cleanup code defined in `self._stop_exception()` inside
an exception handler, as the server halts if this method raises an
exception.
"""
try:
await self._stop_extension()
except Exception as e:
self.log.error("Jupyter AI raised an exception while stopping:")
self.log.exception(e)

async def _stop_extension(self):
"""
Private method that defines the cleanup code to run when the server is
stopping.
"""
if "dask_client_future" in self.settings:
dask_client: DaskClient = await self.settings["dask_client_future"]
self.log.info("Closing Dask client.")
await dask_client.close()
self.log.debug("Closed Dask client.")

0 comments on commit d91e9bb

Please sign in to comment.