Fix 'Unclosed client session' error #830
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation and Context
To resolve
Unclosed client session
errors which occur when the Web App service is running as well as when the localstart.sh
script is used to run the application.As per issues #751 and #593 improper handling of database and other asynchronous connections results in
Unclosed client session
errors.Using
.aio
libraries requires the proper handling and/or closing of asynchronous connections.It resolves issues #751 and #593.
It benefits all users who run the quart version of the app.
Description
As per the
CosmosClient
class in theazure-cosmos
Python library, creating a database instance is a heavy operation:To avoid multiple connection attempts, only a single global instance of the cosmos database connection is created in the
init()
function as part of thecreate_app()
function. Only a single call toinit_cosmosdb_client()
is now needed instead of multiple calls within each function. This implementation leverages thecurrent_app
method of thequart
library to maintain the database object's state during the lifetime of the application. When the database object is needed, it can be called usingcurrent_app
, e.g.,current_app.cosmos_conversation_client.create_message(...)
In addition, an
Event
is used to signal the readiness status of the database initialization to downstream functions to avoid the app calling methods of theCosmosConversationClient
class before the client is completely initialized. Without this approach, a user would see an error on the frontend that disappears only once the initialization is complete. Functions can 'wait' on the database using the.wait()
method of theEvent
class.Another source of the
Unclosed client session
error stems from the use of the asynchronous import ofDefaultAzureCredential
from.aio
. This connection is handled using a context created by theasync with
statement. Thanks to QuentinAd for the template.Contribution Checklist