Skip to content

Commit 7d50f1f

Browse files
committed
fix: liniting errors
1 parent 7fec657 commit 7d50f1f

File tree

16 files changed

+267
-244
lines changed

16 files changed

+267
-244
lines changed

Makefile

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,4 +216,16 @@ check-patterns:
216216

217217
check-queues:
218218
@echo "📬 RabbitMQ queues:"
219-
docker compose exec rabbitmq rabbitmqctl list_queues name messages
219+
docker compose exec rabbitmq rabbitmqctl list_queues name messages
220+
221+
lint:
222+
@echo "detecting linting errors"
223+
ruff check .
224+
225+
lint-fix:
226+
@echo "fixing linting errors"
227+
ruff check . --fix
228+
229+
lint-format:
230+
@echo "formatting code block"
231+
ruff format .

app/api/logs.py

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010
"""
1111

1212
from datetime import datetime, timedelta
13-
from typing import Optional, Dict, Any
13+
from typing import Optional
1414
from uuid import UUID
1515

1616
from fastapi import APIRouter, Depends, HTTPException, Query, status
1717
from sqlalchemy.ext.asyncio import AsyncSession
1818

19-
from app.core.auth_external import get_current_user, get_current_user_optional
19+
from app.core.auth_external import get_current_user
2020
from app.core.logging import get_logger
2121
from app.db.session import get_db
2222
from app.schemas.log_schemas import (
@@ -44,10 +44,10 @@ async def get_logs(
4444
) -> LogListResponse:
4545
"""
4646
Retrieve processed logs with filtering and pagination.
47-
47+
4848
**Purpose**: Monitoring and debugging only.
4949
**Note**: Log analysis happens automatically via RabbitMQ.
50-
50+
5151
Requires JWT authentication.
5252
"""
5353
log_service = LogService(db)
@@ -82,9 +82,9 @@ async def get_log(
8282
) -> LogEntryResponse:
8383
"""
8484
Retrieve a specific log entry by ID.
85-
85+
8686
**Purpose**: Debugging and detailed investigation.
87-
87+
8888
Requires JWT authentication.
8989
"""
9090
log_service = LogService(db)
@@ -105,12 +105,12 @@ async def get_ai_status(
105105
) -> APIResponse:
106106
"""
107107
Get current AI processing status and configuration.
108-
108+
109109
Returns:
110110
- AI enabled status (if disabled, system uses basic analysis)
111111
- Configuration details
112112
- Processing mode
113-
113+
114114
Note: When AI fails, system automatically falls back to basic analysis.
115115
"""
116116
settings = get_settings()
@@ -119,7 +119,9 @@ async def get_ai_status(
119119
return APIResponse(
120120
data={
121121
"ai_enabled": ai_enabled,
122-
"processing_mode": "AI with automatic fallback" if ai_enabled else "Basic analysis only",
122+
"processing_mode": (
123+
"AI with automatic fallback" if ai_enabled else "Basic analysis only"
124+
),
123125
"ai_timeout_seconds": getattr(settings, 'ai_timeout_seconds', 10),
124126
"ai_retry_attempts": getattr(settings, 'ai_retry_attempts', 2),
125127
"ai_confidence_threshold": getattr(settings, 'ai_confidence_threshold', 0.5),
@@ -138,13 +140,13 @@ async def toggle_ai_processing(
138140
) -> APIResponse:
139141
"""
140142
Toggle AI processing on/off.
141-
143+
142144
This endpoint allows you to:
143145
- Enable AI processing: Uses AI analysis with automatic fallback to basic analysis if AI fails
144146
- Disable AI processing: Uses only basic analysis
145-
147+
146148
Changes are applied immediately to new log processing.
147-
149+
148150
Note: Fallback to basic analysis is ALWAYS enabled when AI is on.
149151
When AI fails, the system automatically uses basic analysis to ensure continuous operation.
150152
"""
@@ -155,16 +157,23 @@ async def toggle_ai_processing(
155157
logger.info(
156158
"ai_processing_toggled",
157159
ai_enabled=enable_ai,
158-
processing_mode="AI with automatic fallback" if enable_ai else "Basic analysis only",
160+
processing_mode=(
161+
"AI with automatic fallback" if enable_ai else "Basic analysis only"
162+
),
159163
user=current_user.get("sub", "unknown"),
160164
)
161165

162166
return APIResponse(
163167
data={
164168
"ai_enabled": enable_ai,
165-
"processing_mode": "AI with automatic fallback" if enable_ai else "Basic analysis only",
169+
"processing_mode": (
170+
"AI with automatic fallback" if enable_ai else "Basic analysis only"
171+
),
166172
"message": f"AI processing {'enabled' if enable_ai else 'disabled'} successfully",
167-
"note": "Fallback to basic analysis is automatic when AI fails. Changes apply to new log processing.",
173+
"note": (
174+
"Fallback to basic analysis is automatic when AI fails. "
175+
"Changes apply to new log processing."
176+
),
168177
},
169178
status_code=200,
170179
message=f"AI processing {'enabled' if enable_ai else 'disabled'}",
@@ -178,7 +187,7 @@ async def get_processing_stats(
178187
) -> APIResponse:
179188
"""
180189
Get processing statistics and system metrics.
181-
190+
182191
Returns:
183192
- Total logs processed
184193
- Logs by level (last 24 hours)
@@ -193,31 +202,31 @@ async def get_processing_stats(
193202
# Get logs by level (last 24 hours)
194203
end_date = datetime.utcnow()
195204
start_date = end_date - timedelta(hours=24)
196-
205+
197206
_, error_count = await log_service.get_logs(
198207
log_level="ERROR",
199208
start_date=start_date,
200209
end_date=end_date,
201210
limit=1
202211
)
203-
212+
204213
_, warning_count = await log_service.get_logs(
205214
log_level="WARNING",
206215
start_date=start_date,
207216
end_date=end_date,
208217
limit=1
209218
)
210-
219+
211220
_, info_count = await log_service.get_logs(
212221
log_level="INFO",
213222
start_date=start_date,
214223
end_date=end_date,
215224
limit=1
216225
)
217-
226+
218227
total_24h = error_count + warning_count + info_count
219228
error_rate = (error_count / total_24h * 100) if total_24h > 0 else 0
220-
229+
221230
return APIResponse(
222231
data={
223232
"total_logs": total_logs,
@@ -230,9 +239,11 @@ async def get_processing_stats(
230239
},
231240
"processing_status": {
232241
"ai_enabled": getattr(get_settings(), 'ai_analysis_enabled', True),
233-
"real_time_processing": getattr(get_settings(), 'enable_real_time_processing', True),
242+
"real_time_processing": getattr(
243+
get_settings(), 'enable_real_time_processing', True
244+
),
234245
},
235246
},
236247
status_code=200,
237248
message="Processing statistics retrieved successfully",
238-
)
249+
)

