Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

[FIX] Re connection for close db connection & Removing connection Pool (#685)

harini-venkataraman5a594da5ccb5
diff --git a/platform-service/sample.env b/platform-service/sample.env
index 666835055..0e533af8c 100644
--- a/platform-service/sample.env
+++ b/platform-service/sample.env
@@ -26,10 +26,3 @@ FLIPT_SERVICE_AVAILABLE=False
MODEL_PRICES_URL="https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
MODEL_PRICES_TTL_IN_DAYS=7
MODEL_PRICES_FILE_PATH="/tmp/model_prices.json"
-
-#Connection Pool ENVs
-POOL_MAX_CONNECTIONS=32
-# Number of seconds to allow connections to be used. Same as gunicorn timeout
-POOL_STALE_TIMEOUT=900
-# Number of seconds to block when pool is full. Set to 5 minutes.
-POOL_TIMEOUT=300
diff --git a/platform-service/src/unstract/platform_service/controller/platform.py b/platform-service/src/unstract/platform_service/controller/platform.py
index ad56a83b2..9d51243ce 100644
--- a/platform-service/src/unstract/platform_service/controller/platform.py
+++ b/platform-service/src/unstract/platform_service/controller/platform.py
@@ -8,7 +8,7 @@ from cryptography.fernet import Fernet, InvalidToken
from flask import Blueprint, Request
from flask import current_app as app
from flask import jsonify, make_response, request
-from playhouse.pool import PooledPostgresqlDatabase
+from peewee import PostgresqlDatabase
from unstract.platform_service.constants import DBTable, DBTableV2, FeatureFlag
from unstract.platform_service.env import Env
from unstract.platform_service.exceptions import APIError
@@ -20,19 +20,14 @@ from unstract.platform_service.helper.prompt_studio import PromptStudioRequestHe
from unstract.flags.feature_flag import check_feature_flag_status
-be_db = PooledPostgresqlDatabase(
+be_db = PostgresqlDatabase(
Env.PG_BE_DATABASE,
user=Env.PG_BE_USERNAME,
password=Env.PG_BE_PASSWORD,
host=Env.PG_BE_HOST,
port=Env.PG_BE_PORT,
- max_connections=Env.POOL_MAX_CONNECTIONS,
- stale_timeout=Env.POOL_STALE_TIMEOUT,
- timeout=Env.POOL_TIMEOUT,
)
be_db.init(Env.PG_BE_DATABASE)
-be_db.connect()
-
platform_bp = Blueprint("platform", __name__)
@@ -113,7 +108,6 @@ def validate_bearer_token(token: Optional[str]) -> bool:
cursor = be_db.execute_sql(query)
result_row = cursor.fetchone()
cursor.close()
- be_db.close()
if not result_row or len(result_row) == 0:
app.logger.error(f"Authentication failed. bearer token not found {token}")
return False
diff --git a/platform-service/src/unstract/platform_service/env.py b/platform-service/src/unstract/platform_service/env.py
index f1a21c1f0..a938c4a44 100644
--- a/platform-service/src/unstract/platform_service/env.py
+++ b/platform-service/src/unstract/platform_service/env.py
@@ -22,11 +22,6 @@ class Env:
EnvManager.get_required_setting("MODEL_PRICES_TTL_IN_DAYS")
)
MODEL_PRICES_FILE_PATH = EnvManager.get_required_setting("MODEL_PRICES_FILE_PATH")
- POOL_MAX_CONNECTIONS = int(
- EnvManager.get_required_setting("POOL_MAX_CONNECTIONS", 32)
- )
- POOL_STALE_TIMEOUT = int(EnvManager.get_required_setting("POOL_STALE_TIMEOUT", 900))
- POOL_TIMEOUT = int(EnvManager.get_required_setting("POOL_TIMEOUT", 300))
EnvManager.raise_for_missing_envs()
diff --git a/platform-service/src/unstract/platform_service/helper/adapter_instance.py b/platform-service/src/unstract/platform_service/helper/adapter_instance.py
index 6667c1791..c0d03dbc1 100644
--- a/platform-service/src/unstract/platform_service/helper/adapter_instance.py
+++ b/platform-service/src/unstract/platform_service/helper/adapter_instance.py
@@ -1,6 +1,6 @@
from typing import Any, Optional
-from playhouse.pool import PooledPostgresqlDatabase
+from peewee import PostgresqlDatabase
from unstract.platform_service.constants import DBTableV2, FeatureFlag
from unstract.platform_service.exceptions import APIError
@@ -10,7 +10,7 @@ from unstract.flags.feature_flag import check_feature_flag_status
class AdapterInstanceRequestHelper:
@staticmethod
def get_adapter_instance_from_db(
- db_instance: PooledPostgresqlDatabase,
+ db_instance: PostgresqlDatabase,
organization_id: str,
adapter_instance_id: str,
organization_uid: Optional[int] = None,
@@ -18,7 +18,7 @@ class AdapterInstanceRequestHelper:
"""Get adapter instance from Backend Database.
Args:
- db_instance (PooledPostgresqlDatabase): Backend DB Connection Pool
+ db_instance (PostgresqlDatabase): Backend DB Connection
organization_id (str): organization schema id
adapter_instance_id (str): adapter instance id
@@ -45,5 +45,4 @@ class AdapterInstanceRequestHelper:
columns = [desc[0] for desc in cursor.description]
data_dict: dict[str, Any] = dict(zip(columns, result_row))
cursor.close()
- db_instance.close()
return data_dict
diff --git a/platform-service/src/unstract/platform_service/helper/prompt_studio.py b/platform-service/src/unstract/platform_service/helper/prompt_studio.py
index 276358f76..6801792c1 100644
--- a/platform-service/src/unstract/platform_service/helper/prompt_studio.py
+++ b/platform-service/src/unstract/platform_service/helper/prompt_studio.py
@@ -1,6 +1,6 @@
from typing import Any
-from playhouse.pool import PooledPostgresqlDatabase
+from peewee import PostgresqlDatabase
from unstract.platform_service.constants import DBTableV2, FeatureFlag
from unstract.platform_service.exceptions import APIError
@@ -10,14 +10,14 @@ from unstract.flags.feature_flag import check_feature_flag_status
class PromptStudioRequestHelper:
@staticmethod
def get_prompt_instance_from_db(
- db_instance: PooledPostgresqlDatabase,
+ db_instance: PostgresqlDatabase,
organization_id: str,
prompt_registry_id: str,
) -> dict[str, Any]:
"""Get prompt studio registry from Backend Database.
Args:
- db_instance (PooledPostgresqlDatabase): Backend DB Connection Pool
+ db_instance (PostgresqlDatabase): Backend DB Connection
organization_id (str): organization schema id
prompt_registry_id (str): prompt_registry_id
@@ -45,5 +45,4 @@ class PromptStudioRequestHelper:
columns = [desc[0] for desc in cursor.description]
data_dict: dict[str, Any] = dict(zip(columns, result_row))
cursor.close()
- db_instance.close()
return data_dict
diff --git a/platform-service/src/unstract/platform_service/run.py b/platform-service/src/unstract/platform_service/run.py
index ed81aff97..ae7f9e1a4 100644
--- a/platform-service/src/unstract/platform_service/run.py
+++ b/platform-service/src/unstract/platform_service/run.py
@@ -3,6 +3,7 @@ from logging.config import dictConfig
from dotenv import load_dotenv
from flask import Flask
from unstract.platform_service.controller import api
+from unstract.platform_service.controller.platform import be_db
load_dotenv()
@@ -35,6 +36,13 @@ def create_app() -> Flask:
app = create_app()
+
+def before_request() -> None:
+ if be_db.is_closed():
+ be_db.connect(reuse_if_open=True)
+
+
if __name__ == "__main__":
# Start the server
app.run(host="0.0.0.0", port=3001, load_dotenv=True)
diff --git a/prompt-service/sample.env b/prompt-service/sample.env
index 752394286..53f27dad2 100644
--- a/prompt-service/sample.env
+++ b/prompt-service/sample.env
@@ -27,10 +27,3 @@ EVALUATION_SERVER_PORT=9000
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
# Flipt Service
FLIPT_SERVICE_AVAILABLE=False
-
-#Connection Pool ENVs
-POOL_MAX_CONNECTIONS=32
-# Number of seconds to allow connections to be used. Same as gunicorn timeout
-POOL_STALE_TIMEOUT=900
-# Number of seconds to block when pool is full. Set to 5 minutes.
-POOL_TIMEOUT=300
diff --git a/prompt-service/src/unstract/prompt_service/authentication_middleware.py b/prompt-service/src/unstract/prompt_service/authentication_middleware.py
index 530114ab9..fbf03c37b 100644
--- a/prompt-service/src/unstract/prompt_service/authentication_middleware.py
+++ b/prompt-service/src/unstract/prompt_service/authentication_middleware.py
@@ -25,7 +25,6 @@ class AuthenticationMiddleware:
cursor = db.execute_sql(query)
result_row = cursor.fetchone()
cursor.close()
- db.close()
if not result_row or len(result_row) == 0:
current_app.logger.error(
f"Authentication failed. bearer token not found {token}"
diff --git a/prompt-service/src/unstract/prompt_service/config.py b/prompt-service/src/unstract/prompt_service/config.py
index e61f8138b..5d6a2ef15 100644
--- a/prompt-service/src/unstract/prompt_service/config.py
+++ b/prompt-service/src/unstract/prompt_service/config.py
@@ -4,7 +4,7 @@ from os import environ as env
from dotenv import load_dotenv
from flask import Flask
-from playhouse.pool import PooledPostgresqlDatabase
+from peewee import PostgresqlDatabase
from unstract.prompt_service.constants import LogLevel
load_dotenv()
@@ -28,7 +28,7 @@ dictConfig(
}
)
-db = PooledPostgresqlDatabase(None)
+db = PostgresqlDatabase(None)
def get_env_or_die(env_key: str) -> str:
@@ -54,9 +54,6 @@ def create_app() -> Flask:
db_user = get_env_or_die("PG_BE_USERNAME")
db_pass = get_env_or_die("PG_BE_PASSWORD")
db_name = get_env_or_die("PG_BE_DATABASE")
- max_connections = int(get_env_or_die("POOL_MAX_CONNECTIONS"))
- stale_timeout = int(get_env_or_die("POOL_STALE_TIMEOUT"))
- timeout = int(get_env_or_die("POOL_TIMEOUT"))
# Initialize and connect to the database
db.init(
@@ -65,10 +62,5 @@ def create_app() -> Flask:
password=db_pass,
host=db_host,
port=db_port,
- max_connections=max_connections,
- stale_timeout=stale_timeout,
- timeout=timeout,
)
- db.connect()
-
return app
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index d80d53781..b92fb0076 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -7,7 +7,7 @@ from typing import Any, Optional
from flask import json, jsonify, request
from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters
from unstract.prompt_service.authentication_middleware import AuthenticationMiddleware
-from unstract.prompt_service.config import create_app
+from unstract.prompt_service.config import create_app, db
from unstract.prompt_service.constants import PromptServiceContants as PSKeys
from unstract.prompt_service.constants import RunLevel
from unstract.prompt_service.exceptions import APIError, ErrorResponse, NoPayloadError
@@ -48,6 +48,12 @@ app = create_app()
plugin_loader(app)
+def before_request() -> None:
+ if db.is_closed():
+ db.connect(reuse_if_open=True)
+
+
def _publish_log(
log_events_id: str,
component: dict[str, str],