1+ import datetime
12import logging
23import os
34import re
45import urllib
6+ import jwt
57
68import openeo
79import requests
@@ -29,11 +31,48 @@ class OpenEOPlatform(BaseProcessingPlatform):
2931 This class handles the execution of processing jobs on the OpenEO platform.
3032 """
3133
34+ _connection_cache : dict [str , openeo .Connection ] = {}
35+
36+ def _connection_expired (self , connection : openeo .Connection ) -> bool :
37+ """
38+ Check if the cached connection is still valid.
39+ This method can be used to determine if a new connection needs to be established.
40+ """
41+ jwt_bearer_token = connection .auth .bearer .split ("/" )[- 1 ]
42+ if jwt_bearer_token :
43+ try :
44+ # Check if the token is still valid by decoding it
45+ payload = jwt .decode (
46+ jwt_bearer_token , options = {"verify_signature" : False }
47+ )
48+ exp = payload .get ("exp" )
49+ if not exp :
50+ logger .warning ("JWT bearer token does not contain 'exp' field." )
51+ return True
52+ elif exp < datetime .datetime .now (datetime .timezone .utc ).timestamp ():
53+ logger .warning ("JWT bearer token has expired." )
54+ return True # Token is expired
55+ else :
56+ logger .debug ("JWT bearer token is valid." )
57+ return False # Token is valid
58+ except Exception as e :
59+ logger .warning (f"JWT token validation failed: { e } " )
60+ return True # Token is expired or invalid
61+ else :
62+ logger .warning ("No JWT bearer token found in connection." )
63+ return True
64+
3265 def _setup_connection (self , url : str ) -> openeo .Connection :
3366 """
3467 Setup the connection to the OpenEO backend.
3568 This method can be used to initialize any required client or session.
3669 """
70+ if url in self ._connection_cache and not self ._connection_expired (
71+ self ._connection_cache [url ]
72+ ):
73+ logger .debug (f"Reusing cached OpenEO connection to { url } " )
74+ return self ._connection_cache [url ]
75+
3776 logger .debug (f"Setting up OpenEO connection to { url } " )
3877 connection = openeo .connect (url )
3978 provider_id , client_id , client_secret = self ._get_client_credentials (url )
@@ -43,6 +82,7 @@ def _setup_connection(self, url: str) -> openeo.Connection:
4382 client_id = client_id ,
4483 client_secret = client_secret ,
4584 )
85+ self ._connection_cache [url ] = connection
4686 return connection
4787
4888 def _get_client_credentials (self , url : str ) -> tuple [str , str , str ]:
0 commit comments