File size: 14,277 Bytes
0021b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()