-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1215 lines (1023 loc) · 40.3 KB
/
main.py
File metadata and controls
1215 lines (1023 loc) · 40.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Simple FastAPI example using async-cassandra.
This demonstrates basic CRUD operations with Cassandra using the async wrapper.
Run with: uvicorn main:app --reload
"""
import asyncio
import os
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
from typing import List, Optional
from uuid import UUID
from cassandra import OperationTimedOut, ReadTimeout, Unavailable, WriteTimeout
# Import Cassandra driver exceptions for proper error detection
from cassandra.cluster import Cluster as SyncCluster
from cassandra.cluster import NoHostAvailable
from cassandra.policies import ConstantReconnectionPolicy
from fastapi import FastAPI, HTTPException, Query, Request
from pydantic import BaseModel
from async_cassandra import AsyncCluster, StreamConfig
# Pydantic models
class UserCreate(BaseModel):
name: str
email: str
age: int
class User(BaseModel):
id: str
name: str
email: str
age: int
created_at: datetime
updated_at: datetime
class UserUpdate(BaseModel):
name: Optional[str] = None
email: Optional[str] = None
age: Optional[int] = None
# Global session, cluster, and keyspace
session = None
cluster = None
sync_session = None # For synchronous performance comparison
sync_cluster = None # For synchronous performance comparison
keyspace = "example"
def is_cassandra_unavailable_error(error: Exception) -> bool:
"""
Determine if an error indicates Cassandra is unavailable.
This function checks for specific Cassandra driver exceptions that indicate
the database is not reachable or available.
"""
# Direct Cassandra driver exceptions
if isinstance(
error, (NoHostAvailable, Unavailable, OperationTimedOut, ReadTimeout, WriteTimeout)
):
return True
# Check error message for additional patterns
error_msg = str(error).lower()
unavailability_keywords = [
"no host available",
"all hosts",
"connection",
"timeout",
"unavailable",
"no replicas",
"not enough replicas",
"cannot achieve consistency",
"operation timed out",
"read timeout",
"write timeout",
"connection pool",
"connection closed",
"connection refused",
"unable to connect",
]
return any(keyword in error_msg for keyword in unavailability_keywords)
def handle_cassandra_error(error: Exception, operation: str = "operation") -> HTTPException:
"""
Convert a Cassandra error to an appropriate HTTP exception.
Returns 503 for availability issues, 500 for other errors.
"""
if is_cassandra_unavailable_error(error):
# Log the specific error type for debugging
error_type = type(error).__name__
return HTTPException(
status_code=503,
detail=f"Service temporarily unavailable: Cassandra connection issue ({error_type}: {str(error)})",
)
else:
# Other errors (like InvalidRequest) get 500
return HTTPException(
status_code=500, detail=f"Internal server error during {operation}: {str(error)}"
)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage database lifecycle."""
global session, cluster, sync_session, sync_cluster
try:
# Startup - connect to Cassandra with constant reconnection policy
# IMPORTANT: Using ConstantReconnectionPolicy with 2-second delay for testing
# This ensures quick reconnection during integration tests where we simulate
# Cassandra outages. In production, you might want ExponentialReconnectionPolicy
# to avoid overwhelming a recovering cluster.
# IMPORTANT: Use 127.0.0.1 instead of localhost to force IPv4
contact_points = os.getenv("CASSANDRA_HOSTS", "127.0.0.1").split(",")
# Replace any "localhost" with "127.0.0.1" to ensure IPv4
contact_points = ["127.0.0.1" if cp == "localhost" else cp for cp in contact_points]
cluster = AsyncCluster(
contact_points=contact_points,
port=int(os.getenv("CASSANDRA_PORT", "9042")),
reconnection_policy=ConstantReconnectionPolicy(
delay=2.0
), # Reconnect every 2 seconds for testing
connect_timeout=10.0, # Quick connection timeout for faster test feedback
)
session = await cluster.connect()
except Exception as e:
print(f"Failed to connect to Cassandra: {type(e).__name__}: {e}")
# Don't fail startup completely, allow health check to report unhealthy
session = None
yield
return
# Create keyspace and table
await session.execute(
"""
CREATE KEYSPACE IF NOT EXISTS example
WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1}
"""
)
await session.set_keyspace("example")
# Also create sync cluster for performance comparison
try:
sync_cluster = SyncCluster(
contact_points=contact_points,
port=int(os.getenv("CASSANDRA_PORT", "9042")),
reconnection_policy=ConstantReconnectionPolicy(delay=2.0),
connect_timeout=10.0,
protocol_version=5,
)
sync_session = sync_cluster.connect()
sync_session.set_keyspace("example")
except Exception as e:
print(f"Failed to create sync cluster: {e}")
sync_session = None
# Drop and recreate table for clean test environment
await session.execute("DROP TABLE IF EXISTS users")
await session.execute(
"""
CREATE TABLE users (
id UUID PRIMARY KEY,
name TEXT,
email TEXT,
age INT,
created_at TIMESTAMP,
updated_at TIMESTAMP
)
"""
)
yield
# Shutdown
if session:
await session.close()
if cluster:
await cluster.shutdown()
if sync_session:
sync_session.shutdown()
if sync_cluster:
sync_cluster.shutdown()
# Create FastAPI app
app = FastAPI(
title="FastAPI + async-cassandra Example",
description="Simple CRUD API using async-cassandra",
version="1.0.0",
lifespan=lifespan,
)
@app.get("/")
async def root():
"""Root endpoint."""
return {"message": "FastAPI + async-cassandra example is running!"}
@app.get("/health")
async def health_check():
"""Health check endpoint."""
try:
# Simple health check - verify session is available
if session is None:
return {
"status": "unhealthy",
"cassandra_connected": False,
"timestamp": datetime.now().isoformat(),
}
# Test connection with a simple query
await session.execute("SELECT now() FROM system.local")
return {
"status": "healthy",
"cassandra_connected": True,
"timestamp": datetime.now().isoformat(),
}
except Exception:
return {
"status": "unhealthy",
"cassandra_connected": False,
"timestamp": datetime.now().isoformat(),
}
@app.post("/users", response_model=User, status_code=201)
async def create_user(user: UserCreate):
"""Create a new user."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
user_id = uuid.uuid4()
now = datetime.now()
# Use prepared statement for better performance
stmt = await session.prepare(
"INSERT INTO users (id, name, email, age, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
)
await session.execute(stmt, [user_id, user.name, user.email, user.age, now, now])
return User(
id=str(user_id),
name=user.name,
email=user.email,
age=user.age,
created_at=now,
updated_at=now,
)
except Exception as e:
raise handle_cassandra_error(e, "user creation")
@app.get("/users", response_model=List[User])
async def list_users(limit: int = Query(10, ge=1, le=10000)):
"""List all users."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
# Use prepared statement with validated limit
stmt = await session.prepare("SELECT * FROM users LIMIT ?")
result = await session.execute(stmt, [limit])
users = []
async for row in result:
users.append(
User(
id=str(row.id),
name=row.name,
email=row.email,
age=row.age,
created_at=row.created_at,
updated_at=row.updated_at,
)
)
return users
except Exception as e:
error_msg = str(e)
if any(
keyword in error_msg.lower()
for keyword in ["unavailable", "nohost", "connection", "timeout"]
):
raise HTTPException(
status_code=503,
detail=f"Service temporarily unavailable: Cassandra connection issue - {error_msg}",
)
raise HTTPException(status_code=500, detail=f"Internal server error: {error_msg}")
# Streaming endpoints - must come before /users/{user_id} to avoid route conflict
@app.get("/users/stream")
async def stream_users(
limit: int = Query(1000, ge=0, le=10000), fetch_size: int = Query(100, ge=10, le=1000)
):
"""Stream users data for large result sets."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
# Handle special case where limit=0
if limit == 0:
return {
"users": [],
"metadata": {
"total_returned": 0,
"pages_fetched": 0,
"fetch_size": fetch_size,
"streaming_enabled": True,
},
}
stream_config = StreamConfig(fetch_size=fetch_size)
# Use context manager for proper resource cleanup
# Note: LIMIT not needed - fetch_size controls data flow
stmt = await session.prepare("SELECT * FROM users")
async with await session.execute_stream(stmt, stream_config=stream_config) as result:
users = []
async for row in result:
# Handle both dict-like and object-like row access
if hasattr(row, "__getitem__"):
# Dictionary-like access
try:
user_dict = {
"id": str(row["id"]),
"name": row["name"],
"email": row["email"],
"age": row["age"],
"created_at": row["created_at"].isoformat(),
"updated_at": row["updated_at"].isoformat(),
}
except (KeyError, TypeError):
# Fall back to attribute access
user_dict = {
"id": str(row.id),
"name": row.name,
"email": row.email,
"age": row.age,
"created_at": row.created_at.isoformat(),
"updated_at": row.updated_at.isoformat(),
}
else:
# Object-like access
user_dict = {
"id": str(row.id),
"name": row.name,
"email": row.email,
"age": row.age,
"created_at": row.created_at.isoformat(),
"updated_at": row.updated_at.isoformat(),
}
users.append(user_dict)
return {
"users": users,
"metadata": {
"total_returned": len(users),
"pages_fetched": result.page_number,
"fetch_size": fetch_size,
"streaming_enabled": True,
},
}
except Exception as e:
raise handle_cassandra_error(e, "streaming users")
@app.get("/users/stream/pages")
async def stream_users_by_pages(
limit: int = Query(1000, ge=0, le=10000),
fetch_size: int = Query(100, ge=10, le=1000),
max_pages: int = Query(10, ge=0, le=100),
):
"""Stream users data page by page for memory efficiency."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
# Handle special case where limit=0 or max_pages=0
if limit == 0 or max_pages == 0:
return {
"total_rows_processed": 0,
"pages_info": [],
"metadata": {
"fetch_size": fetch_size,
"max_pages_limit": max_pages,
"streaming_mode": "page_by_page",
},
}
stream_config = StreamConfig(fetch_size=fetch_size, max_pages=max_pages)
# Use context manager for automatic cleanup
# Note: LIMIT not needed - fetch_size controls data flow
stmt = await session.prepare("SELECT * FROM users")
async with await session.execute_stream(stmt, stream_config=stream_config) as result:
pages_info = []
total_processed = 0
async for page in result.pages():
page_size = len(page)
total_processed += page_size
# Extract sample user data, handling both dict-like and object-like access
sample_user = None
if page:
first_row = page[0]
if hasattr(first_row, "__getitem__"):
# Dictionary-like access
try:
sample_user = {
"id": str(first_row["id"]),
"name": first_row["name"],
"email": first_row["email"],
}
except (KeyError, TypeError):
# Fall back to attribute access
sample_user = {
"id": str(first_row.id),
"name": first_row.name,
"email": first_row.email,
}
else:
# Object-like access
sample_user = {
"id": str(first_row.id),
"name": first_row.name,
"email": first_row.email,
}
pages_info.append(
{
"page_number": len(pages_info) + 1,
"rows_in_page": page_size,
"sample_user": sample_user,
}
)
return {
"total_rows_processed": total_processed,
"pages_info": pages_info,
"metadata": {
"fetch_size": fetch_size,
"max_pages_limit": max_pages,
"streaming_mode": "page_by_page",
},
}
except Exception as e:
raise handle_cassandra_error(e, "streaming users by pages")
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: str):
"""Get user by ID."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
user_uuid = uuid.UUID(user_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid UUID")
try:
stmt = await session.prepare("SELECT * FROM users WHERE id = ?")
result = await session.execute(stmt, [user_uuid])
row = result.one()
if not row:
raise HTTPException(status_code=404, detail="User not found")
return User(
id=str(row.id),
name=row.name,
email=row.email,
age=row.age,
created_at=row.created_at,
updated_at=row.updated_at,
)
except HTTPException:
raise
except Exception as e:
raise handle_cassandra_error(e, "checking user existence")
@app.delete("/users/{user_id}", status_code=204)
async def delete_user(user_id: str):
"""Delete user by ID."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
user_uuid = uuid.UUID(user_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid user ID format")
try:
stmt = await session.prepare("DELETE FROM users WHERE id = ?")
await session.execute(stmt, [user_uuid])
return None # 204 No Content
except Exception as e:
error_msg = str(e)
if any(
keyword in error_msg.lower()
for keyword in ["unavailable", "nohost", "connection", "timeout"]
):
raise HTTPException(
status_code=503,
detail=f"Service temporarily unavailable: Cassandra connection issue - {error_msg}",
)
raise HTTPException(status_code=500, detail=f"Internal server error: {error_msg}")
@app.put("/users/{user_id}", response_model=User)
async def update_user(user_id: str, user_update: UserUpdate):
"""Update user by ID."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
user_uuid = uuid.UUID(user_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid user ID format")
try:
# First check if user exists
check_stmt = await session.prepare("SELECT * FROM users WHERE id = ?")
result = await session.execute(check_stmt, [user_uuid])
existing_user = result.one()
if not existing_user:
raise HTTPException(status_code=404, detail="User not found")
except HTTPException:
raise
except Exception as e:
raise handle_cassandra_error(e, "checking user existence")
try:
# Build update query dynamically based on provided fields
update_fields = []
params = []
if user_update.name is not None:
update_fields.append("name = ?")
params.append(user_update.name)
if user_update.email is not None:
update_fields.append("email = ?")
params.append(user_update.email)
if user_update.age is not None:
update_fields.append("age = ?")
params.append(user_update.age)
if not update_fields:
raise HTTPException(status_code=400, detail="No fields to update")
# Always update the updated_at timestamp
update_fields.append("updated_at = ?")
params.append(datetime.now())
params.append(user_uuid) # WHERE clause
# Build a static query based on which fields are provided
# This approach avoids dynamic SQL construction
if len(update_fields) == 1: # Only updated_at
update_stmt = await session.prepare("UPDATE users SET updated_at = ? WHERE id = ?")
elif len(update_fields) == 2: # One field + updated_at
if "name = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET name = ?, updated_at = ? WHERE id = ?"
)
elif "email = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET email = ?, updated_at = ? WHERE id = ?"
)
elif "age = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET age = ?, updated_at = ? WHERE id = ?"
)
elif len(update_fields) == 3: # Two fields + updated_at
if "name = ?" in update_fields and "email = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET name = ?, email = ?, updated_at = ? WHERE id = ?"
)
elif "name = ?" in update_fields and "age = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET name = ?, age = ?, updated_at = ? WHERE id = ?"
)
elif "email = ?" in update_fields and "age = ?" in update_fields:
update_stmt = await session.prepare(
"UPDATE users SET email = ?, age = ?, updated_at = ? WHERE id = ?"
)
else: # All fields
update_stmt = await session.prepare(
"UPDATE users SET name = ?, email = ?, age = ?, updated_at = ? WHERE id = ?"
)
await session.execute(update_stmt, params)
# Return updated user
result = await session.execute(check_stmt, [user_uuid])
updated_user = result.one()
return User(
id=str(updated_user.id),
name=updated_user.name,
email=updated_user.email,
age=updated_user.age,
created_at=updated_user.created_at,
updated_at=updated_user.updated_at,
)
except HTTPException:
raise
except Exception as e:
raise handle_cassandra_error(e, "checking user existence")
@app.patch("/users/{user_id}", response_model=User)
async def partial_update_user(user_id: str, user_update: UserUpdate):
"""Partial update user by ID (same as PUT in this implementation)."""
return await update_user(user_id, user_update)
# Performance testing endpoints
@app.get("/performance/async")
async def test_async_performance(requests: int = Query(100, ge=1, le=1000)):
"""Test async performance with concurrent queries."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
import time
try:
start_time = time.time()
# Prepare statement once
stmt = await session.prepare("SELECT * FROM users LIMIT 1")
# Execute queries concurrently
async def execute_query():
return await session.execute(stmt)
tasks = [execute_query() for _ in range(requests)]
results = await asyncio.gather(*tasks)
end_time = time.time()
duration = end_time - start_time
return {
"requests": requests,
"total_time": duration,
"requests_per_second": requests / duration if duration > 0 else 0,
"avg_time_per_request": duration / requests if requests > 0 else 0,
"successful_requests": len(results),
"mode": "async",
}
except Exception as e:
raise handle_cassandra_error(e, "performance test")
@app.get("/performance/sync")
async def test_sync_performance(requests: int = Query(100, ge=1, le=1000)):
"""Test TRUE sync performance using synchronous cassandra-driver."""
if sync_session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Sync Cassandra connection not established",
)
import time
try:
# Run synchronous operations in a thread pool to not block the event loop
import concurrent.futures
def run_sync_test():
start_time = time.time()
# Prepare statement once
stmt = sync_session.prepare("SELECT * FROM users LIMIT 1")
# Execute queries sequentially with the SYNC driver
results = []
for _ in range(requests):
result = sync_session.execute(stmt)
results.append(result)
end_time = time.time()
duration = end_time - start_time
return {
"requests": requests,
"total_time": duration,
"requests_per_second": requests / duration if duration > 0 else 0,
"avg_time_per_request": duration / requests if requests > 0 else 0,
"successful_requests": len(results),
"mode": "sync (true blocking)",
}
# Run in thread pool to avoid blocking the event loop
loop = asyncio.get_event_loop()
with concurrent.futures.ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, run_sync_test)
return result
except Exception as e:
raise handle_cassandra_error(e, "sync performance test")
# Batch operations endpoint
@app.post("/users/batch", status_code=201)
async def create_users_batch(batch_data: dict):
"""Create multiple users in a batch."""
if session is None:
raise HTTPException(
status_code=503,
detail="Service temporarily unavailable: Cassandra connection not established",
)
try:
users = batch_data.get("users", [])
created_users = []
for user_data in users:
user_id = uuid.uuid4()
now = datetime.now()
# Create user dict with proper fields
user_dict = {
"id": str(user_id),
"name": user_data.get("name", user_data.get("username", "")),
"email": user_data["email"],
"age": user_data.get("age", 25),
"created_at": now.isoformat(),
"updated_at": now.isoformat(),
}
# Insert into database
stmt = await session.prepare(
"INSERT INTO users (id, name, email, age, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
)
await session.execute(
stmt, [user_id, user_dict["name"], user_dict["email"], user_dict["age"], now, now]
)
created_users.append(user_dict)
return {"created": created_users}
except Exception as e:
raise handle_cassandra_error(e, "batch user creation")
# Metrics endpoint
@app.get("/metrics")
async def get_metrics():
"""Get application metrics."""
# Simple metrics implementation
return {
"total_requests": 1000, # Placeholder
"query_performance": {
"avg_response_time_ms": 50,
"p95_response_time_ms": 100,
"p99_response_time_ms": 200,
},
"cassandra_connections": {"active": 10, "idle": 5, "total": 15},
}
# Shutdown endpoint
@app.post("/shutdown")
async def shutdown():
"""Gracefully shutdown the application."""
# In a real app, this would trigger graceful shutdown
return {"message": "Shutdown initiated"}
# Slow query endpoint for testing
@app.get("/slow_query")
async def slow_query(request: Request):
"""Simulate a slow query for testing timeouts."""
# Check for timeout header
timeout_header = request.headers.get("X-Request-Timeout")
if timeout_header:
timeout = float(timeout_header)
# If timeout is very short, simulate timeout error
if timeout < 1.0:
raise HTTPException(status_code=504, detail="Gateway Timeout")
await asyncio.sleep(5) # Simulate slow operation
return {"message": "Slow query completed"}
# Long running query endpoint
@app.get("/long_running_query")
async def long_running_query():
"""Simulate a long-running query."""
await asyncio.sleep(10) # Simulate very long operation
return {"message": "Long query completed"}
# ============================================================================
# Context Manager Safety Endpoints
# ============================================================================
@app.post("/context_manager_safety/query_error")
async def test_query_error_session_safety():
"""Test that query errors don't close the session."""
# Track session state
session_id_before = id(session)
is_closed_before = session.is_closed
# Execute a bad query that will fail
try:
await session.execute("SELECT * FROM non_existent_table_xyz")
except Exception as e:
error_message = str(e)
# Verify session is still usable
session_id_after = id(session)
is_closed_after = session.is_closed
# Try a valid query to prove session works
result = await session.execute("SELECT release_version FROM system.local")
version = result.one().release_version
return {
"test": "query_error_session_safety",
"session_unchanged": session_id_before == session_id_after,
"session_open": not is_closed_after and not is_closed_before,
"error_caught": error_message,
"session_still_works": bool(version),
"cassandra_version": version,
}
@app.post("/context_manager_safety/streaming_error")
async def test_streaming_error_session_safety():
"""Test that streaming errors don't close the session."""
session_id_before = id(session)
error_message = None
stream_completed = False
# Try to stream from non-existent table
try:
async with await session.execute_stream(
"SELECT * FROM non_existent_stream_table"
) as stream:
async for row in stream:
pass
stream_completed = True
except Exception as e:
error_message = str(e)
# Verify session is still usable
session_id_after = id(session)
# Try a valid streaming query
row_count = 0
# Use hardcoded query since keyspace is constant
stmt = await session.prepare("SELECT * FROM example.users LIMIT ?")
async with await session.execute_stream(stmt, [10]) as stream:
async for row in stream:
row_count += 1
return {
"test": "streaming_error_session_safety",
"session_unchanged": session_id_before == session_id_after,
"session_open": not session.is_closed,
"streaming_error_caught": bool(error_message),
"error_message": error_message,
"stream_completed": stream_completed,
"session_still_streams": row_count > 0,
"rows_after_error": row_count,
}
@app.post("/context_manager_safety/concurrent_streams")
async def test_concurrent_streams():
"""Test multiple concurrent streams don't interfere."""
# Create test data
users_to_create = []
for i in range(30):
users_to_create.append(
{
"id": str(uuid.uuid4()),
"name": f"Stream Test User {i}",
"email": f"stream{i}@test.com",
"age": 20 + (i % 3) * 10, # Ages: 20, 30, 40
}
)
# Insert test data
for user in users_to_create:
stmt = await session.prepare(
"INSERT INTO example.users (id, name, email, age) VALUES (?, ?, ?, ?)"
)
await session.execute(
stmt,
[UUID(user["id"]), user["name"], user["email"], user["age"]],
)
# Stream different age groups concurrently
async def stream_age_group(age: int) -> dict:
count = 0
users = []
config = StreamConfig(fetch_size=5)
stmt = await session.prepare("SELECT * FROM example.users WHERE age = ? ALLOW FILTERING")
async with await session.execute_stream(
stmt,
[age],
stream_config=config,
) as stream:
async for row in stream:
count += 1
users.append(row.name)
return {"age": age, "count": count, "users": users[:3]} # First 3 names
# Run concurrent streams
results = await asyncio.gather(stream_age_group(20), stream_age_group(30), stream_age_group(40))
# Clean up test data
for user in users_to_create:
stmt = await session.prepare("DELETE FROM example.users WHERE id = ?")
await session.execute(stmt, [UUID(user["id"])])
return {
"test": "concurrent_streams",
"streams_completed": len(results),
"all_streams_independent": all(r["count"] == 10 for r in results),
"results": results,
"session_still_open": not session.is_closed,
}
@app.post("/context_manager_safety/nested_contexts")
async def test_nested_context_managers():
"""Test nested context managers close in correct order."""
events = []
# Create a temporary keyspace for this test
temp_keyspace = f"test_nested_{uuid.uuid4().hex[:8]}"
try:
# Create new cluster context
async with AsyncCluster(["127.0.0.1"]) as test_cluster:
events.append("cluster_opened")
# Create session context
async with await test_cluster.connect() as test_session:
events.append("session_opened")
# Create keyspace with safe identifier
# Validate keyspace name contains only safe characters
if not temp_keyspace.replace("_", "").isalnum():