internal 1.1.5__py3-none-any.whl → 1.1.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of internal might be problematic. Click here for more details.

internal/base_config.py CHANGED
@@ -11,9 +11,10 @@ class BaseConfig(BaseSettings):
11
11
  LOGGER_REQUEST_ENABLE: bool = True
12
12
 
13
13
  # Request
14
- REQUEST_VERIFY_SSL: bool = True
14
+ REQUEST_VERIFY_SSL: bool = False
15
15
  REQUEST_PROXY: str = ''
16
- REQUEST_RETRY: int = 5
16
+ REQUEST_RETRY_COUNT: int = 5
17
+ REQUEST_RETRY_DELAY_INITIAL_SECONDS: int = 1
17
18
  REQUEST_CONN_POOL_TIMEOUT: float = 5
18
19
  REQUEST_CONN_TIMEOUT: float = 5
19
20
  REQUEST_WRITE_TIMEOUT: float = 5
@@ -52,6 +53,8 @@ class BaseConfig(BaseSettings):
52
53
 
53
54
  # Exception Notify
54
55
  WEBHOOK_BASE_URL: str = ""
56
+ WEBHOOK_RETRY_COUNT: int = 5
57
+ WEBHOOK_RETRY_DELAY_INITIAL_SECONDS: int = 1
55
58
 
56
59
  # Default System Account Password
57
60
  SYSTEM_ACCOUNT: str = "cruisys"
internal/http/requests.py CHANGED
@@ -1,3 +1,6 @@
1
+ import asyncio
2
+ import random
3
+
1
4
  import httpx
2
5
 
3
6
  from fastapi import FastAPI
@@ -8,9 +11,34 @@ from ..const import CORRELATION_ID_HEADER_KEY_NAME
8
11
  from ..exception.internal_exception import GatewayTimeoutException, BadGatewayException
9
12
 
10
13
 
14
+ async def invoke_request(timeout: httpx.Timeout, method: str, url: str, app: FastAPI, **kwargs):
15
+ try:
16
+ async with httpx.AsyncClient(timeout=timeout, verify=app.state.config.REQUEST_VERIFY_SSL) as client:
17
+ if "json" in kwargs:
18
+ kwargs["json"] = jsonable_encoder(kwargs["json"])
19
+
20
+ app.state.logger.info(f"invoke_request() request, url: {method} {url} \nkwargs: {kwargs}")
21
+ response = await client.request(method, url, **kwargs)
22
+ app.state.logger.info(
23
+ f"invoke_request() response, url: {method} {url} \nkwargs: {kwargs} \n\nresponse.status_code: {response.status_code} \nresponse.text: {response.text}"
24
+ )
25
+ return response
26
+ except httpx.TimeoutException as exc:
27
+ app.state.logger.warn(
28
+ f"invoke_request(), TimeoutException, exc: {exc}, url: {url}, method: {method}, kwargs: {kwargs}")
29
+ raise GatewayTimeoutException(
30
+ f"invoke_request(), url: {url}, method: {method}, kwargs: {kwargs}, HTTP TimeoutError occurred: {exc}") from exc
31
+ except Exception as exc:
32
+ app.state.logger.warn(
33
+ f"invoke_request(), Exception, exc: {exc}, url: {url}, method: {method}, kwargs: {kwargs}")
34
+ raise BadGatewayException(
35
+ f"invoke_request(), url: {url}, method: {method}, kwargs: {kwargs}, Error occurred: {exc}") from exc
36
+
37
+
11
38
  async def async_request(app: FastAPI, method, url, current_user: dict = None,
12
39
  request_conn_pool_timeout: float = 0, request_conn_timeout: float = 0,
13
40
  request_write_timeout: float = 0, response_read_timeout: float = 0,
41
+ request_retry_count: int = 0, request_retry_delay: float = 0,
14
42
  **kwargs):
15
43
  if request_conn_pool_timeout <= 0:
16
44
  request_conn_pool_timeout = app.state.config.REQUEST_CONN_POOL_TIMEOUT
