1
1
from enum import Enum
2
2
3
- import cachetools .func
4
3
import requests
5
4
import structlog
6
5
7
- from codegate .db .connection import DbReader
8
-
9
6
logger = structlog .get_logger ("codegate" )
10
7
11
8
9
+ __update_client_singleton = None
10
+
11
+
12
12
# Enum representing whether the request is coming from the front-end or the back-end.
13
13
class Origin (Enum ):
14
14
FrontEnd = "FE"
15
15
BackEnd = "BE"
16
16
17
17
18
18
class UpdateClient :
19
- def __init__ (self , update_url : str , current_version : str , db_reader : DbReader ):
19
+ def __init__ (self , update_url : str , current_version : str , instance_id : str ):
20
20
self .__update_url = update_url
21
21
self .__current_version = current_version
22
- self .__db_reader = db_reader
23
- self .__instance_id = None
22
+ self .__instance_id = instance_id
24
23
25
- async def get_latest_version (self , origin : Origin ) -> str :
24
+ def get_latest_version (self , origin : Origin ) -> str :
26
25
"""
27
26
Retrieves the latest version of CodeGate from updates.codegate.ai
28
27
"""
29
- logger .info (f"Fetching latest version from { self .__update_url } " )
30
- instance_id = await self .__get_instance_id ()
31
- return self .__fetch_latest_version (instance_id , origin )
32
-
33
- @cachetools .func .ttl_cache (maxsize = 128 , ttl = 20 * 60 )
34
- def __fetch_latest_version (self , instance_id : str , origin : Origin ) -> str :
35
28
headers = {
36
- "X-Instance-ID" : instance_id ,
29
+ "X-Instance-ID" : self . __instance_id ,
37
30
"User-Agent" : f"codegate/{ self .__current_version } { origin .value } " ,
38
31
}
39
32
@@ -46,9 +39,19 @@ def __fetch_latest_version(self, instance_id: str, origin: Origin) -> str:
46
39
logger .error (f"Error fetching latest version from f{ self .__update_url } : { e } " )
47
40
return "unknown"
48
41
49
- # Lazy load the instance ID from the DB.
50
- async def __get_instance_id (self ):
51
- if self .__instance_id is None :
52
- instance_data = await self .__db_reader .get_instance ()
53
- self .__instance_id = instance_data [0 ].id
54
- return self .__instance_id
42
+
43
+ # Use a singleton since we do not have a good way of doing dependency injection
44
+ # with the API endpoints.
45
+ def init_update_client_singleton (
46
+ update_url : str , current_version : str , instance_id : str
47
+ ) -> UpdateClient :
48
+ global __update_client_singleton
49
+ __update_client_singleton = UpdateClient (update_url , current_version , instance_id )
50
+ return __update_client_singleton
51
+
52
+
53
+ def get_update_client_singleton () -> UpdateClient :
54
+ global __update_client_singleton
55
+ if __update_client_singleton is None :
56
+ raise ValueError ("UpdateClient singleton not initialized" )
57
+ return __update_client_singleton
0 commit comments