Repository: eclipse-tractusx/industry-core-hub
Pull request #180: feat: Move start method to runtimes module
Author: login: CDiezRodriguez
Created: 2025-05-06T12:50:20Z | Merged: 2025-05-09T08:02:21Z

## WHAT

Move the start method from main to the runtime module.

## WHY

To improve readability and support deployment.

## FURTHER NOTES

Closes #179 


Linked issue #179: feat: Move start method to runtimes module
### Description
Currently, we have only one runtime. In case we add more in the future, we would simply need to change the import path in main and run it with the same command-line command.

### Acceptance Criteria

- [ ] Move the start method

Diff:
diff --git a/ichub-backend/main.py b/ichub-backend/main.py
index 5755125f8..c5d3040cd 100644
--- a/ichub-backend/main.py
+++ b/ichub-backend/main.py
@@ -24,17 +24,11 @@
 from config.config_manager import ConfigManager
 from database import connect_and_test
 
-from fastapi import FastAPI, HTTPException, Request
-
 ## FAST API example for keycloak
-from fastapi_keycloak_middleware import CheckPermissions
-from fastapi_keycloak_middleware import get_user
+# from fastapi_keycloak_middleware import CheckPermissions
+# from fastapi_keycloak_middleware import get_user
 import sys
-import argparse
-from logging import config
-import logging
-import yaml
-import uvicorn
+from logging import captureWarnings
 import urllib3
 
 from pathlib import Path
@@ -42,25 +36,10 @@
 sys.path.append(str(Path(__file__).resolve().parents[1]))
 sys.dont_write_bytecode = True
 
-## Import Library Packeges
-from tractusx_sdk.dataspace.tools import op
-from tractusx_sdk.dataspace.tools import HttpTools
-from tractusx_sdk.dataspace.managers import AuthManager
-from tractusx_sdk.dataspace.services import EdcService
-from tractusx_sdk.industry.services import AasService
-
-## Declare Global Variables
-app_configuration:dict
-log_config:dict
-
-## In memory storage/management services
-edc_service: EdcService
-
-## In memory authentication manager service
-auth_manager: AuthManager
+from runtimes.fastapi import start
 
 urllib3.disable_warnings()
-logging.captureWarnings(True)
+captureWarnings(True)
 
 # Load the logging config
 LoggingManager.init_logging()
@@ -73,74 +52,6 @@
 # if it the database connection is invalid or databse is not available
 # it will raise an exception and the application will not start
 # connect_and_test()
-    
-# Add the previous folder structure to the system path to import the utilities
-app = FastAPI(title="main")
-
-@app.get("/example")
-async def api_call(request: Request):
-    """
-    Example documentation
-
-    Returns:
-        response: :obj:`__insert response here__`
-    """
-    try:
-        ## Check if the api key is present and if it is authenticated
-        if(not auth_manager.is_authenticated(request=request)):
-            return HttpTools.get_not_authorized()
-        ## Standard way to know if user is calling or the EDC.
-        
-        ## DO LOGIC HERE!!!
-        return None
-    
-    except Exception as e:
-        logger.exception(str(e))
-        return HttpTools.get_error_response(
-            status=500,
-            message="It was not possible to execute the request!"
-        )
-
-def start():
-    ## Load in memory data storages and authentication manager
-    global edc_service, auth_manager, logger
-    
-    # Initialize the server environment and get the comand line arguments
-    args = get_arguments()
-
-    # Configure the logging confiuration depending on the configuration stated
-    logger = LoggingManager.get_logger('staging')
-    if(args.debug):
-        logger = LoggingManager.get_logger('development')
-    
-    ## Start storage and edc communication service
-    edc_service = EdcService()
-
-    ## Start the authentication manager
-    auth_manager = AuthManager()
-    
-    ## Once initial checks and configurations are done here is the place where it shall be included
-    logger.info("[INIT] Application Startup Initialization Completed!")
-
-    # Only start the Uvicorn server if not in test mode
-    if not args.test_mode:
-        uvicorn.run(app, host=args.host, port=args.port, log_level=("debug" if args.debug else "info"))        
-    
-def get_arguments():
-    
-    parser = argparse.ArgumentParser()
-
-    parser.add_argument('--test-mode', action='store_true', help="Run in test mode (skips uvicorn.run())", required=False)
-    
-    parser.add_argument("--debug", default=False, action="store_true", help="Enable and disable the debug", required=False)
-    
-    parser.add_argument("--port", default=8080, help="The server port where it will be available", type=int, required=False,)
-    
-    parser.add_argument("--host", default="localhost", help="The server host where it will be available", type=str, required=False)
-    
-    args = parser.parse_args()
-    return args
-
 
 if __name__ == "__main__":
     print("\nEclipse Tractus-X Industry Core Hub\n")
diff --git a/ichub-backend/runtimes/fastapi/__init__.py b/ichub-backend/runtimes/fastapi/__init__.py
index d47335233..40173c263 100644
--- a/ichub-backend/runtimes/fastapi/__init__.py
+++ b/ichub-backend/runtimes/fastapi/__init__.py
@@ -23,3 +23,5 @@
 # Package-level variables
 __author__ = 'Eclipse Tractus-X Contributors'
 __license__ = "Apache License, Version 2.0"
