anuj-exe commited on
Commit
7269d89
·
verified ·
1 Parent(s): 6699d51

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +31 -14
main.py CHANGED
@@ -1,9 +1,9 @@
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import JSONResponse
 
3
  import time
4
  import psutil
5
  import os
6
- import asyncio
7
 
8
  app = FastAPI()
9
 
@@ -11,9 +11,10 @@ process = psutil.Process(os.getpid())
11
  last_cpu_times = process.cpu_times()
12
  last_time = time.time()
13
 
14
- # Limit concurrent requests
15
- MAX_CONCURRENT_REQUESTS = 20
16
- semaphore = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
 
17
 
18
  def get_cpu_percent():
19
  global last_cpu_times, last_time
@@ -31,19 +32,35 @@ def simulate_work():
31
  total += i
32
  return total
33
 
34
- async def limited_worker():
35
- async with semaphore:
36
- # Actual work happens here
37
- simulate_work()
38
- return {"ok": True, "time": int(time.time() * 1000)}
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  @app.get("/")
41
  async def root():
42
- try:
43
- result = await limited_worker()
44
- return result
45
- except Exception as e:
46
- raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
47
 
48
  @app.get("/metrics")
49
  async def metrics():
 
1
  from fastapi import FastAPI, HTTPException
2
  from fastapi.responses import JSONResponse
3
+ import asyncio
4
  import time
5
  import psutil
6
  import os
 
7
 
8
  app = FastAPI()
9
 
 
11
  last_cpu_times = process.cpu_times()
12
  last_time = time.time()
13
 
14
+ # Queue settings
15
+ MAX_QUEUE_SIZE = 100 # Max number of requests waiting in the queue
16
+ NUM_WORKERS = 20 # Number of concurrent workers
17
+ request_queue = asyncio.Queue(MAX_QUEUE_SIZE)
18
 
19
  def get_cpu_percent():
20
  global last_cpu_times, last_time
 
32
  total += i
33
  return total
34
 
35
+ async def worker():
36
+ while True:
37
+ fut = await request_queue.get()
38
+ try:
39
+ result = simulate_work()
40
+ fut.set_result({"ok": True, "time": int(time.time() * 1000)})
41
+ except Exception as e:
42
+ fut.set_exception(e)
43
+ finally:
44
+ request_queue.task_done()
45
+
46
+ # Start worker tasks on startup
47
+ @app.on_event("startup")
48
+ async def startup_event():
49
+ for _ in range(NUM_WORKERS):
50
+ asyncio.create_task(worker())
51
 
52
  @app.get("/")
53
  async def root():
54
+ if request_queue.full():
55
+ # Queue is full, reject request
56
+ raise HTTPException(status_code=429, detail="Server busy, try again later")
57
+
58
+ # Create a future to get the result from the worker
59
+ loop = asyncio.get_event_loop()
60
+ fut = loop.create_future()
61
+ await request_queue.put(fut)
62
+ result = await fut
63
+ return result
64
 
65
  @app.get("/metrics")
66
  async def metrics():