1+ """Eureka client integration for service discovery and registration."""
2+
13import os
24import urllib .request
35import logging
6+ from typing import Union
7+ from urllib .error import URLError
8+
49from cfenv import AppEnv
510from oauth2 import OAuth2Client
6- import py_eureka_client .eureka_client as eureka_client
7- import py_eureka_client .http_client as http_client
8- from urllib .error import URLError
9- from typing import Union
11+ from py_eureka_client import eureka_client , http_client
1012
1113logger = logging .getLogger (__name__ )
1214
@@ -16,6 +18,7 @@ class _OAuth2HttpClient(http_client.HttpClient):
1618 """
1719
1820 def __init__ (self , credentials : dict ):
21+ """Initialize the OAuth2 HTTP client with credentials."""
1922 self .oauth_client = OAuth2Client (
2023 client_id = credentials ['client_id' ],
2124 client_secret = credentials ['client_secret' ],
@@ -24,29 +27,32 @@ def __init__(self, credentials: dict):
2427
2528 async def urlopen (self , request : Union [str , http_client .HttpRequest ] = None ,
2629 data : bytes = None , timeout : float = None ) -> http_client .HttpResponse :
30+ """Open a URL with OAuth2 authentication."""
2731 if isinstance (request , http_client .HttpRequest ):
2832 req = request
2933 elif isinstance (request , str ):
3034 req = http_client .HttpRequest (request , headers = {'Accept-Encoding' : 'gzip' })
3135 else :
3236 raise URLError ("Invalid URL" )
3337
34- req = req ._to_urllib_request ()
38+ req = req ._to_urllib_request () # pylint: disable=protected-access
3539 req .add_header ("Connection" , "close" )
3640 req .add_header ("Authorization" , f"Bearer { self .oauth_client .get_access_token ()} " )
37- res = urllib .request .urlopen (req , data = data , timeout = timeout )
38- return http_client .HttpResponse (res )
41+ with urllib .request .urlopen (req , data = data , timeout = timeout ) as res :
42+ return http_client .HttpResponse (res )
43+
44+ def get_oauth_client (self ):
45+ """Get the OAuth2 client instance."""
46+ return self .oauth_client
3947
4048def _on_err (err_type : str , err : Exception ):
41- logger .error (f"Eureka client error - Type: { err_type } , Error: { err } " )
49+ """Handle Eureka client errors."""
50+ logger .error ("Eureka client error - Type: %s, Error: %s" , err_type , err )
4251 if err_type in (eureka_client .ERROR_REGISTER , eureka_client .ERROR_DISCOVER ):
4352 eureka_client .stop ()
4453
4554def init_client ():
46- """
47- Initializes the eureka client.
48- """
49-
55+ """Initialize the eureka client."""
5056 env = AppEnv ()
5157
5258 service_registry = env .get_service (label = "p.service-registry" )
@@ -58,26 +64,24 @@ def init_client():
5864 http_client .set_http_client (_OAuth2HttpClient (credentials ))
5965
6066 eureka_client .init (
61- app_name = env .name ,
62- instance_host = env .uris [0 ],
63- instance_ip = os .getenv ('CF_INSTANCE_INTERNAL_IP' ),
64- instance_id = f"{ env .uris [0 ]} :{ env .app .get ('instance_id' ) or '0' } " ,
65- instance_unsecure_port_enabled = True ,
66- instance_port = 80 ,
67- instance_secure_port_enabled = True ,
68- instance_secure_port = 443 ,
69- vip_adr = 'UNKNOWN' ,
70- secure_vip_addr = 'UNKNOWN' ,
71- eureka_server = credentials ['uri' ],
72- on_error = _on_err
73- )
67+ app_name = env .name ,
68+ instance_host = env .uris [0 ],
69+ instance_ip = os .getenv ('CF_INSTANCE_INTERNAL_IP' ),
70+ instance_id = f"{ env .uris [0 ]} :{ env .app .get ('instance_id' ) or '0' } " ,
71+ instance_unsecure_port_enabled = True ,
72+ instance_port = 80 ,
73+ instance_secure_port_enabled = True ,
74+ instance_secure_port = 443 ,
75+ vip_adr = 'UNKNOWN' ,
76+ secure_vip_addr = 'UNKNOWN' ,
77+ eureka_server = credentials ['uri' ],
78+ on_error = _on_err
79+ )
7480
7581def call_service (name : str , path : str ):
76- """
77- Calls a service with the given name and path.
78- """
82+ """Call a service with the given name and path."""
7983 try :
8084 return eureka_client .do_service (app_name = name , service = path , prefer_https = True )
8185 except urllib .request .HTTPError as e :
82- logger .error (f "Error calling service { name } at { path } : { e } " )
83- raise e
86+ logger .error ("Error calling service %s at %s: %s" , name , path , e )
87+ raise e
0 commit comments