Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: optimize db connections in thread #1601

Merged
merged 1 commit into from
Nov 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 22 additions & 19 deletions api/services/completion_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def generate_worker(cls, flask_app: Flask, generate_task_id: str, detached_app_m
logging.exception("Unknown Error in completion")
PubHandler.pub_error(user, generate_task_id, e)
finally:
db.session.commit()
db.session.remove()

@classmethod
def countdown_and_close(cls, flask_app: Flask, worker_thread, pubsub, detached_user,
Expand All @@ -242,22 +242,25 @@ def countdown_and_close(cls, flask_app: Flask, worker_thread, pubsub, detached_u

def close_pubsub():
with flask_app.app_context():
user = db.session.merge(detached_user)

sleep_iterations = 0
while sleep_iterations < timeout and worker_thread.is_alive():
if sleep_iterations > 0 and sleep_iterations % 10 == 0:
PubHandler.ping(user, generate_task_id)

time.sleep(1)
sleep_iterations += 1

if worker_thread.is_alive():
PubHandler.stop(user, generate_task_id)
try:
pubsub.close()
except Exception:
pass
try:
user = db.session.merge(detached_user)

sleep_iterations = 0
while sleep_iterations < timeout and worker_thread.is_alive():
if sleep_iterations > 0 and sleep_iterations % 10 == 0:
PubHandler.ping(user, generate_task_id)

time.sleep(1)
sleep_iterations += 1

if worker_thread.is_alive():
PubHandler.stop(user, generate_task_id)
try:
pubsub.close()
except Exception:
pass
finally:
db.session.remove()

countdown_thread = threading.Thread(target=close_pubsub)
countdown_thread.start()
Expand Down Expand Up @@ -394,7 +397,7 @@ def compact_response(cls, pubsub: PubSub, streaming: bool = False) -> Union[dict
logging.exception(e)
raise
finally:
db.session.commit()
db.session.remove()

try:
pubsub.unsubscribe(generate_channel)
Expand Down Expand Up @@ -436,7 +439,7 @@ def generate() -> Generator:
logging.exception(e)
raise
finally:
db.session.commit()
db.session.remove()

try:
pubsub.unsubscribe(generate_channel)
Expand Down
Loading