app/core/auth_external.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,34 +16,34 @@
1616
async def validate_token_with_external_service(token: str) -> Optional[Dict[str, Any]]:
1717
"""
1818
Validate token with external auth service.
19-
19+
2020
Args:
2121
token: JWT token to validate
22-
22+
2323
Returns:
2424
User data if valid, None if invalid
2525
"""
2626
settings = get_settings()
27-
27+
2828
if not settings.auth_service_url:
2929
return None
30-
30+
3131
try:
3232
async with httpx.AsyncClient(timeout=5) as client:
3333
response = await client.post(
3434
f"{settings.auth_service_url}/validate-token",
3535
json={"token": token},
3636
headers={"Content-Type": "application/json"}
3737
)
38-
38+
3939
if response.status_code == 200:
4040
data = response.json()
4141
logger.info("token_validated_with_external_service", user_id=data.get("user_id"))
4242
return data
4343
else:
4444
logger.warning("external_auth_validation_failed", status_code=response.status_code)
4545
return None
46-
46+
4747
except Exception as e:
4848
logger.error("external_auth_error", error=str(e))
4949
return None
@@ -52,15 +52,15 @@ async def validate_token_with_external_service(token: str) -> Optional[Dict[str,
5252
def validate_local_token(token: str) -> Optional[Dict[str, Any]]:
5353
"""
5454
Validate JWT token locally.
55-
55+
5656
Args:
5757
token: JWT token to validate
58-
58+
5959
Returns:
6060
Token payload if valid, None if invalid
6161
"""
6262
settings = get_settings()
63-
63+
6464
try:
6565
payload = jwt.decode(
6666
token,
@@ -79,35 +79,35 @@ async def get_current_user(
7979
) -> Dict[str, Any]:
8080
"""
8181
Dependency to get current authenticated user.
82-
82+
8383
This function:
8484
1. First tries to validate with external auth service (if URL configured)
8585
2. Falls back to local JWT validation
8686
3. Raises 401 if both fail
87-
87+
8888
Args:
8989
credentials: HTTP authorization credentials
90-
90+
9191
Returns:
9292
User information from token
93-
93+
9494
Raises:
9595
HTTPException: If authentication fails
9696
"""
9797
token = credentials.credentials
9898
settings = get_settings()
99-
99+
100100
# Try external auth service first (if configured)
101101
if settings.auth_service_url:
102102
user_data = await validate_token_with_external_service(token)
103103
if user_data:
104104
return user_data
105-
105+
106106
# Fallback to local validation
107107
user_data = validate_local_token(token)
108108
if user_data:
109109
return user_data
110-
110+
111111
# If both fail, raise authentication error
112112
raise HTTPException(
113113
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -121,19 +121,19 @@ async def get_current_user_optional(
121121
) -> Optional[Dict[str, Any]]:
122122
"""
123123
Optional authentication dependency.
124-
124+
125125
Returns user data if authenticated, None if not.
126126
Useful for endpoints that work with or without authentication.
127-
127+
128128
Args:
129129
credentials: Optional HTTP authorization credentials
130-
130+
131131
Returns:
132132
User information if authenticated, None otherwise
133133
"""
134134
if not credentials:
135135
return None
136-
136+
137137
try:
138138
return await get_current_user(credentials)
139139
except HTTPException:
@@ -143,31 +143,31 @@ async def get_current_user_optional(
143143
def create_test_token(user_id: str = "test-user", roles: list = None) -> str:
144144
"""
145145
Create a test JWT token for development/testing.
146-
146+
147147
Args:
148148
user_id: User ID
149149
roles: List of user roles
150-
150+
151151
Returns:
152152
JWT token string
153153
"""
154154
from datetime import datetime, timedelta
155-
155+
156156
settings = get_settings()
157-
157+
158158
payload = {
159159
"sub": user_id,
160160
"user_id": user_id,
161161
"roles": roles or ["user"],
162162
"iat": datetime.utcnow(),
163163
"exp": datetime.utcnow() + timedelta(minutes=settings.jwt_expiration_minutes),
164164
}
165-
165+
166166
token = jwt.encode(
167167
payload,
168168
settings.jwt_secret_key,
169169
algorithm=settings.jwt_algorithm
170170
)
171-
171+
172172
logger.info("test_token_created", user_id=user_id)
173173
return token

app/core/config.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ class Settings(BaseSettings):
7575
api_gateway_public_key: Optional[str] = Field(
7676
default=None, description="API Gateway public key for JWT verification"
7777
)
78-
78+
7979
# External Auth Service Configuration
8080
auth_service_url: Optional[str] = Field(
8181
default=None, description="External auth service URL for token validation"
@@ -103,7 +103,9 @@ class Settings(BaseSettings):
103103

104104
# AI Configuration
105105
ai_analysis_enabled: bool = Field(
106-
default=True, description="Enable AI-powered log analysis (if disabled, uses basic analysis)"
106+
default=True, description=(
107+
"Enable AI-powered log analysis (if disabled, uses basic analysis)"
108+
)
107109
)
108110
ai_timeout_seconds: int = Field(
109111
default=10, ge=1, description="AI analysis timeout in seconds"

0 commit comments

Comments
 (0)