platform-ext-utils 0.0.1__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.
- platform_ext_utils-0.0.1.dist-info/METADATA +130 -0
- platform_ext_utils-0.0.1.dist-info/RECORD +10 -0
- platform_ext_utils-0.0.1.dist-info/WHEEL +5 -0
- platform_ext_utils-0.0.1.dist-info/licenses/LICENSE +178 -0
- platform_ext_utils-0.0.1.dist-info/top_level.txt +1 -0
- py_utils/__init__.py +68 -0
- py_utils/extern_connect.py +64 -0
- py_utils/kafka_service.py +100 -0
- py_utils/utils/envs.py +102 -0
- py_utils/utils/logger.py +22 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: platform-ext-utils
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Shared utility library for Cloudscaile extension features, providing Kafka integration and utilities
|
|
5
|
+
Author: Cloudscaile Engineering
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Keywords: cloudscaile,kafka,extensions,utilities
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: confluent-kafka>=2.4
|
|
17
|
+
Requires-Dist: pydantic>=2.0
|
|
18
|
+
Requires-Dist: pydantic-settings>=2.0
|
|
19
|
+
Requires-Dist: httpx>=0.25
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# platform-ext-utils
|
|
23
|
+
|
|
24
|
+
Shared utility library for Cloudscaile extension features, providing Kafka integration, environment configuration management, and external connectivity utilities.
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- **Kafka Service**: Simplified Kafka producer and consumer interface with Sasl support
|
|
29
|
+
- **Environment Management**: Centralized configuration via environment variables
|
|
30
|
+
- **Logger**: Pre-configured logging for consistent application logs
|
|
31
|
+
- **External Connectivity**: Internal HTTP client instances for inter-service communication
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install platform-ext-utils
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Requirements
|
|
40
|
+
|
|
41
|
+
- Python >= 3.9
|
|
42
|
+
- confluent-kafka >= 2.4
|
|
43
|
+
- pydantic >= 2.0
|
|
44
|
+
- pydantic-settings >= 2.0
|
|
45
|
+
- httpx >= 0.25
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
All configuration is done via environment variables:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# Kafka Configuration
|
|
53
|
+
KAFKA_REQUIRED=
|
|
54
|
+
KAFKA_CLIENT_ID=
|
|
55
|
+
KAFKA_BROKERS=
|
|
56
|
+
KAFKA_GROUP_ID=
|
|
57
|
+
KAFKA_CONSUMER_TOPIC=
|
|
58
|
+
KAFKA_PRODUCER_TOPIC=
|
|
59
|
+
|
|
60
|
+
# Optional: Kafka SASL Authentication
|
|
61
|
+
KAFKA_SASL=
|
|
62
|
+
KAFKA_SASL_USERNAME=
|
|
63
|
+
KAFKA_SASL_PASSWORD=
|
|
64
|
+
|
|
65
|
+
# Tenant Configuration
|
|
66
|
+
TENANT_NAME=
|
|
67
|
+
EXTENSION_NAME=
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Usage
|
|
71
|
+
|
|
72
|
+
### Producing Messages
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from py_utils import produce_message
|
|
76
|
+
|
|
77
|
+
produce_message(
|
|
78
|
+
{"event": "user_created", "userId": "123"},
|
|
79
|
+
topic="user-events"
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Consuming Messages
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from py_utils import kafka_service
|
|
87
|
+
|
|
88
|
+
def handle_message(event):
|
|
89
|
+
print("Received:", event)
|
|
90
|
+
|
|
91
|
+
if kafka_service:
|
|
92
|
+
kafka_service.consume(callback=handle_message)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The callback receives:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
{
|
|
99
|
+
"queueName": "<topic>",
|
|
100
|
+
"partition": 0,
|
|
101
|
+
"offset": 42,
|
|
102
|
+
"message": "<decoded string>",
|
|
103
|
+
"timestamp": (<type>, <value>)
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Using Logger
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from py_utils.utils.logger import logger
|
|
111
|
+
|
|
112
|
+
logger.info("Application started")
|
|
113
|
+
logger.error("An error occurred")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### External Connectivity
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from py_utils import internal_axios_instances
|
|
120
|
+
|
|
121
|
+
# Use pre-configured HTTP clients for inter-service communication
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## License
|
|
125
|
+
|
|
126
|
+
Apache License 2.0
|
|
127
|
+
|
|
128
|
+
## Author
|
|
129
|
+
|
|
130
|
+
Cloudscaile Engineering
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
platform_ext_utils-0.0.1.dist-info/licenses/LICENSE,sha256=y-NeOiY4Zrc6za4xKqeCyrfFhaVXYvTbvjsPq7xheyo,9803
|
|
2
|
+
py_utils/__init__.py,sha256=1tOnIHzAdCTHfE1Vp6OV-y6PCYWHHceyOTJg96VBYP8,1984
|
|
3
|
+
py_utils/extern_connect.py,sha256=pf8PXMSFddrUboEAsah7kXiUXyNqgpj0JOH7zapRslg,1464
|
|
4
|
+
py_utils/kafka_service.py,sha256=sys_Kx5UmjTzIN-PlYAOIOx4SEEodThNq2Us2GfVuuI,3298
|
|
5
|
+
py_utils/utils/envs.py,sha256=pZYZ4tt7e8Le-7yAl8fXzv-B1ovBgnzBK-f68Vad4no,3703
|
|
6
|
+
py_utils/utils/logger.py,sha256=VyRxKs8i3Qq5RKgUqmwH5CnsXB5FeE4PZvAmkCWfzFo,429
|
|
7
|
+
platform_ext_utils-0.0.1.dist-info/METADATA,sha256=kPlpPsBnuW4jlwW5zRgeEhcOnQUUu_Bef61XbJVAtBU,2751
|
|
8
|
+
platform_ext_utils-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
9
|
+
platform_ext_utils-0.0.1.dist-info/top_level.txt,sha256=TurY9TdpPVhVAzKr6GXCR9fBn3fQ6SC0QdC7IEyDWeo,9
|
|
10
|
+
platform_ext_utils-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2026 Cloudscaile
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined in Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
26
|
+
permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or Object
|
|
38
|
+
form, made available under the License, as indicated by a copyright
|
|
39
|
+
notice that is included in or attached to the work (an example is
|
|
40
|
+
provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original Work and any Derivative Works thereof, submitted to,
|
|
52
|
+
or received by, Licensor and intentionally submitted for inclusion
|
|
53
|
+
in, the Work by the copyright owner or by an individual or Legal
|
|
54
|
+
Entity authorized to submit on behalf of the copyright owner. For the
|
|
55
|
+
purposes of this definition, "submitted" means any form of electronic,
|
|
56
|
+
verbal, or written communication sent to the Licensor or its
|
|
57
|
+
representatives, including but not limited to communication on
|
|
58
|
+
electronic mailing lists, source code control systems, and issue
|
|
59
|
+
tracking systems that are managed by, or on behalf of, the Licensor
|
|
60
|
+
for the purpose of discussing and improving the Work, but excluding
|
|
61
|
+
communication that is conspicuously marked or otherwise designated
|
|
62
|
+
in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
65
|
+
whom a Contribution has been received by Licensor and subsequently
|
|
66
|
+
incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file, then any
|
|
109
|
+
Derivative Works that You distribute must include a readable
|
|
110
|
+
copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE from the Work, provided that
|
|
122
|
+
such additional attribution notices cannot be construed as
|
|
123
|
+
modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions of this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contribution.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
py_utils
|
py_utils/__init__.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 CloudScaile
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0
|
|
5
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import atexit
|
|
10
|
+
from .utils.logger import logger
|
|
11
|
+
from .utils.envs import envs as _envs # internal use only
|
|
12
|
+
from .kafka_service import KafkaService
|
|
13
|
+
from .extern_connect import internal_axios_instances
|
|
14
|
+
|
|
15
|
+
kafka_service = None
|
|
16
|
+
|
|
17
|
+
# Initialize KafkaService only if required
|
|
18
|
+
if _envs.KAFKA_REQUIRED:
|
|
19
|
+
try:
|
|
20
|
+
kafka_service = KafkaService(
|
|
21
|
+
client_id=_envs.KAFKA_CLIENT_ID,
|
|
22
|
+
brokers=_envs.KAFKA_BROKERS.split(","),
|
|
23
|
+
consumer_topic=_envs.KAFKA_CONSUMER_TOPIC,
|
|
24
|
+
group_id=_envs.KAFKA_GROUP_ID,
|
|
25
|
+
producer_topic=_envs.KAFKA_PRODUCER_TOPIC,
|
|
26
|
+
)
|
|
27
|
+
logger.info("✅ KafkaService initialized successfully")
|
|
28
|
+
except Exception as e:
|
|
29
|
+
logger.error(f"❌ Failed to initialize KafkaService: {e}")
|
|
30
|
+
kafka_service = None
|
|
31
|
+
else:
|
|
32
|
+
logger.info("ℹ️ KafkaService not required as per configuration")
|
|
33
|
+
|
|
34
|
+
def produce_message(message, topic=None):
|
|
35
|
+
if kafka_service is None:
|
|
36
|
+
logger.warning("⚠️ Kafka disabled. Skipping produce_message()")
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
kafka_service.send_message(message, topic)
|
|
41
|
+
except Exception as e:
|
|
42
|
+
logger.error(f"❌ Failed to send Kafka message: {e}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def consume_messages(callback):
|
|
46
|
+
if kafka_service is None:
|
|
47
|
+
logger.warning("⚠️ Kafka disabled. Skipping consume_messages()")
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
kafka_service.consume_messages(callback)
|
|
52
|
+
except Exception as e:
|
|
53
|
+
logger.error(f"❌ Kafka consumer stopped unexpectedly: {e}")
|
|
54
|
+
|
|
55
|
+
@atexit.register
|
|
56
|
+
def shutdown():
|
|
57
|
+
if kafka_service:
|
|
58
|
+
try:
|
|
59
|
+
kafka_service.disconnect()
|
|
60
|
+
logger.info("🛑 KafkaService disconnected cleanly")
|
|
61
|
+
except Exception as e:
|
|
62
|
+
logger.error(f"❌ Error during Kafka shutdown: {e}")
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"produce_message",
|
|
66
|
+
"consume_messages",
|
|
67
|
+
"internal_axios_instances"
|
|
68
|
+
]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 CloudScaile
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0
|
|
5
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
PLATFORM_URL = os.getenv("PLATFORM_URL")
|
|
13
|
+
|
|
14
|
+
if not PLATFORM_URL:
|
|
15
|
+
raise RuntimeError("PLATFORM_URL env var not set")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _extract_headers(source):
|
|
19
|
+
"""
|
|
20
|
+
Accepts:
|
|
21
|
+
- dict of headers
|
|
22
|
+
- request-like object with `.headers`
|
|
23
|
+
"""
|
|
24
|
+
# Case 1: headers dict
|
|
25
|
+
if isinstance(source, dict):
|
|
26
|
+
return source
|
|
27
|
+
|
|
28
|
+
# Case 2: request-like object
|
|
29
|
+
if hasattr(source, "headers"):
|
|
30
|
+
return dict(source.headers)
|
|
31
|
+
|
|
32
|
+
raise TypeError(
|
|
33
|
+
"internal_axios_instances expects either a headers dict "
|
|
34
|
+
"or an object with a `.headers` attribute"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def internal_axios_instances(source):
|
|
39
|
+
incoming = _extract_headers(source)
|
|
40
|
+
|
|
41
|
+
forward_headers = {}
|
|
42
|
+
|
|
43
|
+
# Authorization — required
|
|
44
|
+
auth = incoming.get("authorization")
|
|
45
|
+
if not auth:
|
|
46
|
+
raise RuntimeError("Authorization header missing in request")
|
|
47
|
+
|
|
48
|
+
forward_headers["Authorization"] = auth
|
|
49
|
+
|
|
50
|
+
# user-agent — optional but common
|
|
51
|
+
ua = incoming.get("user-agent")
|
|
52
|
+
if ua:
|
|
53
|
+
forward_headers["user-agent"] = ua
|
|
54
|
+
|
|
55
|
+
# x-tenant-id — optional (not implemented yet)
|
|
56
|
+
tenant = incoming.get("x-tenant-id")
|
|
57
|
+
if tenant:
|
|
58
|
+
forward_headers["x-tenant-id"] = tenant
|
|
59
|
+
|
|
60
|
+
return httpx.Client(
|
|
61
|
+
base_url=f"{PLATFORM_URL}/v1/portal",
|
|
62
|
+
headers=forward_headers,
|
|
63
|
+
timeout=10.0,
|
|
64
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 CloudScaile
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0
|
|
5
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from confluent_kafka import Producer, Consumer, KafkaError
|
|
10
|
+
import json
|
|
11
|
+
from .utils.logger import logger
|
|
12
|
+
from .utils.envs import envs
|
|
13
|
+
|
|
14
|
+
class KafkaService:
|
|
15
|
+
def __init__(self, client_id, brokers, consumer_topic, group_id, producer_topic):
|
|
16
|
+
self.producer_topic = producer_topic
|
|
17
|
+
self.consumer_topic = consumer_topic
|
|
18
|
+
self.group_id = group_id
|
|
19
|
+
|
|
20
|
+
# Base config
|
|
21
|
+
base_conf = {
|
|
22
|
+
"bootstrap.servers": brokers,
|
|
23
|
+
"client.id": client_id
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
# Security config
|
|
27
|
+
if envs.KAFKA_SASL:
|
|
28
|
+
sasl_conf = {
|
|
29
|
+
"security.protocol": "SASL_SSL",
|
|
30
|
+
"sasl.mechanism": "SCRAM-SHA-512",
|
|
31
|
+
"sasl.username": envs.KAFKA_SASL_USERNAME,
|
|
32
|
+
"sasl.password": envs.KAFKA_SASL_PASSWORD
|
|
33
|
+
}
|
|
34
|
+
base_conf.update(sasl_conf)
|
|
35
|
+
|
|
36
|
+
# Producer
|
|
37
|
+
self.producer = Producer(base_conf)
|
|
38
|
+
|
|
39
|
+
# Consumer configuration
|
|
40
|
+
consumer_conf = base_conf.copy()
|
|
41
|
+
consumer_conf.update({
|
|
42
|
+
"group.id": group_id,
|
|
43
|
+
"auto.offset.reset": "earliest",
|
|
44
|
+
"enable.auto.commit": False
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
# Create consumer only once
|
|
48
|
+
self.consumer_conf = consumer_conf
|
|
49
|
+
self.consumer = Consumer(consumer_conf)
|
|
50
|
+
|
|
51
|
+
def send_message(self, message: dict, topic: str):
|
|
52
|
+
try:
|
|
53
|
+
tenant_topic = f"{envs.TENANT_NAME}-{envs.EXTENSION_NAME}-{topic}"
|
|
54
|
+
payload = json.dumps({
|
|
55
|
+
"tenantExtensionTopic": tenant_topic,
|
|
56
|
+
"message": message
|
|
57
|
+
})
|
|
58
|
+
self.producer.produce(self.producer_topic, payload.encode("utf-8"))
|
|
59
|
+
self.producer.poll(0)
|
|
60
|
+
except Exception as e:
|
|
61
|
+
logger.error(f"❌ Error sending message: {e}")
|
|
62
|
+
|
|
63
|
+
def consume_messages(self, callback):
|
|
64
|
+
self.consumer.subscribe([self.consumer_topic])
|
|
65
|
+
logger.info(f"🎧 Listening to topic '{self.consumer_topic}' as group '{self.group_id}'")
|
|
66
|
+
try:
|
|
67
|
+
while True:
|
|
68
|
+
msg = self.consumer.poll(timeout=1.0)
|
|
69
|
+
if msg is None:
|
|
70
|
+
continue
|
|
71
|
+
if msg.error():
|
|
72
|
+
if msg.error().code() == KafkaError._PARTITION_EOF:
|
|
73
|
+
continue
|
|
74
|
+
logger.error(msg.error())
|
|
75
|
+
continue
|
|
76
|
+
|
|
77
|
+
message_obj = {
|
|
78
|
+
"queueName": msg.topic(),
|
|
79
|
+
"partition": msg.partition(),
|
|
80
|
+
"offset": msg.offset(),
|
|
81
|
+
"message": msg.value().decode("utf-8"),
|
|
82
|
+
"timestamp": msg.timestamp()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
callback(message_obj)
|
|
87
|
+
except Exception as cb_err:
|
|
88
|
+
logger.error(f"--Consumer error-- {cb_err}")
|
|
89
|
+
|
|
90
|
+
except KeyboardInterrupt:
|
|
91
|
+
logger.info("🛑 Consumer interrupted")
|
|
92
|
+
|
|
93
|
+
finally:
|
|
94
|
+
self.consumer.close()
|
|
95
|
+
logger.info("🔌 Kafka consumer disconnected")
|
|
96
|
+
def disconnect(self):
|
|
97
|
+
self.producer.flush()
|
|
98
|
+
if self.consumer:
|
|
99
|
+
self.consumer.close()
|
|
100
|
+
logger.info("🔌 Kafka connections closed")
|
py_utils/utils/envs.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 CloudScaile
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0
|
|
5
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
11
|
+
from pydantic import Field, field_validator, ValidationError
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Settings(BaseSettings):
|
|
17
|
+
# Base
|
|
18
|
+
PORT: int = Field(default=8000, description="Port for the application")
|
|
19
|
+
PG_DB_REQUIRED: bool = Field(default=False, description="Enable PostgreSQL requirement")
|
|
20
|
+
KAFKA_REQUIRED: bool = Field(default=False, description="Enable Kafka requirement")
|
|
21
|
+
|
|
22
|
+
# PostgreSQL (conditionally required)
|
|
23
|
+
PG_HOST: Optional[str] = None
|
|
24
|
+
PG_PORT: Optional[int] = None
|
|
25
|
+
PG_DB: Optional[str] = None
|
|
26
|
+
PG_USERNAME: Optional[str] = None
|
|
27
|
+
PG_PASSWORD: Optional[str] = None
|
|
28
|
+
|
|
29
|
+
# Kafka (conditionally required)
|
|
30
|
+
KAFKA_BROKERS: Optional[str] = None
|
|
31
|
+
KAFKA_CLIENT_ID: Optional[str] = None
|
|
32
|
+
KAFKA_GROUP_ID: Optional[str] = Field(default="cs-platform-group-ext")
|
|
33
|
+
KAFKA_PRODUCER_TOPIC: Optional[str] = Field(default="cs-platform-producer-topic")
|
|
34
|
+
KAFKA_CONSUMER_TOPIC: Optional[str] = Field(default="cs-platform-consumer-topic")
|
|
35
|
+
KAFKA_SASL: bool = Field(default=False)
|
|
36
|
+
KAFKA_SASL_USERNAME: Optional[str] = None
|
|
37
|
+
KAFKA_SASL_PASSWORD: Optional[str] = None
|
|
38
|
+
|
|
39
|
+
# Common required fields
|
|
40
|
+
TENANT_NAME: str = Field(..., description="Tenant name for the application")
|
|
41
|
+
EXTENSION_NAME: str = Field(..., description="Name of the extension being configured")
|
|
42
|
+
PLATFORM_URL: str = Field(..., description="Base URL for the platform API")
|
|
43
|
+
|
|
44
|
+
model_config = SettingsConfigDict(
|
|
45
|
+
env_file=".env",
|
|
46
|
+
case_sensitive=True,
|
|
47
|
+
extra="ignore" # Ignore unknown env vars like in envalid
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# --- Convert string "None" to None for all optional fields ---
|
|
51
|
+
@field_validator(
|
|
52
|
+
"PG_HOST", "PG_PORT", "PG_DB", "PG_USERNAME", "PG_PASSWORD",
|
|
53
|
+
"KAFKA_BROKERS", "KAFKA_CLIENT_ID", "KAFKA_GROUP_ID",
|
|
54
|
+
"KAFKA_PRODUCER_TOPIC", "KAFKA_CONSUMER_TOPIC",
|
|
55
|
+
"KAFKA_SASL_USERNAME", "KAFKA_SASL_PASSWORD",
|
|
56
|
+
mode="before"
|
|
57
|
+
)
|
|
58
|
+
@classmethod
|
|
59
|
+
def convert_none_str_to_none(cls, v):
|
|
60
|
+
if isinstance(v, str) and v.strip().lower() == "none":
|
|
61
|
+
return None
|
|
62
|
+
return v
|
|
63
|
+
|
|
64
|
+
# --- Conditional Validation ---
|
|
65
|
+
@field_validator("PG_HOST", "PG_PORT", "PG_DB", "PG_USERNAME", "PG_PASSWORD")
|
|
66
|
+
@classmethod
|
|
67
|
+
def require_postgres_if_enabled(cls, v, info):
|
|
68
|
+
if info.data.get("PG_DB_REQUIRED"):
|
|
69
|
+
if v in (None, ""):
|
|
70
|
+
raise ValueError(f"{info.field_name} is required when PG_DB_REQUIRED=True")
|
|
71
|
+
return v
|
|
72
|
+
|
|
73
|
+
@field_validator(
|
|
74
|
+
"KAFKA_BROKERS", "KAFKA_CLIENT_ID", "KAFKA_GROUP_ID",
|
|
75
|
+
"KAFKA_PRODUCER_TOPIC", "KAFKA_CONSUMER_TOPIC",
|
|
76
|
+
"KAFKA_SASL_USERNAME", "KAFKA_SASL_PASSWORD"
|
|
77
|
+
)
|
|
78
|
+
@classmethod
|
|
79
|
+
def require_kafka_if_enabled(cls, v, info):
|
|
80
|
+
if not info.data.get("KAFKA_REQUIRED"):
|
|
81
|
+
return v
|
|
82
|
+
|
|
83
|
+
if info.field_name in ("KAFKA_SASL_USERNAME", "KAFKA_SASL_PASSWORD"):
|
|
84
|
+
if info.data.get("KAFKA_SASL") and v in (None, ""):
|
|
85
|
+
raise ValueError(f"{info.field_name} is required when KAFKA_SASL=True")
|
|
86
|
+
elif v in (None, ""):
|
|
87
|
+
raise ValueError(f"{info.field_name} is required when KAFKA_REQUIRED=True")
|
|
88
|
+
|
|
89
|
+
return v
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# Instantiate and export validated settings
|
|
93
|
+
try:
|
|
94
|
+
envs = Settings()
|
|
95
|
+
# Replicate JS behavior: inject into os.environ
|
|
96
|
+
for key, value in envs.model_dump().items():
|
|
97
|
+
if value is not None:
|
|
98
|
+
os.environ[key] = str(value)
|
|
99
|
+
except ValidationError as e:
|
|
100
|
+
print("❌ Environment validation failed:")
|
|
101
|
+
print(e)
|
|
102
|
+
raise
|
py_utils/utils/logger.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright 2026 CloudScaile
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0
|
|
5
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("app_logger")
|
|
12
|
+
logger.setLevel(logging.INFO)
|
|
13
|
+
|
|
14
|
+
handler = logging.StreamHandler()
|
|
15
|
+
|
|
16
|
+
formatter = logging.Formatter(
|
|
17
|
+
fmt="%(asctime)s | %(levelname)s | %(message)s",
|
|
18
|
+
datefmt="%Y-%m-%d %H:%M:%S"
|
|
19
|
+
)
|
|
20
|
+
handler.setFormatter(formatter)
|
|
21
|
+
|
|
22
|
+
logger.addHandler(handler)
|