transformation-api / client.py
Rajavignesh
Initial Code
0021b08
Raw History Blame Contribute Delete
14.3 kB
#!/usr/bin/env python3
"""
WebSocket Client for FastAPI Processing Simulator
This client provides both interactive and automated testing capabilities
for the FastAPI WebSocket endpoint and download functionality.
"""
import asyncio
import websockets
import json
import argparse
import sys
import requests
import os
from datetime import datetime
from typing import Optional, Dict, Any
class ProcessingClient:
def __init__(self, url: str = "ws://10.170.2.156:8000/ws"):
self.url = url
self.websocket = None
# Extract base URL for HTTP requests (download endpoint)
self.base_url = url.replace("ws://", "http://").replace("/ws", "")
async def connect(self) -> bool:
"""Connect to the WebSocket server"""
try:
self.websocket = await websockets.connect(self.url)
print(f"βœ… Connected to {self.url}")
return True
except Exception as e:
print(f"❌ Failed to connect to {self.url}: {e}")
return False
async def disconnect(self):
"""Disconnect from the WebSocket server"""
if self.websocket:
await self.websocket.close()
print("πŸ”Œ Disconnected from server")
async def send_processing_request(self, foldername: str, environment: str) -> Optional[str]:
"""
Send a processing request and return the request ID
Args:
foldername: Name of the folder to process
environment: Environment name (dev, staging, production, etc.)
Returns:
Request ID if successful, None otherwise
"""
if not self.websocket:
print("❌ Not connected to server")
return None
request = {
"foldername": foldername,
"environment": environment
}
try:
await self.websocket.send(json.dumps(request))
print(f"πŸ“€ Sent request: {request}")
return await self._listen_for_messages()
except Exception as e:
print(f"❌ Error sending request: {e}")
return None
async def _listen_for_messages(self) -> Optional[str]:
"""Listen for messages from the server and display them"""
request_id = None
try:
async for message in self.websocket:
data = json.loads(message)
timestamp = datetime.now().strftime("%H:%M:%S")
# Handle different message types
if "error" in data:
print(f"❌ [{timestamp}] Error: {data['error']}")
if "expected_format" in data:
print(f" Expected format: {data['expected_format']}")
elif data.get("type") == "progress":
progress = data.get("progress_percentage", 0)
message = data.get("message", "")
print(f"⏳ [{timestamp}] Progress {progress}%: {message}")
request_id = data.get("request_id", request_id)
elif data.get("type") == "completion":
print(f"βœ… [{timestamp}] {data.get('message', 'Completed')}")
stats = data.get("stats", {})
print("\nπŸ“Š Final Statistics:")
print(f" Status: {stats.get('status')}")
print(f" Number of Records: {stats.get('number_of_records'):,}")
print(f" Request ID: {stats.get('request_id')}")
print(f" Record Count: {stats.get('record_count'):,}")
request_id = stats.get("request_id", request_id)
break
else:
# Handle acknowledgment and other messages
message = data.get("message", "")
if message:
print(f"πŸ“ [{timestamp}] {message}")
request_id = data.get("request_id", request_id)
except websockets.exceptions.ConnectionClosed:
print("πŸ”Œ Connection closed by server")
except Exception as e:
print(f"❌ Error receiving messages: {e}")
return request_id
def download_file(self, request_id: str, save_path: str = None) -> bool:
"""
Download the TEST.pdf file using the request ID
Args:
request_id: The request ID to use for the download
save_path: Optional path to save the file (default: current directory)
Returns:
True if download successful, False otherwise
"""
try:
download_url = f"{self.base_url}/{request_id}/download"
print(f"πŸ“₯ Downloading from: {download_url}")
response = requests.get(download_url)
if response.status_code == 200:
# Determine save path
if save_path is None:
save_path = f"downloaded_TEST_{request_id[:8]}.pdf"
# Save the file
with open(save_path, 'wb') as f:
f.write(response.content)
file_size = len(response.content)
print(f"βœ… File downloaded successfully!")
print(f" πŸ“ Saved as: {save_path}")
print(f" πŸ“Š Size: {file_size:,} bytes")
print(f" πŸ†” Request ID: {response.headers.get('X-Request-ID', 'N/A')}")
return True
else:
print(f"❌ Download failed with status {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error downloading file: {e}")
return False
async def interactive_mode():
"""Run the client in interactive mode"""
print("πŸš€ FastAPI Processing Simulator - Interactive Client")
print("=" * 60)
# Get server URL
url = input("Enter WebSocket URL (default: ws://10.170.2.156:8000/ws): ").strip()
if not url:
url = "ws://10.170.2.156:8000/ws"
client = ProcessingClient(url)
# Connect to server
if not await client.connect():
return
try:
while True:
print("\n" + "=" * 60)
print("Options:")
print("1. Send processing request")
print("2. Download file with request ID")
print("3. Send request and download file")
print("4. Change server URL")
print("5. Quit")
choice = input("\nSelect option (1-5): ").strip()
if choice == "1":
foldername = input("Enter folder name: ").strip()
if not foldername:
print("❌ Folder name cannot be empty")
continue
environment = input("Enter environment (dev/staging/production): ").strip()
if not environment:
print("❌ Environment cannot be empty")
continue
print(f"\nπŸ”„ Processing request for '{foldername}' in '{environment}'...")
request_id = await client.send_processing_request(foldername, environment)
if request_id:
print(f"\nβœ… Request completed with ID: {request_id}")
else:
print("\n❌ Request failed")
elif choice == "2":
request_id = input("Enter request ID for download: ").strip()
if not request_id:
print("❌ Request ID cannot be empty")
continue
save_path = input("Enter save path (or press Enter for default): ").strip()
if not save_path:
save_path = None
print(f"\nπŸ“₯ Downloading file for request ID: {request_id}")
success = client.download_file(request_id, save_path)
if success:
print("βœ… Download completed successfully!")
else:
print("❌ Download failed!")
elif choice == "3":
foldername = input("Enter folder name: ").strip()
if not foldername:
print("❌ Folder name cannot be empty")
continue
environment = input("Enter environment (dev/staging/production): ").strip()
if not environment:
print("❌ Environment cannot be empty")
continue
print(f"\nπŸ”„ Processing request for '{foldername}' in '{environment}'...")
request_id = await client.send_processing_request(foldername, environment)
if request_id:
print(f"\nβœ… Request completed with ID: {request_id}")
# Ask if user wants to download
download_choice = input("\nDownload the file now? (y/n): ").strip().lower()
if download_choice in ['y', 'yes']:
save_path = input("Enter save path (or press Enter for default): ").strip()
if not save_path:
save_path = None
print(f"\nπŸ“₯ Downloading file...")
success = client.download_file(request_id, save_path)
if success:
print("βœ… Download completed successfully!")
else:
print("❌ Download failed!")
else:
print("\n❌ Request failed")
elif choice == "4":
await client.disconnect()
url = input("Enter new WebSocket URL: ").strip()
client = ProcessingClient(url)
if not await client.connect():
break
elif choice == "5":
break
else:
print("❌ Invalid option. Please select 1-5.")
except KeyboardInterrupt:
print("\n\nπŸ‘‹ Goodbye!")
finally:
await client.disconnect()
async def automated_test(url: str, foldername: str, environment: str):
"""Run automated test with specified parameters"""
print(f"πŸ€– Running automated test...")
print(f" URL: {url}")
print(f" Folder: {foldername}")
print(f" Environment: {environment}")
print("=" * 60)
client = ProcessingClient(url)
if await client.connect():
request_id = await client.send_processing_request(foldername, environment)
await client.disconnect()
if request_id:
print(f"\nβœ… Test completed successfully! Request ID: {request_id}")
return True
else:
print("\n❌ Test failed!")
return False
return False
async def stress_test(url: str, num_requests: int = 5):
"""Run multiple concurrent requests to test server performance"""
print(f"⚑ Running stress test with {num_requests} concurrent requests...")
print("=" * 60)
async def single_request(request_num: int):
client = ProcessingClient(url)
if await client.connect():
foldername = f"test-folder-{request_num}"
environment = f"test-env-{request_num}"
print(f"πŸš€ Starting request {request_num}")
request_id = await client.send_processing_request(foldername, environment)
await client.disconnect()
if request_id:
print(f"βœ… Request {request_num} completed: {request_id}")
return True
else:
print(f"❌ Request {request_num} failed")
return False
return False
# Run concurrent requests
tasks = [single_request(i + 1) for i in range(num_requests)]
results = await asyncio.gather(*tasks, return_exceptions=True)
successful = sum(1 for r in results if r is True)
print(f"\nπŸ“Š Stress test results: {successful}/{num_requests} requests successful")
return successful == num_requests
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="WebSocket Client for FastAPI Processing Simulator")
parser.add_argument("--url", default="ws://10.170.2.156:8000/ws", help="WebSocket server URL")
parser.add_argument("--folder", help="Folder name for automated test")
parser.add_argument("--env", help="Environment for automated test")
parser.add_argument("--stress", type=int, metavar="N", help="Run stress test with N concurrent requests")
parser.add_argument("--download", help="Download file using request ID")
parser.add_argument("--save-path", help="Path to save downloaded file")
parser.add_argument("--interactive", action="store_true", help="Run in interactive mode (default)")
args = parser.parse_args()
# Determine mode
if args.download:
# Download mode
client = ProcessingClient(args.url)
success = client.download_file(args.download, args.save_path)
sys.exit(0 if success else 1)
elif args.stress:
# Stress test mode
success = asyncio.run(stress_test(args.url, args.stress))
sys.exit(0 if success else 1)
elif args.folder and args.env:
# Automated test mode
success = asyncio.run(automated_test(args.url, args.folder, args.env))
sys.exit(0 if success else 1)
else:
# Interactive mode (default)
asyncio.run(interactive_mode())
if __name__ == "__main__":
main()