You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api_utils.py 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import json
  17. import random
  18. import time
  19. from functools import wraps
  20. from io import BytesIO
  21. from flask import (
  22. Response, jsonify, send_file, make_response,
  23. request as flask_request,
  24. )
  25. from werkzeug.http import HTTP_STATUS_CODES
  26. from api.utils import json_dumps
  27. from api.settings import RetCode
  28. from api.settings import (
  29. REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC,
  30. stat_logger, CLIENT_AUTHENTICATION, HTTP_APP_KEY, SECRET_KEY
  31. )
  32. import requests
  33. import functools
  34. from api.utils import CustomJSONEncoder
  35. from uuid import uuid1
  36. from base64 import b64encode
  37. from hmac import HMAC
  38. from urllib.parse import quote, urlencode
  39. requests.models.complexjson.dumps = functools.partial(
  40. json.dumps, cls=CustomJSONEncoder)
  41. def request(**kwargs):
  42. sess = requests.Session()
  43. stream = kwargs.pop('stream', sess.stream)
  44. timeout = kwargs.pop('timeout', None)
  45. kwargs['headers'] = {
  46. k.replace(
  47. '_',
  48. '-').upper(): v for k,
  49. v in kwargs.get(
  50. 'headers',
  51. {}).items()}
  52. prepped = requests.Request(**kwargs).prepare()
  53. if CLIENT_AUTHENTICATION and HTTP_APP_KEY and SECRET_KEY:
  54. timestamp = str(round(time() * 1000))
  55. nonce = str(uuid1())
  56. signature = b64encode(HMAC(SECRET_KEY.encode('ascii'), b'\n'.join([
  57. timestamp.encode('ascii'),
  58. nonce.encode('ascii'),
  59. HTTP_APP_KEY.encode('ascii'),
  60. prepped.path_url.encode('ascii'),
  61. prepped.body if kwargs.get('json') else b'',
  62. urlencode(
  63. sorted(
  64. kwargs['data'].items()),
  65. quote_via=quote,
  66. safe='-._~').encode('ascii')
  67. if kwargs.get('data') and isinstance(kwargs['data'], dict) else b'',
  68. ]), 'sha1').digest()).decode('ascii')
  69. prepped.headers.update({
  70. 'TIMESTAMP': timestamp,
  71. 'NONCE': nonce,
  72. 'APP-KEY': HTTP_APP_KEY,
  73. 'SIGNATURE': signature,
  74. })
  75. return sess.send(prepped, stream=stream, timeout=timeout)
  76. def get_exponential_backoff_interval(retries, full_jitter=False):
  77. """Calculate the exponential backoff wait time."""
  78. # Will be zero if factor equals 0
  79. countdown = min(REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC * (2 ** retries))
  80. # Full jitter according to
  81. # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  82. if full_jitter:
  83. countdown = random.randrange(countdown + 1)
  84. # Adjust according to maximum wait time and account for negative values.
  85. return max(0, countdown)
  86. def get_json_result(retcode=RetCode.SUCCESS, retmsg='success',
  87. data=None, job_id=None, meta=None):
  88. import re
  89. result_dict = {
  90. "retcode": retcode,
  91. "retmsg": retmsg,
  92. # "retmsg": re.sub(r"rag", "seceum", retmsg, flags=re.IGNORECASE),
  93. "data": data,
  94. "jobId": job_id,
  95. "meta": meta,
  96. }
  97. response = {}
  98. for key, value in result_dict.items():
  99. if value is None and key != "retcode":
  100. continue
  101. else:
  102. response[key] = value
  103. return jsonify(response)
  104. def get_data_error_result(retcode=RetCode.DATA_ERROR,
  105. retmsg='Sorry! Data missing!'):
  106. import re
  107. result_dict = {
  108. "retcode": retcode,
  109. "retmsg": re.sub(
  110. r"rag",
  111. "seceum",
  112. retmsg,
  113. flags=re.IGNORECASE)}
  114. response = {}
  115. for key, value in result_dict.items():
  116. if value is None and key != "retcode":
  117. continue
  118. else:
  119. response[key] = value
  120. return jsonify(response)
  121. def server_error_response(e):
  122. stat_logger.exception(e)
  123. try:
  124. if e.code == 401:
  125. return get_json_result(retcode=401, retmsg=repr(e))
  126. except BaseException:
  127. pass
  128. if len(e.args) > 1:
  129. return get_json_result(
  130. retcode=RetCode.EXCEPTION_ERROR, retmsg=repr(e.args[0]), data=e.args[1])
  131. if repr(e).find("index_not_found_exception") >= 0:
  132. return get_json_result(retcode=RetCode.EXCEPTION_ERROR, retmsg="No chunk found, please upload file and parse it.")
  133. return get_json_result(retcode=RetCode.EXCEPTION_ERROR, retmsg=repr(e))
  134. def error_response(response_code, retmsg=None):
  135. if retmsg is None:
  136. retmsg = HTTP_STATUS_CODES.get(response_code, 'Unknown Error')
  137. return Response(json.dumps({
  138. 'retmsg': retmsg,
  139. 'retcode': response_code,
  140. }), status=response_code, mimetype='application/json')
  141. def validate_request(*args, **kwargs):
  142. def wrapper(func):
  143. @wraps(func)
  144. def decorated_function(*_args, **_kwargs):
  145. input_arguments = flask_request.json or flask_request.form.to_dict()
  146. no_arguments = []
  147. error_arguments = []
  148. for arg in args:
  149. if arg not in input_arguments:
  150. no_arguments.append(arg)
  151. for k, v in kwargs.items():
  152. config_value = input_arguments.get(k, None)
  153. if config_value is None:
  154. no_arguments.append(k)
  155. elif isinstance(v, (tuple, list)):
  156. if config_value not in v:
  157. error_arguments.append((k, set(v)))
  158. elif config_value != v:
  159. error_arguments.append((k, v))
  160. if no_arguments or error_arguments:
  161. error_string = ""
  162. if no_arguments:
  163. error_string += "required argument are missing: {}; ".format(
  164. ",".join(no_arguments))
  165. if error_arguments:
  166. error_string += "required argument values: {}".format(
  167. ",".join(["{}={}".format(a[0], a[1]) for a in error_arguments]))
  168. return get_json_result(
  169. retcode=RetCode.ARGUMENT_ERROR, retmsg=error_string)
  170. return func(*_args, **_kwargs)
  171. return decorated_function
  172. return wrapper
  173. def is_localhost(ip):
  174. return ip in {'127.0.0.1', '::1', '[::1]', 'localhost'}
  175. def send_file_in_mem(data, filename):
  176. if not isinstance(data, (str, bytes)):
  177. data = json_dumps(data)
  178. if isinstance(data, str):
  179. data = data.encode('utf-8')
  180. f = BytesIO()
  181. f.write(data)
  182. f.seek(0)
  183. return send_file(f, as_attachment=True, attachment_filename=filename)
  184. def get_json_result(retcode=RetCode.SUCCESS, retmsg='success', data=None):
  185. response = {"retcode": retcode, "retmsg": retmsg, "data": data}
  186. return jsonify(response)
  187. def cors_reponse(retcode=RetCode.SUCCESS,
  188. retmsg='success', data=None, auth=None):
  189. result_dict = {"retcode": retcode, "retmsg": retmsg, "data": data}
  190. response_dict = {}
  191. for key, value in result_dict.items():
  192. if value is None and key != "retcode":
  193. continue
  194. else:
  195. response_dict[key] = value
  196. response = make_response(jsonify(response_dict))
  197. if auth:
  198. response.headers["Authorization"] = auth
  199. response.headers["Access-Control-Allow-Origin"] = "*"
  200. response.headers["Access-Control-Allow-Method"] = "*"
  201. response.headers["Access-Control-Allow-Headers"] = "*"
  202. response.headers["Access-Control-Allow-Headers"] = "*"
  203. response.headers["Access-Control-Expose-Headers"] = "Authorization"
  204. return response
  205. def construct_result(code=RetCode.DATA_ERROR, message='data is missing'):
  206. import re
  207. result_dict = {"code": code, "message": re.sub(r"rag", "seceum", message, flags=re.IGNORECASE)}
  208. response = {}
  209. for key, value in result_dict.items():
  210. if value is None and key != "code":
  211. continue
  212. else:
  213. response[key] = value
  214. return jsonify(response)
  215. def construct_json_result(code=RetCode.SUCCESS, message='success', data=None):
  216. if data is None:
  217. return jsonify({"code": code, "message": message})
  218. else:
  219. return jsonify({"code": code, "message": message, "data": data})
  220. def construct_error_response(e):
  221. stat_logger.exception(e)
  222. try:
  223. if e.code == 401:
  224. return construct_json_result(code=RetCode.UNAUTHORIZED, message=repr(e))
  225. except BaseException:
  226. pass
  227. if len(e.args) > 1:
  228. return construct_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=e.args[1])
  229. if repr(e).find("index_not_found_exception") >=0:
  230. return construct_json_result(code=RetCode.EXCEPTION_ERROR, message="No chunk found, please upload file and parse it.")
  231. return construct_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e))