Skip to content

Commit 8bdd0b2

Browse files
committed
And a connections clean up decorator to all scheduled tasks
1 parent 8176018 commit 8bdd0b2

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/khoj/configure.py

+25
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import os
44
from datetime import datetime
55
from enum import Enum
6+
from functools import wraps
67
from typing import Optional
78

89
import openai
@@ -198,6 +199,26 @@ def initialize_server(config: Optional[FullConfig]):
198199
raise e
199200

200201

202+
def clean_connections(func):
203+
"""
204+
A decorator that ensures that Django database connections that have become unusable, or are obsolete, are closed
205+
before and after a method is executed (see: https://docs.djangoproject.com/en/dev/ref/databases/#general-notes
206+
for background).
207+
"""
208+
209+
@wraps(func)
210+
def func_wrapper(*args, **kwargs):
211+
close_old_connections()
212+
try:
213+
result = func(*args, **kwargs)
214+
finally:
215+
close_old_connections()
216+
217+
return result
218+
219+
return func_wrapper
220+
221+
201222
def configure_server(
202223
config: FullConfig,
203224
regenerate: bool = False,
@@ -349,6 +370,7 @@ def update_content_index():
349370

350371

351372
@schedule.repeat(schedule.every(22).to(25).hours)
373+
@clean_connections
352374
def update_content_index_regularly():
353375
ProcessLockAdapters.run_with_lock(
354376
update_content_index, ProcessLock.Operation.INDEX_CONTENT, max_duration_in_seconds=60 * 60 * 2
@@ -364,6 +386,7 @@ def configure_search_types():
364386

365387

366388
@schedule.repeat(schedule.every(2).minutes)
389+
@clean_connections
367390
def upload_telemetry():
368391
if telemetry_disabled(state.config.app, state.telemetry_disabled) or not state.telemetry:
369392
return
@@ -389,12 +412,14 @@ def upload_telemetry():
389412

390413

391414
@schedule.repeat(schedule.every(31).minutes)
415+
@clean_connections
392416
def delete_old_user_requests():
393417
num_deleted = delete_user_requests()
394418
logger.debug(f"🗑️ Deleted {num_deleted[0]} day-old user requests")
395419

396420

397421
@schedule.repeat(schedule.every(17).minutes)
422+
@clean_connections
398423
def wakeup_scheduler():
399424
# Wake up the scheduler to ensure it runs the scheduled tasks. This is because the elected leader may not always be aware of tasks scheduled on other workers.
400425
TWELVE_HOURS = 43200

0 commit comments

Comments
 (0)