From 57d4d9c4e4ddd0d0f720e408188c0e226e080fdc Mon Sep 17 00:00:00 2001 From: Till Tomczak Date: Fri, 23 May 2025 08:34:22 +0200 Subject: [PATCH] "feat: Update project structure documentation and add health route" --- backend/app.py | 42 +++++++- .../PROJECT_STRUCTURE.md | 0 frontend/src/app/health/route.ts | 49 +++++++++ start.ps1 | 100 ------------------ 4 files changed, 90 insertions(+), 101 deletions(-) rename PROJECT_STRUCTURE.md => docs/PROJECT_STRUCTURE.md (100%) create mode 100644 frontend/src/app/health/route.ts delete mode 100644 start.ps1 diff --git a/backend/app.py b/backend/app.py index fc8b704e..5c3cec41 100755 --- a/backend/app.py +++ b/backend/app.py @@ -1,5 +1,6 @@ from flask import Flask, request, jsonify, g, redirect, url_for, session as flask_session, render_template, flash, send_from_directory from werkzeug.security import generate_password_hash, check_password_hash +from flask_cors import CORS import secrets # Für bessere Salt-Generierung from functools import wraps import jwt @@ -40,6 +41,14 @@ def create_app(config_name=None): """ app = Flask(__name__) + # CORS-Konfiguration für Frontend-Server + cors_origins = os.environ.get('CORS_ORIGINS', 'http://localhost:3000').split(',') + CORS(app, + origins=cors_origins, + supports_credentials=True, + allow_headers=['Content-Type', 'Authorization', 'X-Requested-With'], + methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']) + # Bestimme Konfiguration if config_name is None: config_name = os.environ.get('FLASK_ENV', 'development') @@ -86,6 +95,14 @@ def create_app(config_name=None): # Initialisierung - wird später durch create_app ersetzt app = Flask(__name__) +# CORS-Konfiguration für Frontend-Server (Legacy) +cors_origins = os.environ.get('CORS_ORIGINS', 'http://localhost:3000').split(',') +CORS(app, + origins=cors_origins, + supports_credentials=True, + allow_headers=['Content-Type', 'Authorization', 'X-Requested-With'], + methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']) + # Initialisiere Netzwerkkonfiguration network_config = NetworkConfig(app) @@ -1705,7 +1722,30 @@ def job_status(job_id): @app.route('/api/test', methods=['GET']) def test(): - return jsonify({'message': 'MYP Backend API funktioniert!'}) + return jsonify({'message': 'API funktioniert!', 'status': 'success'}) + +@app.route('/health', methods=['GET']) +def health_check(): + """Health Check Endpoint für Backend-Server""" + try: + # Prüfe Datenbankverbindung + db = get_db() + db.execute('SELECT 1').fetchone() + + return jsonify({ + 'status': 'healthy', + 'service': 'myp-backend', + 'timestamp': datetime.datetime.utcnow().isoformat() + 'Z', + 'version': '1.0.0', + 'database': 'connected' + }), 200 + except Exception as e: + return jsonify({ + 'status': 'unhealthy', + 'service': 'myp-backend', + 'timestamp': datetime.datetime.utcnow().isoformat() + 'Z', + 'error': str(e) + }), 503 @app.route('/api/create-initial-admin', methods=['POST']) def create_initial_admin(): diff --git a/PROJECT_STRUCTURE.md b/docs/PROJECT_STRUCTURE.md similarity index 100% rename from PROJECT_STRUCTURE.md rename to docs/PROJECT_STRUCTURE.md diff --git a/frontend/src/app/health/route.ts b/frontend/src/app/health/route.ts new file mode 100644 index 00000000..6a306f89 --- /dev/null +++ b/frontend/src/app/health/route.ts @@ -0,0 +1,49 @@ +import { NextRequest, NextResponse } from 'next/server'; + +/** + * Health Check Endpoint für Frontend-Server + * GET /health + */ +export async function GET(request: NextRequest) { + try { + // Prüfe Backend-Verbindung + const backendUrl = process.env.BACKEND_API_URL || 'http://localhost:5000'; + let backendStatus = 'unknown'; + + try { + // AbortController für Timeout verwenden + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + + const backendResponse = await fetch(`${backendUrl}/health`, { + method: 'GET', + signal: controller.signal, + }); + + clearTimeout(timeoutId); + backendStatus = backendResponse.ok ? 'connected' : 'error'; + } catch { + backendStatus = 'disconnected'; + } + + return NextResponse.json({ + status: 'healthy', + service: 'myp-frontend', + timestamp: new Date().toISOString(), + version: '1.0.0', + backend: { + url: backendUrl, + status: backendStatus + }, + environment: process.env.NODE_ENV || 'development' + }, { status: 200 }); + + } catch (error) { + return NextResponse.json({ + status: 'unhealthy', + service: 'myp-frontend', + timestamp: new Date().toISOString(), + error: error instanceof Error ? error.message : 'Unknown error' + }, { status: 503 }); + } +} \ No newline at end of file diff --git a/start.ps1 b/start.ps1 deleted file mode 100644 index 1906b7c1..00000000 --- a/start.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -# 🚀 MYP - Manage your Printer (Hauptstartskript) -# Weiterleitung an das optimierte Infrastructure-Startskript - -param( - [Parameter(Position=0)] - [ValidateSet("dev", "prod", "test", "development", "production")] - [string]$Environment = "dev", - - [switch]$Help, - [switch]$Version, - [switch]$Clean -) - -# Farbdefinitionen für bessere Ausgabe -$Colors = @{ - Info = "Cyan" - Success = "Green" - Warning = "Yellow" - Error = "Red" - Header = "Magenta" -} - -function Write-ColorOutput { - param([string]$Message, [string]$Color = "White") - Write-Host $Message -ForegroundColor $Colors[$Color] -} - -# Header anzeigen -Write-ColorOutput "MYP - Manage your Printer" "Header" -Write-ColorOutput "=======================================" "Header" - -# Hilfe anzeigen -if ($Help) { - Write-ColorOutput "`nVerwendung:" "Info" - Write-ColorOutput " .\start.ps1 [Environment] [Optionen]" "White" - Write-ColorOutput "`nVerfügbare Umgebungen:" "Info" - Write-ColorOutput " dev, development - Entwicklungsumgebung (Standard)" "White" - Write-ColorOutput " prod, production - Produktionsumgebung" "White" - Write-ColorOutput " test - Testumgebung" "White" - Write-ColorOutput "`nOptionen:" "Info" - Write-ColorOutput " -Help - Diese Hilfe anzeigen" "White" - Write-ColorOutput " -Version - Versionsinformationen anzeigen" "White" - Write-ColorOutput " -Clean - System vor Start bereinigen" "White" - Write-ColorOutput "`nBeispiele:" "Info" - Write-ColorOutput " .\start.ps1 # Entwicklungsumgebung starten" "White" - Write-ColorOutput " .\start.ps1 prod # Produktionsumgebung starten" "White" - Write-ColorOutput " .\start.ps1 dev -Clean # Mit Bereinigung starten" "White" - exit 0 -} - -# Version anzeigen -if ($Version) { - Write-ColorOutput "`nSysteminformationen:" "Info" - Write-ColorOutput " MYP Version: 2.0.0" "White" - Write-ColorOutput " PowerShell: $($PSVersionTable.PSVersion)" "White" - Write-ColorOutput " OS: $($PSVersionTable.OS)" "White" - Write-ColorOutput " Architektur: $env:PROCESSOR_ARCHITECTURE" "White" - exit 0 -} - -# Bereinigung falls gewünscht -if ($Clean) { - Write-ColorOutput "`nSystem wird bereinigt..." "Warning" - & ".\infrastructure\scripts\cleanup.ps1" -Force - if ($LASTEXITCODE -ne 0) { - Write-ColorOutput "Bereinigung fehlgeschlagen!" "Error" - exit 1 - } - Write-ColorOutput "System erfolgreich bereinigt!" "Success" -} - -# Prüfe ob Infrastructure-Skript existiert -$InfraScript = ".\infrastructure\scripts\start.ps1" -if (-not (Test-Path $InfraScript)) { - Write-ColorOutput "`nInfrastructure-Startskript nicht gefunden: $InfraScript" "Error" - Write-ColorOutput " Bitte stellen Sie sicher, dass die Projektstruktur vollständig ist." "Error" - exit 1 -} - -# Weiterleitung an Infrastructure-Skript -Write-ColorOutput "`nWeiterleitung an Infrastructure-Startskript..." "Info" -Write-ColorOutput " Umgebung: $Environment" "White" - -try { - & $InfraScript $Environment - $ExitCode = $LASTEXITCODE - - if ($ExitCode -eq 0) { - Write-ColorOutput "`nMYP erfolgreich gestartet!" "Success" - Write-ColorOutput " Zugriff über: http://localhost" "Info" - } else { - Write-ColorOutput "`nStart fehlgeschlagen (Exit Code: $ExitCode)" "Error" - } - - exit $ExitCode -} catch { - Write-ColorOutput "`nUnerwarteter Fehler beim Start:" "Error" - Write-ColorOutput " $($_.Exception.Message)" "Error" - exit 1 -} \ No newline at end of file