maleo-foundation 0.3.46__py3-none-any.whl → 0.3.47__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.
- maleo_foundation/authentication.py +24 -13
- maleo_foundation/authorization.py +2 -1
- maleo_foundation/client/manager.py +22 -21
- maleo_foundation/client/services/__init__.py +16 -7
- maleo_foundation/client/services/encryption/__init__.py +13 -4
- maleo_foundation/client/services/encryption/aes.py +41 -36
- maleo_foundation/client/services/encryption/rsa.py +50 -50
- maleo_foundation/client/services/hash/__init__.py +19 -6
- maleo_foundation/client/services/hash/bcrypt.py +20 -18
- maleo_foundation/client/services/hash/hmac.py +20 -17
- maleo_foundation/client/services/hash/sha256.py +18 -15
- maleo_foundation/client/services/key.py +50 -42
- maleo_foundation/client/services/signature.py +46 -42
- maleo_foundation/client/services/token.py +49 -58
- maleo_foundation/constants.py +12 -19
- maleo_foundation/enums.py +14 -13
- maleo_foundation/expanded_types/__init__.py +2 -3
- maleo_foundation/expanded_types/client.py +30 -34
- maleo_foundation/expanded_types/encryption/__init__.py +2 -1
- maleo_foundation/expanded_types/encryption/aes.py +7 -5
- maleo_foundation/expanded_types/encryption/rsa.py +7 -5
- maleo_foundation/expanded_types/general.py +13 -11
- maleo_foundation/expanded_types/hash.py +7 -5
- maleo_foundation/expanded_types/key.py +8 -6
- maleo_foundation/expanded_types/service.py +30 -34
- maleo_foundation/expanded_types/signature.py +7 -5
- maleo_foundation/expanded_types/token.py +7 -5
- maleo_foundation/extended_types.py +4 -3
- maleo_foundation/managers/cache.py +2 -1
- maleo_foundation/managers/client/base.py +25 -12
- maleo_foundation/managers/client/google/base.py +11 -4
- maleo_foundation/managers/client/google/parameter.py +9 -11
- maleo_foundation/managers/client/google/secret.py +53 -35
- maleo_foundation/managers/client/google/storage.py +52 -22
- maleo_foundation/managers/client/google/subscription.py +37 -39
- maleo_foundation/managers/client/maleo.py +18 -23
- maleo_foundation/managers/configuration.py +5 -9
- maleo_foundation/managers/credential.py +14 -17
- maleo_foundation/managers/db.py +51 -40
- maleo_foundation/managers/middleware.py +9 -9
- maleo_foundation/managers/service.py +47 -54
- maleo_foundation/middlewares/authentication.py +29 -54
- maleo_foundation/middlewares/base.py +83 -72
- maleo_foundation/middlewares/cors.py +8 -7
- maleo_foundation/models/__init__.py +2 -1
- maleo_foundation/models/responses.py +57 -29
- maleo_foundation/models/schemas/__init__.py +2 -1
- maleo_foundation/models/schemas/encryption.py +5 -2
- maleo_foundation/models/schemas/general.py +38 -18
- maleo_foundation/models/schemas/hash.py +2 -1
- maleo_foundation/models/schemas/key.py +5 -2
- maleo_foundation/models/schemas/parameter.py +45 -15
- maleo_foundation/models/schemas/result.py +35 -20
- maleo_foundation/models/schemas/signature.py +5 -2
- maleo_foundation/models/schemas/token.py +5 -2
- maleo_foundation/models/table.py +33 -27
- maleo_foundation/models/transfers/__init__.py +2 -1
- maleo_foundation/models/transfers/general/__init__.py +2 -1
- maleo_foundation/models/transfers/general/configurations/__init__.py +10 -4
- maleo_foundation/models/transfers/general/configurations/cache/__init__.py +3 -2
- maleo_foundation/models/transfers/general/configurations/cache/redis.py +13 -5
- maleo_foundation/models/transfers/general/configurations/client/__init__.py +5 -1
- maleo_foundation/models/transfers/general/configurations/client/maleo.py +38 -12
- maleo_foundation/models/transfers/general/configurations/database.py +5 -2
- maleo_foundation/models/transfers/general/configurations/middleware.py +22 -15
- maleo_foundation/models/transfers/general/configurations/service.py +2 -1
- maleo_foundation/models/transfers/general/credentials.py +2 -1
- maleo_foundation/models/transfers/general/database.py +11 -4
- maleo_foundation/models/transfers/general/key.py +13 -4
- maleo_foundation/models/transfers/general/request.py +28 -9
- maleo_foundation/models/transfers/general/settings.py +12 -22
- maleo_foundation/models/transfers/general/signature.py +4 -2
- maleo_foundation/models/transfers/general/token.py +34 -27
- maleo_foundation/models/transfers/parameters/__init__.py +2 -1
- maleo_foundation/models/transfers/parameters/client.py +15 -19
- maleo_foundation/models/transfers/parameters/encryption/__init__.py +2 -1
- maleo_foundation/models/transfers/parameters/encryption/aes.py +7 -5
- maleo_foundation/models/transfers/parameters/encryption/rsa.py +7 -5
- maleo_foundation/models/transfers/parameters/general.py +15 -13
- maleo_foundation/models/transfers/parameters/hash/__init__.py +2 -1
- maleo_foundation/models/transfers/parameters/hash/bcrypt.py +5 -5
- maleo_foundation/models/transfers/parameters/hash/hmac.py +6 -6
- maleo_foundation/models/transfers/parameters/hash/sha256.py +5 -5
- maleo_foundation/models/transfers/parameters/key.py +9 -8
- maleo_foundation/models/transfers/parameters/service.py +42 -48
- maleo_foundation/models/transfers/parameters/signature.py +7 -4
- maleo_foundation/models/transfers/parameters/token.py +10 -10
- maleo_foundation/models/transfers/results/__init__.py +2 -1
- maleo_foundation/models/transfers/results/client/__init__.py +2 -1
- maleo_foundation/models/transfers/results/client/controllers/__init__.py +2 -1
- maleo_foundation/models/transfers/results/client/controllers/http.py +10 -7
- maleo_foundation/models/transfers/results/client/service.py +12 -6
- maleo_foundation/models/transfers/results/encryption/__init__.py +2 -1
- maleo_foundation/models/transfers/results/encryption/aes.py +13 -5
- maleo_foundation/models/transfers/results/encryption/rsa.py +12 -4
- maleo_foundation/models/transfers/results/hash.py +7 -3
- maleo_foundation/models/transfers/results/key.py +18 -6
- maleo_foundation/models/transfers/results/service/__init__.py +2 -3
- maleo_foundation/models/transfers/results/service/controllers/__init__.py +2 -1
- maleo_foundation/models/transfers/results/service/controllers/rest.py +14 -11
- maleo_foundation/models/transfers/results/service/general.py +16 -10
- maleo_foundation/models/transfers/results/signature.py +12 -4
- maleo_foundation/models/transfers/results/token.py +10 -4
- maleo_foundation/rest_controller_result.py +23 -21
- maleo_foundation/types.py +15 -14
- maleo_foundation/utils/__init__.py +2 -1
- maleo_foundation/utils/cache.py +10 -13
- maleo_foundation/utils/client.py +25 -12
- maleo_foundation/utils/controller.py +59 -37
- maleo_foundation/utils/dependencies/__init__.py +2 -1
- maleo_foundation/utils/dependencies/auth.py +5 -12
- maleo_foundation/utils/dependencies/context.py +3 -4
- maleo_foundation/utils/exceptions.py +50 -28
- maleo_foundation/utils/extractor.py +18 -6
- maleo_foundation/utils/formatter/__init__.py +2 -1
- maleo_foundation/utils/formatter/case.py +5 -4
- maleo_foundation/utils/loaders/__init__.py +2 -1
- maleo_foundation/utils/loaders/credential/__init__.py +2 -1
- maleo_foundation/utils/loaders/credential/google.py +29 -15
- maleo_foundation/utils/loaders/json.py +3 -2
- maleo_foundation/utils/loaders/key/__init__.py +2 -1
- maleo_foundation/utils/loaders/key/rsa.py +26 -13
- maleo_foundation/utils/loaders/yaml.py +2 -1
- maleo_foundation/utils/logging.py +70 -46
- maleo_foundation/utils/merger.py +7 -9
- maleo_foundation/utils/query.py +41 -34
- maleo_foundation/utils/repository.py +28 -13
- maleo_foundation/utils/searcher.py +4 -6
- {maleo_foundation-0.3.46.dist-info → maleo_foundation-0.3.47.dist-info}/METADATA +14 -1
- maleo_foundation-0.3.47.dist-info/RECORD +137 -0
- maleo_foundation/expanded_types/repository.py +0 -68
- maleo_foundation/models/transfers/results/service/repository.py +0 -39
- maleo_foundation-0.3.46.dist-info/RECORD +0 -139
- {maleo_foundation-0.3.46.dist-info → maleo_foundation-0.3.47.dist-info}/WHEEL +0 -0
- {maleo_foundation-0.3.46.dist-info → maleo_foundation-0.3.47.dist-info}/top_level.txt +0 -0
@@ -4,11 +4,10 @@ from maleo_foundation.models.transfers.general.settings import Settings
|
|
4
4
|
from maleo_foundation.utils.loaders.yaml import YAMLLoader
|
5
5
|
from .credential import CredentialManager
|
6
6
|
|
7
|
+
|
7
8
|
class ConfigurationManager:
|
8
9
|
def __init__(
|
9
|
-
self,
|
10
|
-
settings: Settings,
|
11
|
-
credential_manager: CredentialManager
|
10
|
+
self, settings: Settings, credential_manager: CredentialManager
|
12
11
|
) -> None:
|
13
12
|
self._settings = settings
|
14
13
|
self._credential_manager = credential_manager
|
@@ -23,15 +22,12 @@ class ConfigurationManager:
|
|
23
22
|
self._configurations = Configurations.model_validate(data)
|
24
23
|
return
|
25
24
|
|
26
|
-
secret_data = (
|
27
|
-
self
|
28
|
-
._credential_manager
|
29
|
-
.secret_manager
|
30
|
-
.get(f"{self._settings.SERVICE_KEY}-configurations-{self._settings.ENVIRONMENT}")
|
25
|
+
secret_data = self._credential_manager.secret_manager.get(
|
26
|
+
f"{self._settings.SERVICE_KEY}-configurations-{self._settings.ENVIRONMENT}"
|
31
27
|
)
|
32
28
|
data = YAMLLoader.load_from_string(secret_data)
|
33
29
|
self._configurations = Configurations.model_validate(data)
|
34
30
|
|
35
31
|
@property
|
36
32
|
def configurations(self) -> Configurations:
|
37
|
-
return self._configurations
|
33
|
+
return self._configurations
|
@@ -7,12 +7,9 @@ from maleo_foundation.models.transfers.general.settings import Settings
|
|
7
7
|
from maleo_foundation.utils.loaders.credential.google import GoogleCredentialsLoader
|
8
8
|
from maleo_foundation.utils.logging import SimpleConfig
|
9
9
|
|
10
|
+
|
10
11
|
class CredentialManager:
|
11
|
-
def __init__(
|
12
|
-
self,
|
13
|
-
settings: Settings,
|
14
|
-
log_config: SimpleConfig
|
15
|
-
):
|
12
|
+
def __init__(self, settings: Settings, log_config: SimpleConfig):
|
16
13
|
self.settings = settings
|
17
14
|
self.log_config = log_config
|
18
15
|
self._initialize()
|
@@ -34,7 +31,7 @@ class CredentialManager:
|
|
34
31
|
self._secret_manager = GoogleSecretManager(
|
35
32
|
log_config=self.log_config,
|
36
33
|
service_key=self.settings.SERVICE_KEY,
|
37
|
-
credentials=self._google_credentials
|
34
|
+
credentials=self._google_credentials,
|
38
35
|
)
|
39
36
|
|
40
37
|
def _get_environment_for_credentials(self) -> str:
|
@@ -48,18 +45,18 @@ class CredentialManager:
|
|
48
45
|
environment = self._get_environment_for_credentials()
|
49
46
|
|
50
47
|
try:
|
51
|
-
id = int(
|
52
|
-
|
48
|
+
id = int(
|
49
|
+
self._secret_manager.get(f"maleo-service-account-id-{environment}")
|
50
|
+
)
|
51
|
+
uuid = UUID(
|
52
|
+
self._secret_manager.get(f"maleo-service-account-uuid-{environment}")
|
53
|
+
)
|
53
54
|
email = self._secret_manager.get("maleo-service-account-email")
|
54
55
|
username = self._secret_manager.get("maleo-service-account-username")
|
55
56
|
password = self._secret_manager.get("maleo-service-account-password")
|
56
|
-
|
57
|
+
|
57
58
|
self._maleo_credentials = MaleoCredentials(
|
58
|
-
id=id,
|
59
|
-
uuid=uuid,
|
60
|
-
username=username,
|
61
|
-
email=email,
|
62
|
-
password=password
|
59
|
+
id=id, uuid=uuid, username=username, email=email, password=password
|
63
60
|
)
|
64
61
|
except Exception as e:
|
65
62
|
raise RuntimeError(f"Failed to load Maleo credentials: {str(e)}")
|
@@ -72,11 +69,11 @@ class CredentialManager:
|
|
72
69
|
@property
|
73
70
|
def google_credentials(self) -> Credentials:
|
74
71
|
return self._google_credentials
|
75
|
-
|
72
|
+
|
76
73
|
@property
|
77
74
|
def secret_manager(self) -> GoogleSecretManager:
|
78
75
|
return self._secret_manager
|
79
|
-
|
76
|
+
|
80
77
|
@property
|
81
78
|
def maleo_credentials(self) -> MaleoCredentials:
|
82
|
-
return self._maleo_credentials
|
79
|
+
return self._maleo_credentials
|
maleo_foundation/managers/db.py
CHANGED
@@ -10,21 +10,18 @@ from typing import Generator
|
|
10
10
|
from maleo_foundation.types import BaseTypes
|
11
11
|
from maleo_foundation.utils.logging import DatabaseLogger
|
12
12
|
|
13
|
+
|
13
14
|
class MetadataManager:
|
14
15
|
Base: DeclarativeMeta = declarative_base()
|
15
16
|
metadata: MetaData = Base.metadata
|
16
17
|
|
18
|
+
|
17
19
|
class SessionManager:
|
18
|
-
def __init__(
|
19
|
-
self,
|
20
|
-
logger: DatabaseLogger,
|
21
|
-
engine: Engine
|
22
|
-
):
|
20
|
+
def __init__(self, logger: DatabaseLogger, engine: Engine):
|
23
21
|
self._logger = logger
|
24
22
|
self._logger.info("Initializing SessionMaker")
|
25
|
-
self._sessionmaker:sessionmaker[Session] = sessionmaker(
|
26
|
-
bind=engine,
|
27
|
-
expire_on_commit=False
|
23
|
+
self._sessionmaker: sessionmaker[Session] = sessionmaker(
|
24
|
+
bind=engine, expire_on_commit=False
|
28
25
|
)
|
29
26
|
self._logger.info("SessionMaker initialized successfully")
|
30
27
|
|
@@ -33,18 +30,22 @@ class SessionManager:
|
|
33
30
|
session = self._sessionmaker()
|
34
31
|
self._logger.debug("New database session created.")
|
35
32
|
try:
|
36
|
-
yield session
|
37
|
-
session.commit()
|
33
|
+
yield session # * Provide session
|
34
|
+
session.commit() # * Auto-commit on success
|
38
35
|
except SQLAlchemyError as e:
|
39
|
-
session.rollback()
|
40
|
-
self._logger.error(
|
36
|
+
session.rollback() # * Rollback on error
|
37
|
+
self._logger.error(
|
38
|
+
f"[SQLAlchemyError] Database transaction failed: {e}", exc_info=True
|
39
|
+
)
|
41
40
|
raise
|
42
41
|
except Exception as e:
|
43
|
-
session.rollback()
|
44
|
-
self._logger.error(
|
42
|
+
session.rollback() # * Rollback on error
|
43
|
+
self._logger.error(
|
44
|
+
f"[Exception] Database transaction failed: {e}", exc_info=True
|
45
|
+
)
|
45
46
|
raise
|
46
47
|
finally:
|
47
|
-
session.close()
|
48
|
+
session.close() # * Ensure session closes
|
48
49
|
self._logger.debug("Database session closed.")
|
49
50
|
|
50
51
|
def inject(self) -> Generator[Session, None, None]:
|
@@ -60,10 +61,9 @@ class SessionManager:
|
|
60
61
|
"""Dispose of the sessionmaker and release any resources."""
|
61
62
|
if self._sessionmaker is not None:
|
62
63
|
self._sessionmaker.close_all()
|
63
|
-
self._sessionmaker = None
|
64
64
|
|
65
65
|
self._logger.info("SessionManager disposed successfully")
|
66
|
-
|
66
|
+
|
67
67
|
|
68
68
|
class DatabaseConfigurations(BaseModel):
|
69
69
|
username: str = Field("postgres", description="Database user's username")
|
@@ -76,83 +76,94 @@ class DatabaseConfigurations(BaseModel):
|
|
76
76
|
def url(self) -> str:
|
77
77
|
return f"postgresql://{self.username}:{self.password}@{self.host}:{self.port}/{self.database}"
|
78
78
|
|
79
|
+
|
79
80
|
class DatabaseManager:
|
80
81
|
def __init__(
|
81
82
|
self,
|
82
83
|
metadata: MetaData,
|
83
84
|
logger: DatabaseLogger,
|
84
|
-
url: BaseTypes.OptionalString = None
|
85
|
+
url: BaseTypes.OptionalString = None,
|
85
86
|
):
|
86
|
-
self._metadata = metadata
|
87
|
-
self._logger = logger
|
87
|
+
self._metadata = metadata # * Define database metadata
|
88
|
+
self._logger = logger # * Define database logger
|
88
89
|
|
89
|
-
|
90
|
+
# * Create engine
|
90
91
|
url = url or os.getenv("DB_URL")
|
91
92
|
if url is None:
|
92
|
-
raise ValueError(
|
93
|
+
raise ValueError(
|
94
|
+
"DB_URL environment variable must be set if url is not provided"
|
95
|
+
)
|
93
96
|
self._logger.info("Creating SQlAlchemy engine")
|
94
97
|
self._engine = create_engine(
|
95
|
-
url=url,
|
96
|
-
|
97
|
-
pool_pre_ping=True,
|
98
|
-
pool_recycle=3600)
|
98
|
+
url=url, echo=False, pool_pre_ping=True, pool_recycle=3600
|
99
|
+
)
|
99
100
|
self._logger.info("SQlAlchemy engine created successfully")
|
100
101
|
|
101
|
-
|
102
|
+
# * Creating all table from metadata
|
102
103
|
self._logger.info("Creating all tables defined in metadata")
|
103
|
-
self._metadata.create_all(bind=self._engine)
|
104
|
+
self._metadata.create_all(bind=self._engine) # * Create all tables
|
104
105
|
self._logger.info("Created all tables defined in metadata")
|
105
106
|
|
106
|
-
|
107
|
+
# * Initializing session manager
|
107
108
|
self._logger.info("Initializing session manager")
|
108
|
-
|
109
|
-
self._session = SessionManager(
|
110
|
-
logger=self._logger,
|
111
|
-
engine=self._engine
|
112
|
-
)
|
109
|
+
# * Create session
|
110
|
+
self._session = SessionManager(logger=self._logger, engine=self._engine)
|
113
111
|
self._logger.info("Session manager initialized successfully")
|
114
112
|
|
115
113
|
@property
|
116
114
|
def metadata(self) -> MetaData:
|
115
|
+
if self._metadata is None:
|
116
|
+
raise ValueError("Metadata has not been initialized.")
|
117
117
|
return self._metadata
|
118
118
|
|
119
119
|
@property
|
120
120
|
def engine(self) -> Engine:
|
121
|
+
if self._engine is None:
|
122
|
+
raise ValueError("Engine has not been initialized.")
|
121
123
|
return self._engine
|
122
124
|
|
123
125
|
@property
|
124
126
|
def session(self) -> SessionManager:
|
127
|
+
if self._session is None:
|
128
|
+
raise ValueError("Session manager has not been initialized.")
|
125
129
|
return self._session
|
126
130
|
|
127
131
|
def check_connection(self) -> bool:
|
128
132
|
"""Check database connectivity by executing a simple query."""
|
129
133
|
self._logger.info("Checking database connectivity...")
|
134
|
+
if self._session is None:
|
135
|
+
self._logger.error("Session manager is not initialized.")
|
136
|
+
return False
|
130
137
|
try:
|
131
138
|
with self._session.get() as session:
|
132
139
|
session.execute(text("SELECT 1"))
|
133
140
|
self._logger.info("Database connectivity check successful.")
|
134
141
|
return True
|
135
142
|
except SQLAlchemyError as se:
|
136
|
-
self._logger.error(
|
143
|
+
self._logger.error(
|
144
|
+
f"Database connectivity check failed: {se}", exc_info=True
|
145
|
+
)
|
137
146
|
return False
|
138
147
|
except Exception as e:
|
139
|
-
self._logger.error(
|
148
|
+
self._logger.error(
|
149
|
+
f"Unexpected error during connectivity check: {e}", exc_info=True
|
150
|
+
)
|
140
151
|
return False
|
141
152
|
|
142
153
|
def dispose(self) -> None:
|
143
|
-
|
154
|
+
# * Dispose session
|
144
155
|
if self._session is not None:
|
145
156
|
self._logger.info("Disposing Session Manager")
|
146
157
|
self._session.dispose()
|
147
158
|
self._session = None
|
148
|
-
|
159
|
+
# * Dispose engine
|
149
160
|
if self._engine is not None:
|
150
161
|
self._logger.info("Disposing Engine Manager")
|
151
162
|
self._engine.dispose()
|
152
163
|
self._engine = None
|
153
164
|
self._logger.info("Engine Manager disposed successfully")
|
154
|
-
|
165
|
+
# * Dispose metadata
|
155
166
|
if self._metadata is not None:
|
156
167
|
self._logger.info("Disposing DB Metadata")
|
157
168
|
self._metadata = None
|
158
|
-
self._logger.info("DB Metadata diposed succesfully")
|
169
|
+
self._logger.info("DB Metadata diposed succesfully")
|
@@ -1,13 +1,15 @@
|
|
1
1
|
from fastapi import FastAPI
|
2
2
|
from maleo_foundation.client.manager import MaleoFoundationClientManager
|
3
3
|
from maleo_foundation.models.schemas import BaseGeneralSchemas
|
4
|
-
from maleo_foundation.models.transfers.general.configurations.middleware
|
5
|
-
|
4
|
+
from maleo_foundation.models.transfers.general.configurations.middleware import (
|
5
|
+
MiddlewareConfigurations,
|
6
|
+
)
|
6
7
|
from maleo_foundation.middlewares.authentication import add_authentication_middleware
|
7
8
|
from maleo_foundation.middlewares.base import add_base_middleware
|
8
9
|
from maleo_foundation.middlewares.cors import add_cors_middleware
|
9
10
|
from maleo_foundation.utils.logging import MiddlewareLogger
|
10
11
|
|
12
|
+
|
11
13
|
class MiddlewareManager:
|
12
14
|
def __init__(
|
13
15
|
self,
|
@@ -15,7 +17,7 @@ class MiddlewareManager:
|
|
15
17
|
configurations: MiddlewareConfigurations,
|
16
18
|
keys: BaseGeneralSchemas.RSAKeys,
|
17
19
|
logger: MiddlewareLogger,
|
18
|
-
maleo_foundation: MaleoFoundationClientManager
|
20
|
+
maleo_foundation: MaleoFoundationClientManager,
|
19
21
|
):
|
20
22
|
self._app = app
|
21
23
|
self._configurations = configurations
|
@@ -35,7 +37,7 @@ class MiddlewareManager:
|
|
35
37
|
allow_methods=self._configurations.general.allow_methods,
|
36
38
|
allow_headers=self._configurations.general.allow_headers,
|
37
39
|
allow_credentials=self._configurations.general.allow_credentials,
|
38
|
-
expose_headers=self._configurations.cors.expose_headers
|
40
|
+
expose_headers=self._configurations.cors.expose_headers,
|
39
41
|
)
|
40
42
|
|
41
43
|
def add_base(self):
|
@@ -51,12 +53,10 @@ class MiddlewareManager:
|
|
51
53
|
limit=self._configurations.base.limit,
|
52
54
|
window=self._configurations.base.window,
|
53
55
|
cleanup_interval=self._configurations.base.cleanup_interval,
|
54
|
-
ip_timeout=self._configurations.base.ip_timeout
|
56
|
+
ip_timeout=self._configurations.base.ip_timeout,
|
55
57
|
)
|
56
58
|
|
57
59
|
def add_authentication(self):
|
58
60
|
add_authentication_middleware(
|
59
|
-
app=self._app,
|
60
|
-
|
61
|
-
maleo_foundation=self._maleo_foundation
|
62
|
-
)
|
61
|
+
app=self._app, keys=self._keys, maleo_foundation=self._maleo_foundation
|
62
|
+
)
|
@@ -1,4 +1,3 @@
|
|
1
|
-
import asyncio
|
2
1
|
from fastapi import FastAPI, APIRouter
|
3
2
|
from fastapi.exceptions import RequestValidationError
|
4
3
|
from google.oauth2.service_account import Credentials
|
@@ -11,13 +10,15 @@ from typing import Optional
|
|
11
10
|
from maleo_foundation.client.manager import MaleoFoundationClientManager
|
12
11
|
from maleo_foundation.enums import BaseEnums
|
13
12
|
from maleo_foundation.models.schemas.general import BaseGeneralSchemas
|
14
|
-
from maleo_foundation.models.transfers.general.token
|
15
|
-
|
16
|
-
|
17
|
-
|
13
|
+
from maleo_foundation.models.transfers.general.token import (
|
14
|
+
MaleoFoundationTokenGeneralTransfers,
|
15
|
+
)
|
16
|
+
from maleo_foundation.models.transfers.parameters.token import (
|
17
|
+
MaleoFoundationTokenParametersTransfers,
|
18
|
+
)
|
18
19
|
from maleo_foundation.models.transfers.general.configurations import (
|
19
20
|
Configurations,
|
20
|
-
Loggers
|
21
|
+
Loggers,
|
21
22
|
)
|
22
23
|
from maleo_foundation.models.transfers.general.credentials import MaleoCredentials
|
23
24
|
from maleo_foundation.models.transfers.general.settings import Settings
|
@@ -35,36 +36,37 @@ from maleo_foundation.utils.logging import (
|
|
35
36
|
DatabaseLogger,
|
36
37
|
MiddlewareLogger,
|
37
38
|
RepositoryLogger,
|
38
|
-
ServiceLogger
|
39
|
+
ServiceLogger,
|
39
40
|
)
|
40
41
|
from .credential import CredentialManager
|
41
42
|
from .configuration import ConfigurationManager
|
42
43
|
|
44
|
+
|
43
45
|
class ServiceManager:
|
44
46
|
def __init__(
|
45
47
|
self,
|
46
48
|
db_metadata: MetaData,
|
47
49
|
log_config: SimpleConfig,
|
48
|
-
settings: Optional[Settings] = None
|
50
|
+
settings: Optional[Settings] = None,
|
49
51
|
):
|
50
|
-
self._db_metadata = db_metadata
|
51
|
-
self._log_config = log_config
|
52
|
-
self._settings =
|
52
|
+
self._db_metadata = db_metadata # * Declare DB Metadata
|
53
|
+
self._log_config = log_config # * Declare log config
|
54
|
+
self._settings = (
|
55
|
+
settings if settings is not None else Settings()
|
56
|
+
) # * Initialize settings
|
53
57
|
|
54
|
-
|
58
|
+
# * Disable google cloud logging if environment is local
|
55
59
|
if self._settings.ENVIRONMENT == "local":
|
56
60
|
self._log_config.google_cloud_logging = None
|
57
61
|
|
58
|
-
|
62
|
+
# * Initialize Credential Manager
|
59
63
|
self._credential_manager = CredentialManager(
|
60
|
-
settings=self._settings,
|
61
|
-
log_config=self._log_config
|
64
|
+
settings=self._settings, log_config=self._log_config
|
62
65
|
)
|
63
66
|
|
64
|
-
|
67
|
+
# * Initialize Configuration Manager
|
65
68
|
self._configuration_manager = ConfigurationManager(
|
66
|
-
settings=self._settings,
|
67
|
-
credential_manager=self._credential_manager
|
69
|
+
settings=self._settings, credential_manager=self._credential_manager
|
68
70
|
)
|
69
71
|
|
70
72
|
self._load_keys()
|
@@ -113,9 +115,7 @@ class ServiceManager:
|
|
113
115
|
public = self.secret_manager.get(name="maleo-public-key")
|
114
116
|
|
115
117
|
self._keys = BaseGeneralSchemas.RSAKeys(
|
116
|
-
password=password,
|
117
|
-
private=private,
|
118
|
-
public=public
|
118
|
+
password=password, private=private, public=public
|
119
119
|
)
|
120
120
|
|
121
121
|
@property
|
@@ -124,28 +124,22 @@ class ServiceManager:
|
|
124
124
|
|
125
125
|
def _initialize_loggers(self) -> None:
|
126
126
|
application = ApplicationLogger(
|
127
|
-
service_key=self.configurations.service.key,
|
128
|
-
**self._log_config.model_dump()
|
127
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
129
128
|
)
|
130
129
|
cache = CacheLogger(
|
131
|
-
service_key=self.configurations.service.key,
|
132
|
-
**self._log_config.model_dump()
|
130
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
133
131
|
)
|
134
132
|
database = DatabaseLogger(
|
135
|
-
service_key=self.configurations.service.key,
|
136
|
-
**self._log_config.model_dump()
|
133
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
137
134
|
)
|
138
135
|
middleware = MiddlewareLogger(
|
139
|
-
service_key=self.configurations.service.key,
|
140
|
-
**self._log_config.model_dump()
|
136
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
141
137
|
)
|
142
138
|
repository = RepositoryLogger(
|
143
|
-
service_key=self.configurations.service.key,
|
144
|
-
**self._log_config.model_dump()
|
139
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
145
140
|
)
|
146
141
|
service = ServiceLogger(
|
147
|
-
service_key=self.configurations.service.key,
|
148
|
-
**self._log_config.model_dump()
|
142
|
+
service_key=self.configurations.service.key, **self._log_config.model_dump()
|
149
143
|
)
|
150
144
|
self._loggers = Loggers(
|
151
145
|
application=application,
|
@@ -153,7 +147,7 @@ class ServiceManager:
|
|
153
147
|
database=database,
|
154
148
|
middleware=middleware,
|
155
149
|
repository=repository,
|
156
|
-
service=service
|
150
|
+
service=service,
|
157
151
|
)
|
158
152
|
|
159
153
|
@property
|
@@ -163,7 +157,7 @@ class ServiceManager:
|
|
163
157
|
async def _clear_cache(self) -> None:
|
164
158
|
prefixes = [
|
165
159
|
self.configurations.service.key,
|
166
|
-
f"google-cloud-storage:{self.configurations.service.key}"
|
160
|
+
f"google-cloud-storage:{self.configurations.service.key}",
|
167
161
|
]
|
168
162
|
for prefix in prefixes:
|
169
163
|
async for key in self._redis.scan_iter(f"{prefix}*"):
|
@@ -175,7 +169,9 @@ class ServiceManager:
|
|
175
169
|
self._loggers.cache.info("Redis connection check successful.")
|
176
170
|
return True
|
177
171
|
except RedisError as e:
|
178
|
-
self._loggers.cache.error(
|
172
|
+
self._loggers.cache.error(
|
173
|
+
f"Redis connection check failed: {e}", exc_info=True
|
174
|
+
)
|
179
175
|
return False
|
180
176
|
|
181
177
|
async def initialize_cache(self) -> None:
|
@@ -185,7 +181,7 @@ class ServiceManager:
|
|
185
181
|
db=self.configurations.cache.redis.db,
|
186
182
|
password=self.configurations.cache.redis.password,
|
187
183
|
decode_responses=self.configurations.cache.redis.decode_responses,
|
188
|
-
health_check_interval=self.configurations.cache.redis.health_check_interval
|
184
|
+
health_check_interval=self.configurations.cache.redis.health_check_interval,
|
189
185
|
)
|
190
186
|
await self.check_redis_connection()
|
191
187
|
self._cache = CacheManagers(redis=self._redis)
|
@@ -210,7 +206,7 @@ class ServiceManager:
|
|
210
206
|
service_key=self._settings.SERVICE_KEY,
|
211
207
|
bucket_name=f"maleo-suite-{environment}",
|
212
208
|
credentials=self.google_credentials,
|
213
|
-
redis=self._redis
|
209
|
+
redis=self._redis,
|
214
210
|
)
|
215
211
|
|
216
212
|
@property
|
@@ -221,7 +217,7 @@ class ServiceManager:
|
|
221
217
|
self._database = DatabaseManager(
|
222
218
|
metadata=self._db_metadata,
|
223
219
|
logger=self._loggers.database,
|
224
|
-
url=self.configurations.database.url
|
220
|
+
url=self.configurations.database.url,
|
225
221
|
)
|
226
222
|
|
227
223
|
@property
|
@@ -230,8 +226,7 @@ class ServiceManager:
|
|
230
226
|
|
231
227
|
def _initialize_foundation(self) -> None:
|
232
228
|
self._foundation = MaleoFoundationClientManager(
|
233
|
-
log_config=self._log_config,
|
234
|
-
service_key=self._settings.SERVICE_KEY
|
229
|
+
log_config=self._log_config, service_key=self._settings.SERVICE_KEY
|
235
230
|
)
|
236
231
|
|
237
232
|
@property
|
@@ -249,12 +244,10 @@ class ServiceManager:
|
|
249
244
|
u_u=self.maleo_credentials.username,
|
250
245
|
u_e=self.maleo_credentials.email,
|
251
246
|
u_ut="service",
|
252
|
-
exp_in=1
|
247
|
+
exp_in=1,
|
253
248
|
)
|
254
249
|
parameters = MaleoFoundationTokenParametersTransfers.Encode(
|
255
|
-
key=self._keys.private,
|
256
|
-
password=self._keys.password,
|
257
|
-
payload=payload
|
250
|
+
key=self._keys.private, password=self._keys.password, payload=payload
|
258
251
|
)
|
259
252
|
result = self._foundation.services.token.encode(parameters=parameters)
|
260
253
|
return result.data.token if result.success else None
|
@@ -263,7 +256,7 @@ class ServiceManager:
|
|
263
256
|
self,
|
264
257
|
router: APIRouter,
|
265
258
|
lifespan: Optional[Lifespan[AppType]] = None,
|
266
|
-
version: str = "unknown"
|
259
|
+
version: str = "unknown",
|
267
260
|
) -> FastAPI:
|
268
261
|
self._loggers.application.info("Creating FastAPI application")
|
269
262
|
root_path = self._settings.ROOT_PATH
|
@@ -271,35 +264,35 @@ class ServiceManager:
|
|
271
264
|
title=self.configurations.service.name,
|
272
265
|
version=version,
|
273
266
|
lifespan=lifespan,
|
274
|
-
root_path=root_path
|
267
|
+
root_path=root_path,
|
275
268
|
)
|
276
269
|
self._loggers.application.info("FastAPI application created successfully")
|
277
270
|
|
278
|
-
|
271
|
+
# * Add middleware(s)
|
279
272
|
self._loggers.application.info("Configuring middlewares")
|
280
273
|
self._middleware = MiddlewareManager(
|
281
274
|
app=self._app,
|
282
275
|
configurations=self.configurations.middleware,
|
283
276
|
keys=self._keys,
|
284
277
|
logger=self._loggers.middleware,
|
285
|
-
maleo_foundation=self._foundation
|
278
|
+
maleo_foundation=self._foundation,
|
286
279
|
)
|
287
280
|
self._middleware.add_all()
|
288
281
|
self._loggers.application.info("Middlewares added successfully")
|
289
282
|
|
290
|
-
|
283
|
+
# * Add exception handler(s)
|
291
284
|
self._loggers.application.info("Adding exception handlers")
|
292
285
|
self._app.add_exception_handler(
|
293
286
|
exc_class_or_status_code=RequestValidationError,
|
294
|
-
handler=BaseExceptions.validation_exception_handler
|
287
|
+
handler=BaseExceptions.validation_exception_handler,
|
295
288
|
)
|
296
289
|
self._app.add_exception_handler(
|
297
290
|
exc_class_or_status_code=HTTPException,
|
298
|
-
handler=BaseExceptions.http_exception_handler
|
291
|
+
handler=BaseExceptions.http_exception_handler,
|
299
292
|
)
|
300
293
|
self._loggers.application.info("Exception handlers added successfully")
|
301
294
|
|
302
|
-
|
295
|
+
# * Include router
|
303
296
|
self._loggers.application.info("Including routers")
|
304
297
|
self._app.include_router(router)
|
305
298
|
self._loggers.application.info("Routers included successfully")
|
@@ -326,4 +319,4 @@ class ServiceManager:
|
|
326
319
|
self._loggers.database.dispose()
|
327
320
|
self._loggers.middleware.info("Disposing logger")
|
328
321
|
self._loggers.middleware.dispose()
|
329
|
-
self._loggers = None
|
322
|
+
self._loggers = None
|