atlan-application-sdk 0.1.1rc38__py3-none-any.whl → 0.1.1rc40__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- application_sdk/activities/.cursor/BUGBOT.md +424 -0
- application_sdk/clients/.cursor/BUGBOT.md +280 -0
- application_sdk/clients/sql.py +110 -74
- application_sdk/clients/temporal.py +4 -2
- application_sdk/common/.cursor/BUGBOT.md +316 -0
- application_sdk/constants.py +8 -0
- application_sdk/decorators/.cursor/BUGBOT.md +279 -0
- application_sdk/inputs/.cursor/BUGBOT.md +250 -0
- application_sdk/interceptors/.cursor/BUGBOT.md +320 -0
- application_sdk/interceptors/cleanup.py +171 -0
- application_sdk/interceptors/events.py +6 -6
- application_sdk/outputs/.cursor/BUGBOT.md +295 -0
- application_sdk/outputs/iceberg.py +4 -0
- application_sdk/outputs/json.py +6 -0
- application_sdk/outputs/parquet.py +89 -34
- application_sdk/server/.cursor/BUGBOT.md +442 -0
- application_sdk/services/objectstore.py +98 -20
- application_sdk/version.py +1 -1
- application_sdk/workflows/.cursor/BUGBOT.md +218 -0
- {atlan_application_sdk-0.1.1rc38.dist-info → atlan_application_sdk-0.1.1rc40.dist-info}/METADATA +1 -1
- {atlan_application_sdk-0.1.1rc38.dist-info → atlan_application_sdk-0.1.1rc40.dist-info}/RECORD +24 -14
- {atlan_application_sdk-0.1.1rc38.dist-info → atlan_application_sdk-0.1.1rc40.dist-info}/WHEEL +0 -0
- {atlan_application_sdk-0.1.1rc38.dist-info → atlan_application_sdk-0.1.1rc40.dist-info}/licenses/LICENSE +0 -0
- {atlan_application_sdk-0.1.1rc38.dist-info → atlan_application_sdk-0.1.1rc40.dist-info}/licenses/NOTICE +0 -0
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
# Server Code Review Guidelines - FastAPI Applications
|
|
2
|
+
|
|
3
|
+
## Context-Specific Patterns
|
|
4
|
+
|
|
5
|
+
This directory contains FastAPI server implementations, middleware, routers, and API endpoint definitions. These components handle HTTP requests, authentication, and API responses.
|
|
6
|
+
|
|
7
|
+
### Phase 1: Critical Server Safety Issues
|
|
8
|
+
|
|
9
|
+
**API Security Requirements:**
|
|
10
|
+
|
|
11
|
+
- All endpoints must have proper input validation using Pydantic models
|
|
12
|
+
- Authentication and authorization must be enforced on protected endpoints
|
|
13
|
+
- No sensitive data in API responses (passwords, tokens, internal IDs)
|
|
14
|
+
- Request rate limiting must be implemented for public endpoints
|
|
15
|
+
- CORS configuration must be explicit and restrictive
|
|
16
|
+
|
|
17
|
+
**Input Validation and Sanitization:**
|
|
18
|
+
|
|
19
|
+
- All request bodies must use Pydantic models for validation
|
|
20
|
+
- Query parameters must be validated with proper types
|
|
21
|
+
- File uploads must have size and type restrictions
|
|
22
|
+
- SQL injection prevention in any database queries
|
|
23
|
+
- No raw user input in log messages
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
# ✅ DO: Proper input validation
|
|
27
|
+
from pydantic import BaseModel, Field, validator
|
|
28
|
+
|
|
29
|
+
class CreateUserRequest(BaseModel):
|
|
30
|
+
username: str = Field(..., min_length=3, max_length=50, regex="^[a-zA-Z0-9_]+$")
|
|
31
|
+
email: str = Field(..., regex=r'^[\w\.-]+@[\w\.-]+\.\w+$')
|
|
32
|
+
age: int = Field(..., ge=18, le=120)
|
|
33
|
+
|
|
34
|
+
@validator('username')
|
|
35
|
+
def username_must_not_contain_prohibited_words(cls, v):
|
|
36
|
+
prohibited = ['admin', 'root', 'system']
|
|
37
|
+
if any(word in v.lower() for word in prohibited):
|
|
38
|
+
raise ValueError('Username contains prohibited words')
|
|
39
|
+
return v
|
|
40
|
+
|
|
41
|
+
@app.post("/users/", response_model=UserResponse)
|
|
42
|
+
async def create_user(user_data: CreateUserRequest):
|
|
43
|
+
# Input is already validated by Pydantic
|
|
44
|
+
return await user_service.create_user(user_data)
|
|
45
|
+
|
|
46
|
+
# ❌ NEVER: Raw input without validation
|
|
47
|
+
@app.post("/users/")
|
|
48
|
+
async def bad_create_user(request: dict): # No validation!
|
|
49
|
+
username = request.get("username") # Could be anything
|
|
50
|
+
return await user_service.create_user(username)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Phase 2: FastAPI Architecture Patterns
|
|
54
|
+
|
|
55
|
+
**Router Organization:**
|
|
56
|
+
|
|
57
|
+
- Group related endpoints in separate router modules
|
|
58
|
+
- Use consistent URL patterns and naming conventions
|
|
59
|
+
- Implement proper HTTP status codes for all responses
|
|
60
|
+
- Use response models for all endpoint returns
|
|
61
|
+
- Implement proper error handling with HTTP exceptions
|
|
62
|
+
|
|
63
|
+
**Dependency Injection:**
|
|
64
|
+
|
|
65
|
+
- Use FastAPI's dependency injection for database connections
|
|
66
|
+
- Implement proper dependency scoping (request, application)
|
|
67
|
+
- Create reusable dependencies for authentication, logging, etc.
|
|
68
|
+
- Use dependency override for testing
|
|
69
|
+
- Implement proper cleanup for dependencies
|
|
70
|
+
|
|
71
|
+
**Async Pattern Enforcement:**
|
|
72
|
+
|
|
73
|
+
- **Always use async/await for I/O operations**: Database queries, external API calls, file operations
|
|
74
|
+
- **Non-blocking operations**: Ensure that async endpoints don't accidentally use blocking operations
|
|
75
|
+
- **Proper context switching**: Use async context managers for resource management
|
|
76
|
+
- **Background task usage**: Use FastAPI BackgroundTasks for non-critical operations that shouldn't block responses
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# ✅ DO: Proper async patterns
|
|
80
|
+
from fastapi import BackgroundTasks
|
|
81
|
+
|
|
82
|
+
@router.post("/users/", response_model=UserResponse)
|
|
83
|
+
async def create_user_async(
|
|
84
|
+
user_data: CreateUserRequest,
|
|
85
|
+
background_tasks: BackgroundTasks,
|
|
86
|
+
db: AsyncConnection = Depends(get_async_db)
|
|
87
|
+
) -> UserResponse:
|
|
88
|
+
"""Create user with proper async patterns."""
|
|
89
|
+
|
|
90
|
+
# Main operation - blocking response
|
|
91
|
+
async with db.transaction():
|
|
92
|
+
user = await user_service.create_user_async(db, user_data)
|
|
93
|
+
|
|
94
|
+
# Non-critical operations in background (don't block response)
|
|
95
|
+
background_tasks.add_task(send_welcome_email, user.email)
|
|
96
|
+
background_tasks.add_task(update_analytics, "user_created")
|
|
97
|
+
|
|
98
|
+
return user
|
|
99
|
+
|
|
100
|
+
# ❌ REJECT: Mixed async/sync patterns
|
|
101
|
+
@router.post("/users/")
|
|
102
|
+
async def bad_async_patterns(user_data: dict):
|
|
103
|
+
# Blocking database call in async function
|
|
104
|
+
user = sync_db_connection.execute(f"INSERT INTO users...") # Blocks event loop
|
|
105
|
+
|
|
106
|
+
# Synchronous email sending that blocks response
|
|
107
|
+
email_client.send_email(user.email, "Welcome") # Should be background task
|
|
108
|
+
|
|
109
|
+
return {"status": "created"}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
# ✅ DO: Proper FastAPI router with dependencies
|
|
114
|
+
from fastapi import APIRouter, Depends, HTTPException, status
|
|
115
|
+
from typing import List
|
|
116
|
+
|
|
117
|
+
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
|
118
|
+
|
|
119
|
+
async def get_db_connection():
|
|
120
|
+
async with database_pool.acquire() as conn:
|
|
121
|
+
try:
|
|
122
|
+
yield conn
|
|
123
|
+
finally:
|
|
124
|
+
# Connection automatically returned to pool
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
128
|
+
user = await auth_service.get_user_from_token(token)
|
|
129
|
+
if not user:
|
|
130
|
+
raise HTTPException(
|
|
131
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
132
|
+
detail="Invalid authentication credentials",
|
|
133
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
134
|
+
)
|
|
135
|
+
return user
|
|
136
|
+
|
|
137
|
+
@router.get("/{user_id}", response_model=UserResponse)
|
|
138
|
+
async def get_user(
|
|
139
|
+
user_id: int,
|
|
140
|
+
current_user: User = Depends(get_current_user),
|
|
141
|
+
db: AsyncConnection = Depends(get_db_connection)
|
|
142
|
+
):
|
|
143
|
+
if user_id != current_user.id and not current_user.is_admin:
|
|
144
|
+
raise HTTPException(
|
|
145
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
146
|
+
detail="Not authorized to access this user"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
user = await user_service.get_user(db, user_id)
|
|
150
|
+
if not user:
|
|
151
|
+
raise HTTPException(
|
|
152
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
153
|
+
detail="User not found"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
return user
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**Logging Standards:**
|
|
160
|
+
|
|
161
|
+
- **Appropriate log levels**: Use correct log levels for different types of messages
|
|
162
|
+
|
|
163
|
+
- DEBUG: Development/debugging information
|
|
164
|
+
- INFO: General operational information, successful operations
|
|
165
|
+
- WARNING: Potentially problematic situations that don't prevent operation
|
|
166
|
+
- ERROR: Error conditions that may still allow operation to continue
|
|
167
|
+
- CRITICAL: Serious errors that may prevent program from continuing
|
|
168
|
+
|
|
169
|
+
- **Context inclusion**: Include request IDs, user information, and operation context
|
|
170
|
+
- **Structured logging**: Use consistent log formats that can be parsed by log aggregation tools
|
|
171
|
+
- **No sensitive data**: Never log passwords, tokens, or personal information
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
# ✅ DO: Proper logging levels and context
|
|
175
|
+
import logging
|
|
176
|
+
|
|
177
|
+
logger = logging.getLogger(__name__)
|
|
178
|
+
|
|
179
|
+
@router.post("/users/{user_id}/reset-password")
|
|
180
|
+
async def reset_password(user_id: int, request_id: str = Depends(get_request_id)):
|
|
181
|
+
"""Reset user password with proper logging."""
|
|
182
|
+
|
|
183
|
+
# INFO: Normal operation
|
|
184
|
+
logger.info(f"Password reset requested for user {user_id}", extra={
|
|
185
|
+
"request_id": request_id,
|
|
186
|
+
"user_id": user_id,
|
|
187
|
+
"operation": "password_reset"
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
await password_service.reset_password(user_id)
|
|
192
|
+
|
|
193
|
+
# INFO: Successful completion
|
|
194
|
+
logger.info(f"Password reset completed for user {user_id}", extra={
|
|
195
|
+
"request_id": request_id,
|
|
196
|
+
"user_id": user_id,
|
|
197
|
+
"status": "success"
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
except UserNotFoundError:
|
|
201
|
+
# WARNING: Expected error that doesn't prevent system operation
|
|
202
|
+
logger.warning(f"Password reset attempted for non-existent user {user_id}", extra={
|
|
203
|
+
"request_id": request_id,
|
|
204
|
+
"user_id": user_id,
|
|
205
|
+
"error_type": "user_not_found"
|
|
206
|
+
})
|
|
207
|
+
raise HTTPException(status_code=404, detail="User not found")
|
|
208
|
+
|
|
209
|
+
except DatabaseConnectionError as e:
|
|
210
|
+
# ERROR: Unexpected error that prevents operation but system can continue
|
|
211
|
+
logger.error(f"Database connection failed during password reset", extra={
|
|
212
|
+
"request_id": request_id,
|
|
213
|
+
"user_id": user_id,
|
|
214
|
+
"error": str(e),
|
|
215
|
+
"operation": "password_reset"
|
|
216
|
+
})
|
|
217
|
+
raise HTTPException(status_code=500, detail="Service temporarily unavailable")
|
|
218
|
+
|
|
219
|
+
# ❌ REJECT: Inappropriate log levels and missing context
|
|
220
|
+
@router.post("/users/login")
|
|
221
|
+
async def bad_logging_example(credentials: dict):
|
|
222
|
+
logger.error("User login attempted") # Should be INFO, not ERROR
|
|
223
|
+
|
|
224
|
+
if not credentials.get("username"):
|
|
225
|
+
logger.debug("Login failed - no username") # Should be WARNING with context
|
|
226
|
+
return {"error": "Bad request"}
|
|
227
|
+
|
|
228
|
+
logger.critical("Processing login") # Should be DEBUG or INFO, not CRITICAL
|
|
229
|
+
|
|
230
|
+
# No context, wrong levels, missing request tracking
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Phase 3: Server Testing Requirements
|
|
234
|
+
|
|
235
|
+
**API Testing Standards:**
|
|
236
|
+
|
|
237
|
+
- Use FastAPI's TestClient for endpoint testing
|
|
238
|
+
- Test all HTTP status codes (success, client errors, server errors)
|
|
239
|
+
- Test authentication and authorization scenarios
|
|
240
|
+
- Test input validation with invalid data
|
|
241
|
+
- Mock external dependencies in API tests
|
|
242
|
+
- Include integration tests with real database
|
|
243
|
+
|
|
244
|
+
**Request/Response Testing:**
|
|
245
|
+
|
|
246
|
+
- Test request body validation with Pydantic models
|
|
247
|
+
- Test query parameter validation
|
|
248
|
+
- Test response model serialization
|
|
249
|
+
- Test error response formats
|
|
250
|
+
- Test file upload functionality
|
|
251
|
+
- Include performance tests for API endpoints
|
|
252
|
+
|
|
253
|
+
### Phase 4: Performance and Scalability
|
|
254
|
+
|
|
255
|
+
**API Performance:**
|
|
256
|
+
|
|
257
|
+
- Use async/await for all I/O operations
|
|
258
|
+
- Implement proper database connection pooling
|
|
259
|
+
- Use response caching where appropriate
|
|
260
|
+
- Implement request batching for bulk operations
|
|
261
|
+
- Monitor API response times and error rates
|
|
262
|
+
|
|
263
|
+
**Middleware and Request Processing:**
|
|
264
|
+
|
|
265
|
+
- Implement request logging middleware with correlation IDs
|
|
266
|
+
- Use compression middleware for large responses
|
|
267
|
+
- Implement proper timeout handling for long-running operations
|
|
268
|
+
- Use background tasks for non-critical operations
|
|
269
|
+
- Monitor memory usage and connection counts
|
|
270
|
+
|
|
271
|
+
```python
|
|
272
|
+
# ✅ DO: Efficient async endpoint with proper error handling
|
|
273
|
+
@router.post("/users/bulk", response_model=List[UserResponse])
|
|
274
|
+
async def create_users_bulk(
|
|
275
|
+
users_data: List[CreateUserRequest],
|
|
276
|
+
background_tasks: BackgroundTasks,
|
|
277
|
+
db: AsyncConnection = Depends(get_db_connection),
|
|
278
|
+
current_user: User = Depends(get_admin_user)
|
|
279
|
+
):
|
|
280
|
+
if len(users_data) > 100: # Prevent abuse
|
|
281
|
+
raise HTTPException(
|
|
282
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
283
|
+
detail="Cannot create more than 100 users at once"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
# Batch operation for better performance
|
|
288
|
+
created_users = await user_service.create_users_batch(db, users_data)
|
|
289
|
+
|
|
290
|
+
# Non-critical operation in background
|
|
291
|
+
background_tasks.add_task(
|
|
292
|
+
send_welcome_emails,
|
|
293
|
+
[user.email for user in created_users]
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
return created_users
|
|
297
|
+
|
|
298
|
+
except ValidationError as e:
|
|
299
|
+
raise HTTPException(
|
|
300
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
301
|
+
detail=f"Validation failed: {e}"
|
|
302
|
+
)
|
|
303
|
+
except Exception as e:
|
|
304
|
+
logger.error(f"Bulk user creation failed: {e}", exc_info=True)
|
|
305
|
+
raise HTTPException(
|
|
306
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
307
|
+
detail="Internal server error"
|
|
308
|
+
)
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
### Phase 5: Server Maintainability
|
|
312
|
+
|
|
313
|
+
**API Documentation and Versioning:**
|
|
314
|
+
|
|
315
|
+
- Use OpenAPI tags for endpoint organization
|
|
316
|
+
- Document all endpoints with proper descriptions
|
|
317
|
+
- Implement API versioning strategy
|
|
318
|
+
- Use response examples in OpenAPI documentation
|
|
319
|
+
- Document all possible error responses
|
|
320
|
+
|
|
321
|
+
**Configuration and Environment:**
|
|
322
|
+
|
|
323
|
+
- Externalize all server configuration
|
|
324
|
+
- Use environment-specific settings
|
|
325
|
+
- Implement proper CORS configuration
|
|
326
|
+
- Configure security headers
|
|
327
|
+
- Document all configuration options
|
|
328
|
+
|
|
329
|
+
---
|
|
330
|
+
|
|
331
|
+
## Server-Specific Anti-Patterns
|
|
332
|
+
|
|
333
|
+
**Always Reject:**
|
|
334
|
+
|
|
335
|
+
- Endpoints without input validation
|
|
336
|
+
- Missing authentication on protected endpoints
|
|
337
|
+
- Raw dictionaries instead of Pydantic models
|
|
338
|
+
- Generic exception handling without proper HTTP responses
|
|
339
|
+
- Hardcoded configuration values
|
|
340
|
+
- Missing CORS configuration
|
|
341
|
+
- Endpoints without proper HTTP status codes
|
|
342
|
+
- Blocking operations in async endpoints
|
|
343
|
+
|
|
344
|
+
**Logging Anti-Patterns:**
|
|
345
|
+
|
|
346
|
+
- **Wrong log levels**: Using ERROR for normal operations, DEBUG for production warnings
|
|
347
|
+
- **Missing context**: Log messages without request IDs, user context, or operation details
|
|
348
|
+
- **Sensitive data**: Logging passwords, tokens, personal information
|
|
349
|
+
- **Inconsistent formats**: Different log formats that can't be parsed consistently
|
|
350
|
+
|
|
351
|
+
**Async Pattern Anti-Patterns:**
|
|
352
|
+
|
|
353
|
+
- **Blocking in async**: Using synchronous database calls or file operations in async endpoints
|
|
354
|
+
- **Missing background tasks**: Long-running operations that block API responses
|
|
355
|
+
- **Sync/async mixing**: Inconsistent use of async patterns within the same service
|
|
356
|
+
|
|
357
|
+
**Input Validation Anti-Patterns:**
|
|
358
|
+
|
|
359
|
+
```python
|
|
360
|
+
# ❌ REJECT: No input validation
|
|
361
|
+
@app.post("/users/")
|
|
362
|
+
async def bad_endpoint(data: dict): # No validation
|
|
363
|
+
username = data["username"] # Could fail with KeyError
|
|
364
|
+
# No type checking, no sanitization
|
|
365
|
+
return {"status": "created"}
|
|
366
|
+
|
|
367
|
+
# ✅ REQUIRE: Proper validation with Pydantic
|
|
368
|
+
@app.post("/users/", response_model=UserResponse)
|
|
369
|
+
async def good_endpoint(user_data: CreateUserRequest):
|
|
370
|
+
# Pydantic automatically validates input
|
|
371
|
+
validated_user = await user_service.create_user(user_data)
|
|
372
|
+
return validated_user
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
**Error Handling Anti-Patterns:**
|
|
376
|
+
|
|
377
|
+
```python
|
|
378
|
+
# ❌ REJECT: Poor error handling and logging
|
|
379
|
+
@app.get("/users/{user_id}")
|
|
380
|
+
async def bad_get_user(user_id: int):
|
|
381
|
+
logger.error(f"Getting user {user_id}") # Wrong log level
|
|
382
|
+
try:
|
|
383
|
+
user = await user_service.get_user(user_id)
|
|
384
|
+
return user # No response model
|
|
385
|
+
except Exception as e:
|
|
386
|
+
logger.debug(f"User lookup failed: {e}") # Should be ERROR with context
|
|
387
|
+
return {"error": str(e)} # Wrong HTTP status, exposes internals
|
|
388
|
+
|
|
389
|
+
# ✅ REQUIRE: Proper error handling and logging
|
|
390
|
+
@app.get("/users/{user_id}", response_model=UserResponse)
|
|
391
|
+
async def good_get_user(user_id: int, request_id: str = Depends(get_request_id)):
|
|
392
|
+
logger.info(f"Retrieving user {user_id}", extra={"request_id": request_id})
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
user = await user_service.get_user(user_id)
|
|
396
|
+
if not user:
|
|
397
|
+
logger.warning(f"User {user_id} not found", extra={
|
|
398
|
+
"request_id": request_id,
|
|
399
|
+
"user_id": user_id
|
|
400
|
+
})
|
|
401
|
+
raise HTTPException(
|
|
402
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
403
|
+
detail="User not found"
|
|
404
|
+
)
|
|
405
|
+
return user
|
|
406
|
+
except ValidationError as e:
|
|
407
|
+
logger.warning(f"Invalid user ID format: {user_id}", extra={
|
|
408
|
+
"request_id": request_id,
|
|
409
|
+
"error": str(e)
|
|
410
|
+
})
|
|
411
|
+
raise HTTPException(
|
|
412
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
413
|
+
detail=f"Invalid request: {e}"
|
|
414
|
+
)
|
|
415
|
+
except Exception as e:
|
|
416
|
+
logger.error(f"User retrieval failed for {user_id}: {e}", extra={
|
|
417
|
+
"request_id": request_id,
|
|
418
|
+
"user_id": user_id
|
|
419
|
+
}, exc_info=True)
|
|
420
|
+
raise HTTPException(
|
|
421
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
422
|
+
detail="Internal server error"
|
|
423
|
+
)
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
## Educational Context for Server Reviews
|
|
427
|
+
|
|
428
|
+
When reviewing server code, emphasize:
|
|
429
|
+
|
|
430
|
+
1. **Security Impact**: "API endpoints are the primary attack surface. Proper input validation and authentication aren't just good practices - they're essential for preventing data breaches and unauthorized access."
|
|
431
|
+
|
|
432
|
+
2. **Performance Impact**: "Server performance directly affects user experience. Blocking operations in async endpoints can cause cascading slowdowns that affect all API users."
|
|
433
|
+
|
|
434
|
+
3. **Reliability Impact**: "Proper error handling in APIs determines whether clients can gracefully handle failures or crash unexpectedly. Clear error responses help clients implement proper retry logic."
|
|
435
|
+
|
|
436
|
+
4. **Maintainability Impact**: "Well-structured FastAPI applications with proper dependency injection and router organization make it easier for teams to add features and maintain the codebase as it grows."
|
|
437
|
+
|
|
438
|
+
5. **Observability Impact**: "API logging and monitoring are critical for debugging production issues. Proper request correlation IDs and structured logging make the difference between quick problem resolution and extended outages."
|
|
439
|
+
|
|
440
|
+
6. **Async Pattern Impact**: "Proper async patterns are essential for handling concurrent requests efficiently. Blocking operations in async code can degrade performance for all users and cause connection pool exhaustion."
|
|
441
|
+
|
|
442
|
+
7. **Logging Quality Impact**: "Appropriate log levels and structured context are crucial for operational visibility. Wrong log levels create noise and hide real issues, while missing context makes debugging nearly impossible."
|
|
@@ -26,6 +26,31 @@ class ObjectStore:
|
|
|
26
26
|
OBJECT_CREATE_OPERATION = "create"
|
|
27
27
|
OBJECT_GET_OPERATION = "get"
|
|
28
28
|
OBJECT_LIST_OPERATION = "list"
|
|
29
|
+
OBJECT_DELETE_OPERATION = "delete"
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def _create_file_metadata(cls, key: str) -> dict[str, str]:
|
|
33
|
+
"""Create metadata for file operations (get, delete, create).
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
key: The file key/path.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
Metadata dictionary with key, fileName, and blobName fields.
|
|
40
|
+
"""
|
|
41
|
+
return {"key": key, "fileName": key, "blobName": key}
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def _create_list_metadata(cls, prefix: str) -> dict[str, str]:
|
|
45
|
+
"""Create metadata for list operations.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
prefix: The prefix to list files under.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Metadata dictionary with prefix and fileName fields, or empty dict if no prefix.
|
|
52
|
+
"""
|
|
53
|
+
return {"prefix": prefix, "fileName": prefix} if prefix else {}
|
|
29
54
|
|
|
30
55
|
@classmethod
|
|
31
56
|
async def list_files(
|
|
@@ -44,12 +69,11 @@ class ObjectStore:
|
|
|
44
69
|
Exception: If there's an error listing files from the object store.
|
|
45
70
|
"""
|
|
46
71
|
try:
|
|
47
|
-
metadata = {"prefix": prefix, "fileName": prefix} if prefix else {}
|
|
48
72
|
data = json.dumps({"prefix": prefix}).encode("utf-8") if prefix else ""
|
|
49
73
|
|
|
50
74
|
response_data = await cls._invoke_dapr_binding(
|
|
51
75
|
operation=cls.OBJECT_LIST_OPERATION,
|
|
52
|
-
metadata=
|
|
76
|
+
metadata=cls._create_list_metadata(prefix),
|
|
53
77
|
data=data,
|
|
54
78
|
store_name=store_name,
|
|
55
79
|
)
|
|
@@ -105,12 +129,11 @@ class ObjectStore:
|
|
|
105
129
|
Exception: If there's an error getting the file from the object store.
|
|
106
130
|
"""
|
|
107
131
|
try:
|
|
108
|
-
metadata = {"key": key, "fileName": key, "blobName": key}
|
|
109
132
|
data = json.dumps({"key": key}).encode("utf-8") if key else ""
|
|
110
133
|
|
|
111
134
|
response_data = await cls._invoke_dapr_binding(
|
|
112
135
|
operation=cls.OBJECT_GET_OPERATION,
|
|
113
|
-
metadata=
|
|
136
|
+
metadata=cls._create_file_metadata(key),
|
|
114
137
|
data=data,
|
|
115
138
|
store_name=store_name,
|
|
116
139
|
)
|
|
@@ -144,20 +167,76 @@ class ObjectStore:
|
|
|
144
167
|
return False
|
|
145
168
|
|
|
146
169
|
@classmethod
|
|
147
|
-
async def
|
|
170
|
+
async def delete_file(
|
|
148
171
|
cls, key: str, store_name: str = DEPLOYMENT_OBJECT_STORE_NAME
|
|
149
172
|
) -> None:
|
|
150
|
-
"""Delete a file
|
|
173
|
+
"""Delete a single file from the object store.
|
|
151
174
|
|
|
152
175
|
Args:
|
|
153
|
-
key: The file path
|
|
176
|
+
key: The file path to delete.
|
|
154
177
|
store_name: Name of the Dapr object store binding to use.
|
|
155
178
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
179
|
+
Raises:
|
|
180
|
+
Exception: If there's an error deleting the file from the object store.
|
|
181
|
+
"""
|
|
182
|
+
try:
|
|
183
|
+
data = json.dumps({"key": key}).encode("utf-8")
|
|
184
|
+
|
|
185
|
+
await cls._invoke_dapr_binding(
|
|
186
|
+
operation=cls.OBJECT_DELETE_OPERATION,
|
|
187
|
+
metadata=cls._create_file_metadata(key),
|
|
188
|
+
data=data,
|
|
189
|
+
store_name=store_name,
|
|
190
|
+
)
|
|
191
|
+
logger.debug(f"Successfully deleted file: {key}")
|
|
192
|
+
except Exception as e:
|
|
193
|
+
logger.error(f"Error deleting file {key}: {str(e)}")
|
|
194
|
+
raise
|
|
195
|
+
|
|
196
|
+
@classmethod
|
|
197
|
+
async def delete_prefix(
|
|
198
|
+
cls, prefix: str, store_name: str = DEPLOYMENT_OBJECT_STORE_NAME
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Delete all files under a prefix from the object store.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
prefix: The prefix path to delete all files under.
|
|
204
|
+
store_name: Name of the Dapr object store binding to use.
|
|
205
|
+
|
|
206
|
+
Raises:
|
|
207
|
+
Exception: If there's an error deleting files from the object store.
|
|
159
208
|
"""
|
|
160
|
-
|
|
209
|
+
try:
|
|
210
|
+
# First, list all files under the prefix
|
|
211
|
+
try:
|
|
212
|
+
files_to_delete = await cls.list_files(
|
|
213
|
+
prefix=prefix, store_name=store_name
|
|
214
|
+
)
|
|
215
|
+
except Exception as e:
|
|
216
|
+
# If we can't list files for any reason, we can't delete them either
|
|
217
|
+
# Raise FileNotFoundError to give developers clear feedback
|
|
218
|
+
logger.info(f"Cannot list files under prefix {prefix}: {str(e)}")
|
|
219
|
+
raise FileNotFoundError(f"No files found under prefix: {prefix}")
|
|
220
|
+
|
|
221
|
+
if not files_to_delete:
|
|
222
|
+
logger.info(f"No files found under prefix: {prefix}")
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
logger.info(f"Deleting {len(files_to_delete)} files under prefix: {prefix}")
|
|
226
|
+
|
|
227
|
+
# Delete each file individually
|
|
228
|
+
for file_path in files_to_delete:
|
|
229
|
+
try:
|
|
230
|
+
await cls.delete_file(key=file_path, store_name=store_name)
|
|
231
|
+
except Exception as e:
|
|
232
|
+
logger.warning(f"Failed to delete file {file_path}: {str(e)}")
|
|
233
|
+
# Continue with other files even if one fails
|
|
234
|
+
|
|
235
|
+
logger.info(f"Successfully deleted all files under prefix: {prefix}")
|
|
236
|
+
|
|
237
|
+
except Exception as e:
|
|
238
|
+
logger.error(f"Error deleting files under prefix {prefix}: {str(e)}")
|
|
239
|
+
raise
|
|
161
240
|
|
|
162
241
|
@classmethod
|
|
163
242
|
async def upload_file(
|
|
@@ -165,6 +244,7 @@ class ObjectStore:
|
|
|
165
244
|
source: str,
|
|
166
245
|
destination: str,
|
|
167
246
|
store_name: str = DEPLOYMENT_OBJECT_STORE_NAME,
|
|
247
|
+
retain_local_copy: bool = False,
|
|
168
248
|
) -> None:
|
|
169
249
|
"""Upload a single file to the object store.
|
|
170
250
|
|
|
@@ -191,17 +271,11 @@ class ObjectStore:
|
|
|
191
271
|
logger.error(f"Error reading file {source}: {str(e)}")
|
|
192
272
|
raise e
|
|
193
273
|
|
|
194
|
-
metadata = {
|
|
195
|
-
"key": destination,
|
|
196
|
-
"blobName": destination,
|
|
197
|
-
"fileName": destination,
|
|
198
|
-
}
|
|
199
|
-
|
|
200
274
|
try:
|
|
201
275
|
await cls._invoke_dapr_binding(
|
|
202
276
|
operation=cls.OBJECT_CREATE_OPERATION,
|
|
203
277
|
data=file_content,
|
|
204
|
-
metadata=
|
|
278
|
+
metadata=cls._create_file_metadata(destination),
|
|
205
279
|
store_name=store_name,
|
|
206
280
|
)
|
|
207
281
|
logger.debug(f"Successfully uploaded file: {destination}")
|
|
@@ -212,7 +286,8 @@ class ObjectStore:
|
|
|
212
286
|
raise e
|
|
213
287
|
|
|
214
288
|
# Clean up local file after successful upload
|
|
215
|
-
|
|
289
|
+
if not retain_local_copy:
|
|
290
|
+
cls._cleanup_local_path(source)
|
|
216
291
|
|
|
217
292
|
@classmethod
|
|
218
293
|
async def upload_prefix(
|
|
@@ -221,6 +296,7 @@ class ObjectStore:
|
|
|
221
296
|
destination: str,
|
|
222
297
|
store_name: str = DEPLOYMENT_OBJECT_STORE_NAME,
|
|
223
298
|
recursive: bool = True,
|
|
299
|
+
retain_local_copy: bool = False,
|
|
224
300
|
) -> None:
|
|
225
301
|
"""Upload all files from a directory to the object store.
|
|
226
302
|
|
|
@@ -268,7 +344,9 @@ class ObjectStore:
|
|
|
268
344
|
store_key = os.path.join(destination, relative_path).replace(
|
|
269
345
|
os.sep, "/"
|
|
270
346
|
)
|
|
271
|
-
await cls.upload_file(
|
|
347
|
+
await cls.upload_file(
|
|
348
|
+
file_path, store_key, store_name, retain_local_copy
|
|
349
|
+
)
|
|
272
350
|
|
|
273
351
|
logger.info(f"Completed uploading directory {source} to object store")
|
|
274
352
|
except Exception as e:
|
application_sdk/version.py
CHANGED