-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
328 lines (261 loc) · 8.75 KB
/
server.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
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
import sys
import functools
import logging
from typing import Dict, Any
from fastapi import FastAPI, HTTPException, Request, Query, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from fastapi_jwt_auth import AuthJWT
from fastapi_jwt_auth.exceptions import AuthJWTException
from fastapi.openapi.utils import get_openapi
from dotenv import load_dotenv
from pipeline import Message, Settings, Command, CommandActions, Monitor, Definition
from apihub_users.security.depends import RateLimiter, RateLimits, require_user
from apihub_users.security.router import router as security_router
from apihub_users.subscription.depends import require_subscription
from apihub_users.subscription.router import router as application_router
from apihub.utils import DEFINITION, State, make_topic, make_key, Result, Status
from apihub import __worker__, __version__
load_dotenv(override=False)
monitor = Monitor()
operation_counter = monitor.use_counter(
"APIHub",
"API operation counts",
labels=["api", "user", "operation"],
)
@functools.lru_cache(maxsize=None)
def get_state():
logging.basicConfig(level=logging.DEBUG)
return State(logger=logging)
def get_redis():
return get_state().redis
ip_rate_limited = RateLimiter(
key="ip", limits=RateLimits(limit=10, window_secs=10), redis=get_redis()
)
class JWTSettings(BaseModel):
authjwt_secret_key: str = "secret"
# callback to get your configuration
@AuthJWT.load_config
def jwt_get_config():
return JWTSettings()
api = FastAPI(
title=__worker__,
description="API for TANBIH ML models",
version=__version__,
)
api.include_router(
security_router,
# prefix='/security',
tags=["security"],
dependencies=[Depends(ip_rate_limited)],
)
api.include_router(
application_router, tags=["subscription"], dependencies=[Depends(ip_rate_limited)]
)
@api.exception_handler(AuthJWTException)
def authjwt_exception_handler(request: Request, exc: AuthJWTException):
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
class AsyncAPIRequestResponse(BaseModel):
success: bool = Field(title="boolean", example=True)
key: str = Field(title="unique key", example="91cb3a68-dd59-11ea-9f2a-82527949ac01")
class AsyncAPIResultResponse(BaseModel):
success: bool = Field(title="boolean", example=True)
key: str = Field(title="unique key", example="91cb3a68-dd59-11ea-9f2a-82527949ac01")
result: Dict[str, Any] = Field(title="result")
@api.get("/", include_in_schema=False, dependencies=[Depends(ip_rate_limited)])
async def root():
return {
__worker__: __version__,
}
@api.get(
"/define/{application}",
include_in_schema=False,
dependencies=[Depends(ip_rate_limited)],
)
async def define_service(
application: str,
# username: str = Depends(require_admin),
):
""" """
get_state().write(make_topic(application), Command(action=CommandActions.Define))
return {"define": f"application {application}"}
@api.post(
"/async/{application}",
include_in_schema=False,
response_model=AsyncAPIRequestResponse,
dependencies=[Depends(ip_rate_limited)],
)
async def async_service(
application: str, request: Request, username: str = Depends(require_subscription)
):
"""generic handler for async api."""
operation_counter.labels(api=application, user=username, operation="received").inc()
key = make_key()
dct: Dict[str, Any] = {}
# inject form data
dct.update(await request.form())
# inject query parameters
dct.update(request.query_params)
# inject user information
info = Result(
user=username,
api=application,
status=Status.ACCEPTED,
)
accept_notification = Message(content=info.dict(), id=key)
get_state().write(make_topic("result"), accept_notification)
# send job request to its approporate topic
info.status = Status.PROCESSED
dct.update(info.dict())
get_state().write(make_topic(application), Message(content=dct, id=key))
operation_counter.labels(api=application, user=username, operation="accepted").inc()
return AsyncAPIRequestResponse(success=True, key=key)
@api.get(
"/async/{application}",
dependencies=[Depends(ip_rate_limited)],
include_in_schema=False,
)
async def async_service_result(
application: str,
key: str = Query(
...,
title="unique key returned by a request",
example="91cb3a68-dd59-11ea-9f2a-82527949ac01",
),
username=Depends(require_user),
):
""" """
result = get_redis().get(key)
if result is None:
operation_counter.labels(
api=application, user=username, operation="result_not_found"
).inc()
raise HTTPException(
status_code=404,
detail="Result with this key cannot be found",
)
result = Result.parse_raw(result)
if result.status == Status.ACCEPTED:
raise HTTPException(
status_code=202,
detail="Result is not ready",
)
elif result.status != Status.PROCESSED:
operation_counter.labels(
api=application, user=username, operation="error"
).inc()
# FIXME change status code
raise HTTPException(
status_code=501,
detail="Unexpected error happened",
)
operation_counter.labels(
api=application, user=username, operation="result_served"
).inc()
return AsyncAPIResultResponse(
success=True,
key=result.get("key"),
result=result,
)
@api.post(
"/sync/{service_name}",
include_in_schema=False,
)
async def sync_service(service_name: str):
"""generic synchronised api hendler"""
# TODO synchronised service, basically it will wait and return results
# when it is ready. It will have a timeout of 30 seconds
def get_paths(redis=get_redis()):
paths = {}
for name, dct_str in redis.hgetall(DEFINITION).items():
name = name.decode("utf-8")
path = {}
definition = Definition.parse_raw(dct_str)
operation = {}
operation["tags"] = ["app"]
operation["summary"] = definition.description
operation["description"] = definition.description
parameters = {}
operation["requestBody"] = {
"content": {
"application/json": {
"schema": definition.input_schema, # ["properties"],
}
},
"required": True,
}
operation["responses"] = {
"200": {
"description": "successful request",
"status_code": 200,
"content": {
"application/json": {"schema": AsyncAPIRequestResponse.schema()}
},
}
}
path["post"] = operation
operation = {}
operation["tags"] = ["app"]
operation["summary"] = "obtain results from previous post requests"
operation["description"] = definition.description
parameters = [
{
"name": "key",
"in": "query",
"description": "the unique key obtained from post request",
"required": True,
"type": "string",
"format": "string",
}
]
# a strange way to sort parameters maybe
operation["parameters"] = list(
{param["name"]: param for param in parameters}.values()
)
operation["responses"] = {
"200": {
"description": "success",
"content": {
"application/json": {
"schema": definition.output_schema,
}
},
}
}
path["get"] = operation
paths[f"/async/{name}"] = path
return paths
def custom_openapi(app=api):
# if app.openapi_schema:
# return app.openapi_schema
openapi_schema = get_openapi(
title="APIHub",
version="0.1.0",
description="API for AI",
routes=app.routes,
)
openapi_schema["info"]["x-logo"] = {
"url": "https://raw.githubusercontent.com/yifan/apihub/master/images/APIHub-logo.png"
}
openapi_schema["paths"].update(get_paths())
app.openapi_schema = openapi_schema
return app.openapi_schema
api.openapi = custom_openapi
class ServerSettings(Settings):
port: int = 5000
log_level: str = "debug"
reload: bool = True
def main():
import uvicorn
monitor.expose()
settings = ServerSettings()
settings.parse_args(args=sys.argv)
uvicorn.run(
"apihub.server:api",
host="0.0.0.0",
port=settings.port,
log_level=settings.log_level,
reload=settings.reload,
)
if __name__ == "__main__":
main()