-
Notifications
You must be signed in to change notification settings - Fork 0
FEAT: Implement backend service #4
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
Open
jgfranco17
wants to merge
3
commits into
main
Choose a base branch
from
feat/add-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| from backend.service import main | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| """Main backend source code. | ||
|
|
||
| This package contains the core functionality of the backend service. | ||
| The main logger initialization is also done here to ensure consistent | ||
| logging across the application. | ||
| """ |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import logging | ||
| import os | ||
|
|
||
| from pydantic import BaseModel, Field | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Constants for backward compatibility | ||
| LOG_LEVEL = "LOG_LEVEL" | ||
|
|
||
|
|
||
| class Config(BaseModel): | ||
| """Application configuration loaded from environment variables.""" | ||
|
|
||
| # Application settings | ||
| app_name: str = Field(default="DevOps API") | ||
| app_version: str = Field(default="0.0.1") | ||
| debug: bool = Field(default=False) | ||
|
|
||
| # Server settings | ||
| host: str = Field(default="0.0.0.0") | ||
| port: int = Field(default=8000) | ||
| reload: bool = Field(default=False) | ||
|
|
||
| # Logging settings | ||
| log_level: str = Field(default="INFO") | ||
|
|
||
| @classmethod | ||
| def from_env(cls) -> "Config": | ||
| """Create a Config instance from environment variables.""" | ||
|
|
||
| def parse_bool(value: str) -> bool: | ||
| """Parse a string as a boolean.""" | ||
| return value.lower() in ("true", "1", "t", "yes", "y", "on") | ||
|
|
||
| def parse_list(value: str) -> list[str]: | ||
| """Parse a comma-separated string as a list.""" | ||
| if not value: | ||
| return [] | ||
| return [item.strip() for item in value.split(",")] | ||
|
|
||
| def parse_log_level(value: str) -> str: | ||
| """Parse and validate log level.""" | ||
| level = value.upper() | ||
| valid_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"} | ||
| if level not in valid_levels: | ||
| return "INFO" | ||
| return level # type: ignore | ||
|
|
||
| return cls( | ||
| app_name=os.getenv("APP_NAME", "DevOps API"), | ||
| app_version=os.getenv("APP_VERSION", "0.0.1"), | ||
| debug=parse_bool(os.getenv("DEBUG", "false")), | ||
| host=os.getenv("HOST", "0.0.0.0"), | ||
| port=int(os.getenv("PORT", "8000")), | ||
| reload=parse_bool(os.getenv("RELOAD", "false")), | ||
| log_level=parse_log_level(os.getenv("LOG_LEVEL", "INFO")), | ||
| ) | ||
|
|
||
|
|
||
| def load_environment() -> Config: | ||
| """Load the application configuration from environment variables.""" | ||
| config = Config.from_env() | ||
| logger.info("Environment configuration loaded successfully!") | ||
| return config |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import yaml | ||
| from pathlib import Path | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
|
|
||
| class SoftwareComponent(BaseModel): | ||
| """Model representing a software component with name and version.""" | ||
|
|
||
| name: str | ||
| version: str | ||
| description: str | None = None | ||
| repository: str | None = None | ||
|
|
||
| @classmethod | ||
| def from_definition_file(cls, filepath: Path) -> "SoftwareComponent": | ||
| """Load a Software Component from a definition file.""" | ||
| with open(filepath, "r") as f: | ||
| if filepath.suffix.lower() not in (".yml", ".yaml"): | ||
| raise ValueError("Unsupported file format. Use .json or .yaml/.yml") | ||
| data = yaml.safe_load(f) | ||
| return cls(**data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Observability module.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import logging | ||
| import os | ||
| from typing import Final | ||
|
|
||
| from backend.core.config.env import LOG_LEVEL | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| LOG_FORMAT: Final[str] = "[%(asctime)s][%(levelname)s] %(name)s: %(message)s" | ||
| TIMESTAMP_FORMAT: Final[str] = "%Y-%m-%d %H:%M:%S" | ||
|
|
||
|
|
||
| def setup_logger(): | ||
| """Set up logging configuration.""" | ||
| levels = { | ||
| "CRITICAL": logging.CRITICAL, | ||
| "ERROR": logging.ERROR, | ||
| "WARNING": logging.WARNING, | ||
| "INFO": logging.INFO, | ||
| "DEBUG": logging.DEBUG, | ||
| } | ||
| base_log_level = logging.INFO | ||
| if level_from_env := os.getenv(LOG_LEVEL): | ||
| base_log_level = levels.get(level_from_env.upper(), base_log_level) | ||
| logging.basicConfig( | ||
| format=LOG_FORMAT, datefmt=TIMESTAMP_FORMAT, level=base_log_level | ||
| ) | ||
| logger.debug( | ||
| f"Logging initialized with level: {logging.getLevelName(base_log_level)}" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Service utility helpers.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from typing import Dict | ||
|
|
||
| JsonResponse = Dict[str, object] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import logging | ||
| import time | ||
| from http import HTTPStatus | ||
|
|
||
| import uvicorn | ||
| from fastapi import FastAPI, HTTPException, Request | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from fastapi.responses import JSONResponse | ||
|
|
||
| from backend.core.config.env import load_environment | ||
| from backend.core.obs.logging import setup_logger | ||
| from backend.core.utils.types import JsonResponse | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
| config = load_environment() | ||
| app = FastAPI( | ||
| title=config.app_name, | ||
| version=config.app_version, | ||
| description="Backend service for software component management", | ||
| contact={ | ||
| "name": "Chino Franco", | ||
| "email": "chino.franco@gmail.com", | ||
| "github": "https://github.com/jgfranco17", | ||
| }, | ||
| ) | ||
| startup_time = time.time() | ||
|
|
||
|
|
||
| @app.get("/", status_code=HTTPStatus.OK, tags=["SYSTEM"]) | ||
| def root(): | ||
| """Project main page.""" | ||
| return { | ||
| "message": f"Welcome to the {config.app_name}!", | ||
| "version": config.app_version, | ||
| "debug": config.debug, | ||
| } | ||
|
|
||
|
|
||
| @app.get("/healthz", status_code=HTTPStatus.OK, tags=["SYSTEM"]) | ||
| def health_check() -> JsonResponse: | ||
| """Health check for the API.""" | ||
| return {"status": "ok", "uptime": time.time() - startup_time} | ||
|
|
||
|
|
||
| @app.get("/config", status_code=HTTPStatus.OK, tags=["SYSTEM"]) | ||
| def get_config() -> JsonResponse: | ||
| """Get the current application configuration.""" | ||
| return { | ||
| "app_name": config.app_name, | ||
| "app_version": config.app_version, | ||
| "debug": config.debug, | ||
| "host": config.host, | ||
| "port": config.port, | ||
| "log_level": config.log_level, | ||
| } | ||
|
|
||
|
|
||
| @app.exception_handler(HTTPException) | ||
| async def http_exception_handler(request: Request, exc: HTTPException): | ||
| """General exception handler.""" | ||
| return JSONResponse( | ||
| status_code=exc.status_code, | ||
| content={ | ||
| "message": exc.detail, | ||
| "request": { | ||
| "method": request.method, | ||
| "url": str(request.url), | ||
| "status": exc.status_code, | ||
| }, | ||
| }, | ||
| ) | ||
|
|
||
|
|
||
| app.add_middleware( | ||
| CORSMiddleware, | ||
| allow_origins=["*"], | ||
| allow_credentials=True, | ||
| allow_methods=["*"], | ||
| allow_headers=["*"], | ||
| ) | ||
|
|
||
|
|
||
| def start(): | ||
| """Main entry point for the application.""" | ||
| setup_logger() | ||
| logger.info(f"Starting {config.app_name} v{config.app_version}...") | ||
| uvicorn.run( | ||
| app, | ||
| host=config.host, | ||
| port=config.port, | ||
| reload=config.reload, | ||
| log_level=config.log_level.lower(), | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using wildcard
*for CORS origins in production is a security risk. Consider restricting to specific domains or making this configurable.