-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecondary.py
76 lines (57 loc) · 1.92 KB
/
secondary.py
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
import os
import time
from typing import Optional
import logging
from fastapi import FastAPI, Response, HTTPException
from http import HTTPStatus
from pydantic import BaseModel
logger = logging.getLogger("master")
class MessageModel(BaseModel):
message: str
id: int
is_blocked: bool = False
if (os.environ.get('BREAK', None) != None):
print('terminating the program because flag was passed')
exit(1)
pass
else:
app = FastAPI(debug=True)
INMEMORY_MESSAGE_LIST = []
DELAY = None if 'DELAY' not in os.environ else float(os.environ['DELAY'])
ERROR_K = 0 if 'ERROR_K' not in os.environ else float(os.environ['ERROR_K'])
def error_simulation(is_blocked):
global ERROR_K
if ERROR_K > 0 and is_blocked:
ERROR_K -= 1
msg = f'Okay, we got an error, retry your request pls. You will get {ERROR_K} more errors'
logging.info(msg)
raise Exception(msg)
@app.get("/ping")
def ping():
if DELAY is not None and DELAY > 0:
time.sleep(DELAY)
return Response(status_code=HTTPStatus.NO_CONTENT.value)
@app.get("/message")
def get_message():
res = []
for m in INMEMORY_MESSAGE_LIST:
if m == None:
break
res.append(m)
return res
@app.post("/__message")
def post_message(message: MessageModel):
logging.info(message)
try:
error_simulation(message.is_blocked)
if DELAY is not None and DELAY > 0:
print(f'Introducing delay {DELAY} sec..')
time.sleep(DELAY)
print(f'Delay completed!')
if len(INMEMORY_MESSAGE_LIST) <= message.id:
INMEMORY_MESSAGE_LIST.extend([None for i in range(0, 1 + message.id - len(INMEMORY_MESSAGE_LIST))])
INMEMORY_MESSAGE_LIST[message.id] = message.message
print(INMEMORY_MESSAGE_LIST)
return Response(status_code=HTTPStatus.NO_CONTENT.value)
except:
raise HTTPException(status_code=500, detail="Item not found")