Skip to content

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

[FIX] Platform service refactor (#731)

Deepak K9ba1150f4e07
diff --git a/platform-service/src/unstract/platform_service/config.py b/platform-service/src/unstract/platform_service/config.py
new file mode 100644
index 000000000..12bec9a2c
--- /dev/null
+++ b/platform-service/src/unstract/platform_service/config.py
@@ -0,0 +1,84 @@
+import logging
+from logging.config import dictConfig
+
+from dotenv import load_dotenv
+from flask import Flask
+from unstract.platform_service.constants import LogLevel
+from unstract.platform_service.controller import api
+from unstract.platform_service.env import Env
+from unstract.platform_service.extensions import db
+
+load_dotenv()
+
+
+dictConfig(
+ {
+ "version": 1,
+ "formatters": {
+ "default": {
+ "format": (
+ "[%(asctime)s] %(levelname)s in"
+ " %(name)s (%(module)s): %(message)s"
+ ),
+ "datefmt": "%Y-%m-%d %H:%M:%S %z",
+ },
+ },
+ "handlers": {
+ "wsgi": {
+ "class": "logging.StreamHandler",
+ "stream": "ext://flask.logging.wsgi_errors_stream",
+ "formatter": "default",
+ },
+ },
+ "loggers": {
+ "werkzeug": {
+ "level": Env.LOG_LEVEL,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ "gunicorn.access": {
+ "level": Env.LOG_LEVEL,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ "gunicorn.error": {
+ "level": Env.LOG_LEVEL,
+ "handlers": ["wsgi"],
+ "propagate": False,
+ },
+ },
+ "root": {
+ "level": Env.LOG_LEVEL,
+ "handlers": ["wsgi"],
+ },
+ }
+)
+
+LOGGING_LEVELS = {
+ LogLevel.DEBUG: logging.DEBUG,
+ LogLevel.INFO: logging.INFO,
+ LogLevel.WARNING: logging.WARNING,
+ LogLevel.ERROR: logging.ERROR,
+ LogLevel.CRITICAL: logging.CRITICAL,
+}
+
+
+def create_app() -> Flask:
+ app = Flask("platform-service")
+
+ # Set logging level
+ logging_level = LOGGING_LEVELS.get(Env.LOG_LEVEL, logging.INFO)
+ app.logger.setLevel(logging_level)
+ app.register_blueprint(api)
+
+ # Initialize and connect to the database
+ db.init(
+ database=Env.PG_BE_DATABASE,
+ user=Env.PG_BE_USERNAME,
+ password=Env.PG_BE_PASSWORD,
+ host=Env.PG_BE_HOST,
+ port=Env.PG_BE_PORT,
+ options=f"-c application_name={Env.APPLICATION_NAME}",
+ )
+
+ return app
diff --git a/platform-service/src/unstract/platform_service/controller/__init__.py b/platform-service/src/unstract/platform_service/controller/__init__.py
index 95e7074ff..619aec940 100644
--- a/platform-service/src/unstract/platform_service/controller/__init__.py
+++ b/platform-service/src/unstract/platform_service/controller/__init__.py
@@ -3,12 +3,11 @@ import traceback
from typing import Union
from flask import Blueprint, Response, jsonify, request
+from unstract.platform_service.controller.health import health_bp
+from unstract.platform_service.controller.platform import platform_bp
from unstract.platform_service.exceptions import APIError, ErrorResponse
from werkzeug.exceptions import HTTPException
-from .health import health_bp
-from .platform import platform_bp
-
api = Blueprint("api", __name__)
api.register_blueprint(platform_bp)
api.register_blueprint(health_bp)
diff --git a/platform-service/src/unstract/platform_service/controller/platform.py b/platform-service/src/unstract/platform_service/controller/platform.py
index 2f8aa992e..232bf2c2d 100644
--- a/platform-service/src/unstract/platform_service/controller/platform.py
+++ b/platform-service/src/unstract/platform_service/controller/platform.py
@@ -8,10 +8,10 @@ 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 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
+from unstract.platform_service.extensions import db
from unstract.platform_service.helper.adapter_instance import (
AdapterInstanceRequestHelper,
)
@@ -20,16 +20,6 @@ from unstract.platform_service.helper.prompt_studio import PromptStudioRequestHe
from unstract.flags.feature_flag import check_feature_flag_status
-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,
- options=f"-c application_name={Env.APPLICATION_NAME}",
-)
-be_db.init(Env.PG_BE_DATABASE)
-
platform_bp = Blueprint("platform", __name__)
@@ -92,7 +82,7 @@ def get_organization_from_bearer_token(token: str) -> tuple[Optional[int], str]:
def execute_query(query: str, params: tuple = ()) -> Any:
- cursor = be_db.execute_sql(query, params)
+ cursor = db.execute_sql(query, params)
result_row = cursor.fetchone()
cursor.close()
if not result_row or len(result_row) == 0:
@@ -118,7 +108,7 @@ def validate_bearer_token(token: Optional[str]) -> bool:
SELECT * FROM {platform_key_table} WHERE key = '{token}'
"""
- cursor = be_db.execute_sql(query)
+ cursor = db.execute_sql(query)
result_row = cursor.fetchone()
cursor.close()
if not result_row or len(result_row) == 0:
@@ -187,8 +177,8 @@ def page_usage() -> Any:
)
try:
- with be_db.atomic() as transaction:
- be_db.execute_sql(query, params)
+ with db.atomic() as transaction:
+ db.execute_sql(query, params)
transaction.commit()
app.logger.info("Entry created with id %s for %s", usage_id, org_id)
result["status"] = "OK"
@@ -308,8 +298,8 @@ def usage() -> Any:
current_time,
)
try:
- with be_db.atomic() as transaction:
- be_db.execute_sql(query, params)
+ with db.atomic() as transaction:
+ db.execute_sql(query, params)
transaction.commit()
app.logger.info("Entry created with id %s for %s", usage_id, org_id)
result["status"] = "OK"
@@ -453,7 +443,6 @@ def adapter_instance() -> Any:
try:
data_dict = AdapterInstanceRequestHelper.get_adapter_instance_from_db(
- db_instance=be_db,
organization_id=organization_id,
adapter_instance_id=adapter_instance_id,
organization_uid=organization_uid,
@@ -510,7 +499,7 @@ def custom_tool_instance() -> Any:
try:
data_dict = PromptStudioRequestHelper.get_prompt_instance_from_db(
- db_instance=be_db,
+ db_instance=db,
organization_id=organization_id,
prompt_registry_id=prompt_registry_id,
)
@@ -522,8 +511,3 @@ def custom_tool_instance() -> Any:
)
return "Internal Server Error", 500
return "Method Not Allowed", 405
-
-
-if __name__ == "__main__":
- # Start the server
- app.run(host="0.0.0.0", port="3001")
diff --git a/platform-service/src/unstract/platform_service/extensions.py b/platform-service/src/unstract/platform_service/extensions.py
new file mode 100644
index 000000000..ffa750da0
--- /dev/null
+++ b/platform-service/src/unstract/platform_service/extensions.py
@@ -0,0 +1,3 @@
+from peewee import PostgresqlDatabase
+
+db = PostgresqlDatabase(None)
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 c6daa25b6..65594fc21 100644
--- a/platform-service/src/unstract/platform_service/helper/adapter_instance.py
+++ b/platform-service/src/unstract/platform_service/helper/adapter_instance.py
@@ -1,8 +1,8 @@
from typing import Any, Optional
-from peewee import PostgresqlDatabase
from unstract.platform_service.constants import DBTableV2, FeatureFlag
from unstract.platform_service.exceptions import APIError
+from unstract.platform_service.extensions import db
from unstract.platform_service.utils import EnvManager
from unstract.flags.feature_flag import check_feature_flag_status
@@ -13,7 +13,6 @@ DB_SCHEMA = EnvManager.get_required_setting("DB_SCHEMA", "unstract_v2")
class AdapterInstanceRequestHelper:
@staticmethod
def get_adapter_instance_from_db(
- db_instance: PostgresqlDatabase,
organization_id: str,
adapter_instance_id: str,
organization_uid: Optional[int] = None,
@@ -21,7 +20,6 @@ class AdapterInstanceRequestHelper:
"""Get adapter instance from Backend Database.
Args:
- db_instance (PostgresqlDatabase): Backend DB Connection
organization_id (str): organization schema id
adapter_instance_id (str): adapter instance id
@@ -41,7 +39,7 @@ class AdapterInstanceRequestHelper:
f'"{organization_id}".adapter_adapterinstance x '
f"WHERE id='{adapter_instance_id}'"
)
- cursor = db_instance.execute_sql(query)
+ cursor = db.execute_sql(query)
result_row = cursor.fetchone()
if not result_row:
raise APIError(message="Adapter not found", code=404)
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 e685909c2..565c3c2f9 100644
--- a/platform-service/src/unstract/platform_service/helper/prompt_studio.py
+++ b/platform-service/src/unstract/platform_service/helper/prompt_studio.py
@@ -1,8 +1,8 @@
from typing import Any
-from peewee import PostgresqlDatabase
from unstract.platform_service.constants import DBTableV2, FeatureFlag
from unstract.platform_service.exceptions import APIError
+from unstract.platform_service.extensions import db
from unstract.platform_service.utils import EnvManager
from unstract.flags.feature_flag import check_feature_flag_status
@@ -13,14 +13,12 @@ DB_SCHEMA = EnvManager.get_required_setting("DB_SCHEMA", "unstract_v2")
class PromptStudioRequestHelper:
@staticmethod
def get_prompt_instance_from_db(
- db_instance: PostgresqlDatabase,
organization_id: str,
prompt_registry_id: str,
) -> dict[str, Any]:
"""Get prompt studio registry from Backend Database.
Args:
- db_instance (PostgresqlDatabase): Backend DB Connection
organization_id (str): organization schema id
prompt_registry_id (str): prompt_registry_id
@@ -41,7 +39,7 @@ class PromptStudioRequestHelper:
f'"{organization_id}".prompt_studio_registry_promptstudioregistry x'
f" WHERE prompt_registry_id='{prompt_registry_id}'"
)
- cursor = db_instance.execute_sql(query)
+ cursor = db.execute_sql(query)
result_row = cursor.fetchone()
if not result_row:
raise APIError(message="Custom Tool not found", code=404)
diff --git a/platform-service/src/unstract/platform_service/run.py b/platform-service/src/unstract/platform_service/run.py
index b30958b4f..c0735741b 100644
--- a/platform-service/src/unstract/platform_service/run.py
+++ b/platform-service/src/unstract/platform_service/run.py
@@ -1,95 +1,19 @@
-import logging
-from logging.config import dictConfig
from typing import Any
-from dotenv import load_dotenv
-from flask import Flask
-from unstract.platform_service.constants import LogLevel
-from unstract.platform_service.controller import api
-from unstract.platform_service.controller.platform import be_db
-from unstract.platform_service.env import Env
-
-load_dotenv()
-
-dictConfig(
- {
- "version": 1,
- "formatters": {
- "default": {
- "format": (
- "[%(asctime)s] %(levelname)s in"
- " %(name)s (%(module)s): %(message)s"
- ),
- "datefmt": "%Y-%m-%d %H:%M:%S %z",
- },
- },
- "handlers": {
- "wsgi": {
- "class": "logging.StreamHandler",
- "stream": "ext://flask.logging.wsgi_errors_stream",
- "formatter": "default",
- },
- },
- "loggers": {
- "werkzeug": {
- "level": Env.LOG_LEVEL,
- "handlers": ["wsgi"],
- "propagate": False,
- },
- "gunicorn.access": {
- "level": Env.LOG_LEVEL,
- "handlers": ["wsgi"],
- "propagate": False,
- },
- "gunicorn.error": {
- "level": Env.LOG_LEVEL,
- "handlers": ["wsgi"],
- "propagate": False,
- },
- },
- "root": {
- "level": Env.LOG_LEVEL,
- "handlers": ["wsgi"],
- },
- }
-)
-
-LOGGING_LEVELS = {
- LogLevel.DEBUG: logging.DEBUG,
- LogLevel.INFO: logging.INFO,
- LogLevel.WARNING: logging.WARNING,
- LogLevel.ERROR: logging.ERROR,
- LogLevel.CRITICAL: logging.CRITICAL,
-}
-
-
-def create_app() -> Flask:
- app = Flask("platform-service")
-
- # Set logging level
- logging_level = LOGGING_LEVELS.get(Env.LOG_LEVEL, logging.INFO)
- app.logger.setLevel(logging_level)
- app.register_blueprint(api)
-
- return app
-
+from unstract.platform_service.config import create_app
+from unstract.platform_service.extensions import db
app = create_app()
@app.before_request
def before_request() -> None:
- if be_db.is_closed():
- be_db.connect(reuse_if_open=True)
+ if db.is_closed():
+ db.connect(reuse_if_open=True)
@app.teardown_request
def after_request(exception: Any) -> None:
# Close the connection after each request
- if not be_db.is_closed():
- be_db.close()
-
-
-if __name__ == "__main__":
- # Start the server
- app.run(host="0.0.0.0", port=3001, load_dotenv=True)
+ if not db.is_closed():
+ db.close()
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index 9e1885ed1..473c7c4d3 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -882,8 +882,3 @@ def handle_uncaught_exception(e):
log_exceptions(e)
return handle_http_exception(APIError())
-
-
-# TODO: Review if below code is needed
-if __name__ == "__main__":
- app.run(host="0.0.0.0", port=5003)