+
+from .main import start
diff --git a/ichub-backend/runtimes/fastapi/main.py b/ichub-backend/runtimes/fastapi/main.py
index 3eb26b509..b52205256 100644
--- a/ichub-backend/runtimes/fastapi/main.py
+++ b/ichub-backend/runtimes/fastapi/main.py
@@ -21,8 +21,41 @@
 #################################################################################
 import uvicorn
 from controllers.fastapi import app as api
+from tractusx_sdk.dataspace.tools.utils import get_arguments
+from config.log_manager import LoggingManager
+from tractusx_sdk.dataspace.managers import AuthManager
+from tractusx_sdk.dataspace.services import EdcService
 
 app = api
 
-if __name__ == "__main__":
-    uvicorn.run("runtimes.fastapi.main:api", reload=True)
\ No newline at end of file
+## In memory storage/management services
+edc_service: EdcService
+
+## In memory authentication manager service
+auth_manager: AuthManager
+
+
+def start():
+    ## Load in memory data storages and authentication manager
+    global edc_service, auth_manager, logger
+    
+    # Initialize the server environment and get the comand line arguments
+    args = get_arguments()
+
+    # Configure the logging confiuration depending on the configuration stated
+    logger = LoggingManager.get_logger('staging')
+    if(args.debug):
+        logger = LoggingManager.get_logger('development')
+    
+    ## Start storage and edc communication service
+    edc_service = EdcService()
+
+    ## Start the authentication manager
+    auth_manager = AuthManager()
+    
+    ## Once initial checks and configurations are done here is the place where it shall be included
+    logger.info("[INIT] Application Startup Initialization Completed!")
+
+    # Only start the Uvicorn server if not in test mode
+    if not args.test_mode:
+        uvicorn.run(app, host=args.host, port=args.port, log_level=("debug" if args.debug else "info"))


Reviews:
user: login: gomezbc
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-08T07:59:18Z
user: login: gomezbc
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-05-08T08:00:41Z
user: login: gomezbc
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-05-08T12:45:42Z
user: login: mgarciaLKS
body: Worked Fine to me
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-05-09T08:01:01Z

Review comments:
diff_hunk: @@ -151,7 +66,7 @@ def get_arguments():
      _/ // /__/_____/ __  / /_/ / /_/ /  / /_/ / /_/ / /__/ ,< /  __/ / / / /_/ /  
     /___/\____/    /_/ /_/\__,_/_.___/  /_____/\__,_/\___/_/|_|\___/_/ /_/\__,_/   
     """)
-    print("\n\n\t\t\t\t\t\t\t\t\t\tv0.0.1")
+    print("\n\n\t\t\t\t\t\t\t\t\t\tv0.1.3")
path: ichub-backend/main.py
user: login: gomezbc
body: The image tag is 0.0.1
```suggestion
    print("\n\n\t\t\t\t\t\t\t\t\t\tv0.0.1")
```
created_at: 2025-05-08T07:59:16Z
author_association: CONTRIBUTOR
diff_hunk: @@ -24,43 +24,26 @@
 from config.config_manager import ConfigManager
 from database import connect_and_test
 
-from fastapi import FastAPI, HTTPException, Request
-
 ## FAST API example for keycloak
-from fastapi_keycloak_middleware import CheckPermissions
-from fastapi_keycloak_middleware import get_user
+# from fastapi_keycloak_middleware import CheckPermissions
+# from fastapi_keycloak_middleware import get_user
 import sys
-import argparse
-from logging import config
-import logging
-import yaml
-import uvicorn
+from logging import captureWarnings
 import urllib3
 
 from pathlib import Path
 ## Import paths
 sys.path.append(str(Path(__file__).resolve().parents[1]))
 sys.dont_write_bytecode = True
 
-## Import Library Packeges
-from tractusx_sdk.dataspace.tools import op
-from tractusx_sdk.dataspace.tools import HttpTools
-from tractusx_sdk.dataspace.managers import AuthManager
-from tractusx_sdk.dataspace.services import EdcService
-from tractusx_sdk.industry.services import AasService
+from runtimes.fastapi import start
 
 ## Declare Global Variables
 app_configuration:dict
 log_config:dict
path: ichub-backend/main.py
user: login: gomezbc
body: We don't need these global variables, the config is saved in the managers
```suggestion
```
created_at: 2025-05-08T08:00:40Z
author_association: CONTRIBUTOR

PR comments:
user: login: sonarqubecloud[bot]
created_at: 2025-05-08T12:42:21Z
body: ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=eclipse-tractusx_industry-core-hub&pullRequest=180) **Quality Gate passed**  
Issues  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 New issues](https://sonarcloud.io/project/issues?id=eclipse-tractusx_industry-core-hub&pullRequest=180&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=eclipse-tractusx_industry-core-hub&pullRequest=180&issueStatuses=ACCEPTED)

Measures  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=eclipse-tractusx_industry-core-hub&pullRequest=180&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=eclipse-tractusx_industry-core-hub&pullRequest=180&metric=new_coverage&view=list)  
![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Duplication on New Code](https://sonarcloud.io/component_measures?id=eclipse-tractusx_industry-core-hub&pullRequest=180&metric=new_duplicated_lines_density&view=list)  
  
[See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=eclipse-tractusx_industry-core-hub&pullRequest=180)


author_association: NONE