Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

api_utils.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 functools
  17. import json
  18. import random
  19. import time
  20. from base64 import b64encode
  21. from functools import wraps
  22. from hmac import HMAC
  23. from io import BytesIO
  24. from urllib.parse import quote, urlencode
  25. from uuid import uuid1
  26. import requests
  27. from flask import (
  28. Response, jsonify, send_file, make_response,
  29. request as flask_request,
  30. )
  31. from werkzeug.http import HTTP_STATUS_CODES
  32. from api.db.db_models import APIToken
  33. from api.settings import (
  34. REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC,
  35. stat_logger, CLIENT_AUTHENTICATION, HTTP_APP_KEY, SECRET_KEY
  36. )
  37. from api.settings import RetCode
  38. from api.utils import CustomJSONEncoder
  39. from api.utils import json_dumps
  40. requests.models.complexjson.dumps = functools.partial(
  41. json.dumps, cls=CustomJSONEncoder)
  42. def request(**kwargs):
  43. sess = requests.Session()
  44. stream = kwargs.pop('stream', sess.stream)
  45. timeout = kwargs.pop('timeout', None)
  46. kwargs['headers'] = {
  47. k.replace(
  48. '_',
  49. '-').upper(): v for k,
  50. v in kwargs.get(
  51. 'headers',
  52. {}).items()}
  53. prepped = requests.Request(**kwargs).prepare()
  54. if CLIENT_AUTHENTICATION and HTTP_APP_KEY and SECRET_KEY:
  55. timestamp = str(round(time() * 1000))
  56. nonce = str(uuid1())
  57. signature = b64encode(HMAC(SECRET_KEY.encode('ascii'), b'\n'.join([
  58. timestamp.encode('ascii'),
  59. nonce.encode('ascii'),
  60. HTTP_APP_KEY.encode('ascii'),
  61. prepped.path_url.encode('ascii'),
  62. prepped.body if kwargs.get('json') else b'',
  63. urlencode(
  64. sorted(
  65. kwargs['data'].items()),
  66. quote_via=quote,
  67. safe='-._~').encode('ascii')
  68. if kwargs.get('data') and isinstance(kwargs['data'], dict) else b'',
  69. ]), 'sha1').digest()).decode('ascii')
  70. prepped.headers.update({
  71. 'TIMESTAMP': timestamp,
  72. 'NONCE': nonce,
  73. 'APP-KEY': HTTP_APP_KEY,
  74. 'SIGNATURE': signature,
  75. })
  76. return sess.send(prepped, stream=stream, timeout=timeout)
  77. def get_exponential_backoff_interval(retries, full_jitter=False):
  78. """Calculate the exponential backoff wait time."""
  79. # Will be zero if factor equals 0
  80. countdown = min(REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC * (2 ** retries))
  81. # Full jitter according to
  82. # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  83. if full_jitter:
  84. countdown = random.randrange(countdown + 1)
  85. # Adjust according to maximum wait time and account for negative values.
  86. return max(0, countdown)
  87. def get_data_error_result(retcode=RetCode.DATA_ERROR,
  88. retmsg='Sorry! Data missing!'):
  89. import re
  90. result_dict = {
  91. "retcode": retcode,
  92. "retmsg": re.sub(
  93. r"rag",
  94. "seceum",
  95. retmsg,
  96. flags=re.IGNORECASE)}
  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 server_error_response(e):
  105. stat_logger.exception(e)
  106. try:
  107. if e.code == 401:
  108. return get_json_result(retcode=401, retmsg=repr(e))
  109. except BaseException:
  110. pass
  111. if len(e.args) > 1:
  112. return get_json_result(
  113. retcode=RetCode.EXCEPTION_ERROR, retmsg=repr(e.args[0]), data=e.args[1])
  114. if repr(e).find("index_not_found_exception") >= 0:
  115. return get_json_result(retcode=RetCode.EXCEPTION_ERROR,
  116. retmsg="No chunk found, please upload file and parse it.")
  117. return get_json_result(retcode=RetCode.EXCEPTION_ERROR, retmsg=repr(e))
  118. def error_response(response_code, retmsg=None):
  119. if retmsg is None:
  120. retmsg = HTTP_STATUS_CODES.get(response_code, 'Unknown Error')
  121. return Response(json.dumps({
  122. 'retmsg': retmsg,
  123. 'retcode': response_code,
  124. }), status=response_code, mimetype='application/json')
  125. def validate_request(*args, **kwargs):
  126. def wrapper(func):
  127. @wraps(func)
  128. def decorated_function(*_args, **_kwargs):
  129. input_arguments = flask_request.json or flask_request.form.to_dict()
  130. no_arguments = []
  131. error_arguments = []
  132. for arg in args:
  133. if arg not in input_arguments:
  134. no_arguments.append(arg)
  135. for k, v in kwargs.items():
  136. config_value = input_arguments.get(k, None)
  137. if config_value is None:
  138. no_arguments.append(k)
  139. elif isinstance(v, (tuple, list)):
  140. if config_value not in v:
  141. error_arguments.append((k, set(v)))
  142. elif config_value != v:
  143. error_arguments.append((k, v))
  144. if no_arguments or error_arguments:
  145. error_string = ""
  146. if no_arguments:
  147. error_string += "required argument are missing: {}; ".format(
  148. ",".join(no_arguments))
  149. if error_arguments:
  150. error_string += "required argument values: {}".format(
  151. ",".join(["{}={}".format(a[0], a[1]) for a in error_arguments]))
  152. return get_json_result(
  153. retcode=RetCode.ARGUMENT_ERROR, retmsg=error_string)
  154. return func(*_args, **_kwargs)
  155. return decorated_function
  156. return wrapper
  157. def is_localhost(ip):
  158. return ip in {'127.0.0.1', '::1', '[::1]', 'localhost'}
  159. def send_file_in_mem(data, filename):
  160. if not isinstance(data, (str, bytes)):
  161. data = json_dumps(data)
  162. if isinstance(data, str):
  163. data = data.encode('utf-8')
  164. f = BytesIO()
  165. f.write(data)
  166. f.seek(0)
  167. return send_file(f, as_attachment=True, attachment_filename=filename)
  168. def get_json_result(retcode=RetCode.SUCCESS, retmsg='success', data=None):
  169. response = {"retcode": retcode, "retmsg": retmsg, "data": data}
  170. return jsonify(response)
  171. def construct_response(retcode=RetCode.SUCCESS,
  172. retmsg='success', data=None, auth=None):
  173. result_dict = {"retcode": retcode, "retmsg": retmsg, "data": data}
  174. response_dict = {}
  175. for key, value in result_dict.items():
  176. if value is None and key != "retcode":
  177. continue
  178. else:
  179. response_dict[key] = value
  180. response = make_response(jsonify(response_dict))
  181. if auth:
  182. response.headers["Authorization"] = auth
  183. response.headers["Access-Control-Allow-Origin"] = "*"
  184. response.headers["Access-Control-Allow-Method"] = "*"
  185. response.headers["Access-Control-Allow-Headers"] = "*"
  186. response.headers["Access-Control-Allow-Headers"] = "*"
  187. response.headers["Access-Control-Expose-Headers"] = "Authorization"
  188. return response
  189. def construct_result(code=RetCode.DATA_ERROR, message='data is missing'):
  190. import re
  191. result_dict = {"code": code, "message": re.sub(r"rag", "seceum", message, flags=re.IGNORECASE)}
  192. response = {}
  193. for key, value in result_dict.items():
  194. if value is None and key != "code":
  195. continue
  196. else:
  197. response[key] = value
  198. return jsonify(response)
  199. def construct_json_result(code=RetCode.SUCCESS, message='success', data=None):
  200. if data is None:
  201. return jsonify({"code": code, "message": message})
  202. else:
  203. return jsonify({"code": code, "message": message, "data": data})
  204. def construct_error_response(e):
  205. stat_logger.exception(e)
  206. try:
  207. if e.code == 401:
  208. return construct_json_result(code=RetCode.UNAUTHORIZED, message=repr(e))
  209. except BaseException:
  210. pass
  211. if len(e.args) > 1:
  212. return construct_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=e.args[1])
  213. if repr(e).find("index_not_found_exception") >= 0:
  214. return construct_json_result(code=RetCode.EXCEPTION_ERROR,
  215. message="No chunk found, please upload file and parse it.")
  216. return construct_json_result(code=RetCode.EXCEPTION_ERROR, message=repr(e))
  217. def token_required(func):
  218. @wraps(func)
  219. def decorated_function(*args, **kwargs):
  220. token = flask_request.headers.get('Authorization').split()[1]
  221. objs = APIToken.query(token=token)
  222. if not objs:
  223. return get_json_result(
  224. data=False, retmsg='Token is not valid!', retcode=RetCode.AUTHENTICATION_ERROR
  225. )
  226. kwargs['tenant_id'] = objs[0].tenant_id
  227. return func(*args, **kwargs)
  228. return decorated_function
  229. def get_result(retcode=RetCode.SUCCESS, retmsg='error', data=None):
  230. if retcode == 0:
  231. if data is not None:
  232. response = {"code": retcode, "data": data}
  233. else:
  234. response = {"code": retcode}
  235. else:
  236. response = {"code": retcode, "message": retmsg}
  237. return jsonify(response)
  238. def get_error_data_result(retcode=RetCode.DATA_ERROR,
  239. retmsg='Sorry! Data missing!'):
  240. import re
  241. result_dict = {
  242. "code": retcode,
  243. "message": re.sub(
  244. r"rag",
  245. "seceum",
  246. retmsg,
  247. flags=re.IGNORECASE)}
  248. response = {}
  249. for key, value in result_dict.items():
  250. if value is None and key != "code":
  251. continue
  252. else:
  253. response[key] = value
  254. return jsonify(response)