@@ -20,6 +48,10 @@ async def async_request(app: FastAPI, method, url, current_user: dict = None,
20
48
  request_write_timeout = app.state.config.REQUEST_WRITE_TIMEOUT
21
49
  if response_read_timeout <= 0:
22
50
  response_read_timeout = app.state.config.RESPONSE_READ_TIMEOUT
51
+ if request_retry_count <= 0:
52
+ request_retry_count = app.state.config.REQUEST_RETRY_COUNT
53
+ if request_retry_delay <= 0:
54
+ request_retry_delay = app.state.config.REQUEST_RETRY_DELAY_INITIAL_SECONDS
23
55
 
24
56
  timeout = httpx.Timeout(connect=request_conn_timeout, read=response_read_timeout,
25
57
  write=request_write_timeout, pool=request_conn_pool_timeout)
@@ -39,30 +71,89 @@ async def async_request(app: FastAPI, method, url, current_user: dict = None,
39
71
  "Authorization": f"Bearer {current_user.get('access_token')}"
40
72
  }
41
73
 
42
- try:
43
- async with httpx.AsyncClient(timeout=timeout, verify=False) as client:
44
- if "json" in kwargs:
45
- kwargs["json"] = jsonable_encoder(kwargs["json"])
74
+ if request_retry_count <= 0:
75
+ response = await invoke_request(timeout, method, url, app, **kwargs)
76
+ return response
77
+ else:
78
+ retries = 0
79
+ current_delay = float(request_retry_delay)
46
80
 
47
- app.state.logger.info(f"async_request() request, url: {method} {url} \nkwargs: {kwargs}")
48
- response = await client.request(method, url, **kwargs)
49
- app.state.logger.info(
50
- f"async_request() response, url: {method} {url} \nkwargs: {kwargs} \n\nresponse.status_code: {response.status_code} \nresponse.text: {response.text}")
51
- return response
52
- except httpx.TimeoutException as exc:
53
- app.state.logger.warn(
54
- f"async_request(), TimeoutException, exc: {exc}, url: {url}, method: {method}, kwargs: {kwargs}")
55
- raise GatewayTimeoutException(str(exc))
56
- except Exception as exc:
57
- app.state.logger.warn(
58
- f"async_request(), Exception, exc: {exc}, url: {url}, method: {method}, kwargs: {kwargs}")
59
- raise BadGatewayException(str(exc))
81
+ while retries <= request_retry_count:
82
+ app.state.logger.warn(f"嘗試送請求 (第 {retries + 1} 次嘗試)...")
83
+ try:
84
+ # 使用 await 關鍵字等待異步請求完成
85
+ response = await invoke_request(timeout, method, url, app, **kwargs)
86
+ return response
87
+ except GatewayTimeoutException as e:
88
+ if retries < request_retry_count:
89
+ # 計算下一次的延遲時間:current_delay * 2^retries + 隨機抖動
90
+ sleep_time = current_delay * (2 ** retries) + random.uniform(0, 0.5)
91
+ app.state.logger.warn(f"等待 {sleep_time:.2f} 秒後重試...")
92
+ # 使用 asyncio.sleep 進行異步等待,不會阻塞主執行緒
93
+ await asyncio.sleep(sleep_time)
94
+ retries += 1
95
+ else:
96
+ app.state.logger.warn(f"已達到最大重試次數 ({request_retry_count}),放棄發送請求。")
97
+ raise # 重新拋出最後一個異常
98
+
99
+
100
+ async def invoke_webhook_message_api(app: FastAPI, message: str):
101
+ payload = {"text": message}
102
+ response = await async_request(app, "POST", app.state.config.WEBHOOK_BASE_URL, json=payload)
103
+ response.raise_for_status()
104
+ return response
60
105
 
61
106
 
62
107
  async def send_webhook_message(app: FastAPI, message: str):
63
- if app.state.config.WEBHOOK_BASE_URL:
64
- payload = {"text": message}
108
+ if not app.state.config.WEBHOOK_BASE_URL:
109
+ app.state.logger.warn(f"Skip notify webhook url is null")
110
+ return None
111
+
112
+ retry_count = app.state.config.WEBHOOK_RETRY_COUNT
113
+ if retry_count <= 0:
65
114
  try:
66
- await async_request(app, "POST", app.state.config.WEBHOOK_BASE_URL, json=payload)
115
+ response = await invoke_webhook_message_api(app, message)
116
+ return response
67
117
  except Exception as e:
68
118
  app.state.logger.warn(f"Notify failure, Exception:{e}")
119
+ else:
120
+ retries = 0
121
+ current_delay = float(app.state.config.WEBHOOK_RETRY_DELAY_INITIAL_SECONDS)
122
+
123
+ while retries <= retry_count:
124
+ app.state.logger.warn(f"嘗試發送訊息 (第 {retries + 1} 次嘗試)...")
125
+ try:
126
+ # 使用 await 關鍵字等待異步請求完成
127
+ response = await invoke_webhook_message_api(app, message)
128
+ return response
129
+ except httpx.HTTPStatusError as e:
130
+ if e.response.status_code == 429:
131
+ app.state.logger.warn(f"收到 429 錯誤:{e.response.status_code} - {e.response.text}")
132
+ if retries < retry_count:
133
+ # 計算下一次的延遲時間:current_delay * 2^retries + 隨機抖動
134
+ sleep_time = current_delay * (2 ** retries) + random.uniform(0, 0.5)
135
+ app.state.logger.warn(f"等待 {sleep_time:.2f} 秒後重試...")
136
+ # 使用 asyncio.sleep 進行異步等待,不會阻塞主執行緒
137
+ await asyncio.sleep(sleep_time)
138
+ retries += 1
139
+ else:
140
+ app.state.logger.warn(
141
+ f"已達到最大重試次數 ({app.state.config.WEBHOOK_RETRY_COUNT}),放棄發送訊息。")
142
+ raise # 重新拋出最後一個異常
143
+ else:
144
+ app.state.logger.warn(f"發生其他 HTTP 錯誤:{e.response.status_code} - {e.response.text}")
145
+ raise # 對於非 429 錯誤,直接拋出
146
+
147
+ except httpx.RequestError as e:
148
+ # 處理網絡錯誤,例如 DNS 查找失敗、連接超時等
149
+ app.state.logger.warn(f"發生網絡錯誤:{e}")
150
+ if retries < retry_count:
151
+ sleep_time = current_delay * (2 ** retries) + random.uniform(0, 0.5)
152
+ app.state.logger.warn(f"等待 {sleep_time:.2f} 秒後重試...")
153
+ await asyncio.sleep(sleep_time)
154
+ retries += 1
155
+ else:
156
+ app.state.logger.warn(f"已達到最大重試次數 ({retry_count}),放棄發送訊息。")
157
+ raise
158
+
159
+ return None # 如果重試次數用盡仍未成功
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: internal
3
- Version: 1.1.5
3
+ Version: 1.1.7
4
4
  Summary:
5
5
  Author: Ray
6
6
  Author-email: ray@cruisys.com
@@ -1,5 +1,5 @@
1
1
  internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- internal/base_config.py,sha256=CtGIJhMSYsJQxvfkr5rZxuuXpGUY9RYyAf-p8MDv2pM,2142
2
+ internal/base_config.py,sha256=3gOJxFW70lb9whTwsJt87Z0CLFUssw0tU7YDb2280e0,2280
3
3
  internal/base_factory.py,sha256=DVWjOeCOURscykpm0MizOvT9PjbclpoVv92XySWMDkw,11353
4
4
  internal/cache_redis.py,sha256=YMsrUXHd-wKjsjsboD79Y-ciBBowzT6aAjdJZ36-yEY,697
5
5
  internal/common_enum/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -23,7 +23,7 @@ internal/ext/amazon/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSu
23
23
  internal/ext/amazon/aws/__init__.py,sha256=2YFjb-rHG1JaZGZiZffYDesgTAJjDshOqQbswOYzhP8,834
24
24
  internal/ext/amazon/aws/const.py,sha256=l4WMg5bKWujwOKABBkCO2zclNg3abnYOfbhD7DG8GsA,109
25
25
  internal/http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
- internal/http/requests.py,sha256=cgzLPD0w_JdNh_I3w-dvOJwwrgPU7QtVH7OQtGaqFBM,3140
26
+ internal/http/requests.py,sha256=yNGoTHzCSISaljArc40K_arnUeU6Y3K7U5pJEameklA,7861
27
27
  internal/http/responses.py,sha256=zvU0iRQ9-qxeEZfKmuvTi8lv9DFcaNAsHlQKOTCpVzw,2945
28
28
  internal/interface/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
29
  internal/interface/base_interface.py,sha256=3YaVjIgLi_pZpLk5SEIk8WVkuICM8qPavT8rB0MdB5U,1536
@@ -34,6 +34,6 @@ internal/model/base_model.py,sha256=hxleV8fYNvFgUoYmCv_inEP3kA4tD4HhCBCNFVK8SZg,
34
34
  internal/model/operate.py,sha256=QSM6yXYXpJMwrqkUGEWZLrEBaUgqHwVHY_Fi4S42hKc,3190
35
35
  internal/utils.py,sha256=i6YZdiXsiWnOjRdlJ6afNCGpyMe3Uo9mhm3xlQBy3Ls,2824
36
36
  internal/validator_utils.py,sha256=CqjaVFoAu5MqvBG_AkTP-r7AliWawtUWB851USj4moI,1519
37
- internal-1.1.5.dist-info/METADATA,sha256=YRtNqS8TKkAREgS6YAVQENd-FCUzEouFZHX78XGjo9k,938
38
- internal-1.1.5.dist-info/WHEEL,sha256=RaoafKOydTQ7I_I3JTrPCg6kUmTgtm4BornzOqyEfJ8,88
39
- internal-1.1.5.dist-info/RECORD,,
37
+ internal-1.1.7.dist-info/METADATA,sha256=W_8Em-DtofNIqceC6cuObuLGukuBepuVQXjd4Ayg9f4,938
38
+ internal-1.1.7.dist-info/WHEEL,sha256=RaoafKOydTQ7I_I3JTrPCg6kUmTgtm4BornzOqyEfJ8,88
39
+ internal-1.1.7.dist-info/RECORD,,