nui-lambda-shared-utils 1.0.0__tar.gz

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.
Files changed (39) hide show
  1. nui_lambda_shared_utils-1.0.0/LICENSE +21 -0
  2. nui_lambda_shared_utils-1.0.0/MANIFEST.in +37 -0
  3. nui_lambda_shared_utils-1.0.0/PKG-INFO +401 -0
  4. nui_lambda_shared_utils-1.0.0/README.md +341 -0
  5. nui_lambda_shared_utils-1.0.0/docs/README.md +115 -0
  6. nui_lambda_shared_utils-1.0.0/docs/configuration.md +324 -0
  7. nui_lambda_shared_utils-1.0.0/docs/index.md +64 -0
  8. nui_lambda_shared_utils-1.0.0/docs/installation.md +244 -0
  9. nui_lambda_shared_utils-1.0.0/docs/quickstart.md +275 -0
  10. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/__init__.py +177 -0
  11. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/cloudwatch_metrics.py +367 -0
  12. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/config.py +127 -0
  13. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/db_client.py +521 -0
  14. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/error_handler.py +372 -0
  15. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/es_client.py +153 -0
  16. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/es_query_builder.py +315 -0
  17. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/secrets_helper.py +187 -0
  18. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_client.py +413 -0
  19. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_formatter.py +325 -0
  20. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_setup/__init__.py +14 -0
  21. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_setup/channel_creator.py +295 -0
  22. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_setup/channel_definitions.py +187 -0
  23. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_setup/setup_helpers.py +211 -0
  24. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/slack_setup_cli.py +194 -0
  25. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils/timezone.py +117 -0
  26. nui_lambda_shared_utils-1.0.0/nui_lambda_shared_utils.egg-info/SOURCES.txt +36 -0
  27. nui_lambda_shared_utils-1.0.0/pyproject.toml +123 -0
  28. nui_lambda_shared_utils-1.0.0/setup.cfg +4 -0
  29. nui_lambda_shared_utils-1.0.0/setup.py +76 -0
  30. nui_lambda_shared_utils-1.0.0/tests/__init__.py +3 -0
  31. nui_lambda_shared_utils-1.0.0/tests/test_cloudwatch_metrics.py +557 -0
  32. nui_lambda_shared_utils-1.0.0/tests/test_db_client.py +652 -0
  33. nui_lambda_shared_utils-1.0.0/tests/test_error_handler.py +404 -0
  34. nui_lambda_shared_utils-1.0.0/tests/test_es_client.py +306 -0
  35. nui_lambda_shared_utils-1.0.0/tests/test_es_query_builder.py +723 -0
  36. nui_lambda_shared_utils-1.0.0/tests/test_secrets_helper.py +326 -0
  37. nui_lambda_shared_utils-1.0.0/tests/test_slack_client.py +633 -0
  38. nui_lambda_shared_utils-1.0.0/tests/test_slack_formatter.py +575 -0
  39. nui_lambda_shared_utils-1.0.0/tests/test_timezone.py +150 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 NUI Markets Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,37 @@
1
+ # Include the license and readme
2
+ include LICENSE
3
+ include README.md
4
+ include CHANGELOG.md
5
+
6
+ # Include package data
7
+ recursive-include nui_lambda_shared_utils *.py
8
+ recursive-include nui_lambda_shared_utils/slack_setup *.yaml
9
+
10
+ # Exclude development and build files
11
+ exclude .gitignore
12
+ exclude .github
13
+ recursive-exclude * __pycache__
14
+ recursive-exclude * *.py[co]
15
+ recursive-exclude * *.so
16
+ recursive-exclude * *.dylib
17
+ exclude .coverage
18
+ exclude htmlcov
19
+ recursive-exclude htmlcov *
20
+ exclude .pytest_cache
21
+ recursive-exclude .pytest_cache *
22
+ exclude .mypy_cache
23
+ recursive-exclude .mypy_cache *
24
+ exclude build
25
+ recursive-exclude build *
26
+ exclude dist
27
+ recursive-exclude dist *
28
+ exclude *.egg-info
29
+ recursive-exclude *.egg-info *
30
+
31
+ # Include tests for source distributions
32
+ recursive-include tests *.py
33
+ exclude tests/conftest.py
34
+
35
+ # Documentation
36
+ include docs/*.md
37
+ recursive-exclude docs/_build *
@@ -0,0 +1,401 @@
1
+ Metadata-Version: 2.4
2
+ Name: nui-lambda-shared-utils
3
+ Version: 1.0.0
4
+ Summary: Enterprise-grade utilities for AWS Lambda functions with Slack, Elasticsearch, and monitoring integrations
5
+ Home-page: https://github.com/nuimarkets/nui-lambda-shared-utils
6
+ Author: NUI Markets
7
+ Author-email: NUI Markets <develop@nuimarkets.com>
8
+ Project-URL: Homepage, https://github.com/nuimarkets/nui-lambda-shared-utils
9
+ Project-URL: Bug Tracker, https://github.com/nuimarkets/nui-lambda-shared-utils/issues
10
+ Project-URL: Documentation, https://github.com/nuimarkets/nui-lambda-shared-utils/blob/main/README.md
11
+ Project-URL: Source, https://github.com/nuimarkets/nui-lambda-shared-utils
12
+ Keywords: aws,lambda,utilities,slack,elasticsearch,monitoring,serverless
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: System :: Monitoring
24
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
25
+ Classifier: Environment :: Console
26
+ Classifier: Framework :: AWS CDK
27
+ Requires-Python: >=3.9
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: boto3>=1.20.0
31
+ Requires-Dist: pytz>=2021.3
32
+ Requires-Dist: click>=8.0.0
33
+ Requires-Dist: pyyaml>=6.0
34
+ Provides-Extra: elasticsearch
35
+ Requires-Dist: elasticsearch<8.0.0,>=7.17.0; extra == "elasticsearch"
36
+ Provides-Extra: database
37
+ Requires-Dist: pymysql>=1.0.0; extra == "database"
38
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "database"
39
+ Provides-Extra: slack
40
+ Requires-Dist: slack-sdk>=3.19.0; extra == "slack"
41
+ Provides-Extra: all
42
+ Requires-Dist: elasticsearch<8.0.0,>=7.17.0; extra == "all"
43
+ Requires-Dist: pymysql>=1.0.0; extra == "all"
44
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "all"
45
+ Requires-Dist: slack-sdk>=3.19.0; extra == "all"
46
+ Provides-Extra: dev
47
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
48
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
49
+ Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
50
+ Requires-Dist: moto>=4.0.0; extra == "dev"
51
+ Requires-Dist: black>=22.0.0; extra == "dev"
52
+ Requires-Dist: mypy>=0.990; extra == "dev"
53
+ Requires-Dist: boto3-stubs[essential]>=1.20.0; extra == "dev"
54
+ Requires-Dist: twine>=4.0.0; extra == "dev"
55
+ Requires-Dist: build>=0.8.0; extra == "dev"
56
+ Dynamic: author
57
+ Dynamic: home-page
58
+ Dynamic: license-file
59
+ Dynamic: requires-python
60
+
61
+ # NUI Lambda Shared Utilities
62
+
63
+ [![PyPI version](https://badge.fury.io/py/nui-lambda-shared-utils.svg)](https://badge.fury.io/py/nui-lambda-shared-utils)
64
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
65
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
66
+
67
+ Enterprise-grade utilities for AWS Lambda functions with Slack, Elasticsearch, and monitoring integrations. This package provides standardized, production-ready patterns for common serverless operations while maintaining flexibility and configurability.
68
+
69
+ ## Key Features
70
+
71
+ - **AWS Secrets Manager Integration** - Secure credential management with caching
72
+ - **Slack Messaging** - Rich formatting, threading, file uploads, and channel management
73
+ - **Elasticsearch Operations** - Query builders, index management, and health monitoring
74
+ - **Database Connections** - Connection pooling, automatic retries, and transaction management
75
+ - **CloudWatch Metrics** - Batched publishing with custom dimensions
76
+ - **Error Handling** - Intelligent retry patterns with exponential backoff
77
+ - **Timezone Utilities** - Timezone handling and formatting
78
+ - **Configurable Defaults** - Environment-aware configuration system
79
+
80
+ ## Quick Start
81
+
82
+ ### Installation
83
+
84
+ ```bash
85
+ pip install nui-lambda-shared-utils
86
+
87
+ # With specific extras for optional dependencies
88
+ pip install nui-lambda-shared-utils[all] # All integrations
89
+ pip install nui-lambda-shared-utils[slack] # Slack only
90
+ pip install nui-lambda-shared-utils[elasticsearch] # Elasticsearch only
91
+ pip install nui-lambda-shared-utils[database] # Database only
92
+ ```
93
+
94
+ ### Basic Configuration
95
+
96
+ ```python
97
+ import nui_lambda_shared_utils as nui
98
+
99
+ # Configure for your environment (optional - uses sensible defaults)
100
+ nui.configure(
101
+ es_host="your-elasticsearch-host:9200",
102
+ es_credentials_secret="your-es-secret-name",
103
+ slack_credentials_secret="your-slack-secret-name",
104
+ db_credentials_secret="your-database-secret-name"
105
+ )
106
+
107
+ # Or use environment variables:
108
+ # ES_HOST, ES_CREDENTIALS_SECRET, SLACK_CREDENTIALS_SECRET, etc.
109
+ ```
110
+
111
+ ## Usage Examples
112
+
113
+ ### Secrets Management
114
+
115
+ ```python
116
+ from nui_lambda_shared_utils import get_secret, get_slack_credentials, get_database_credentials
117
+
118
+ # Generic secret retrieval
119
+ api_keys = get_secret("my-service/api-keys")
120
+
121
+ # Specialized getters with normalized field names
122
+ slack_creds = get_slack_credentials() # Uses configured secret name
123
+ db_creds = get_database_credentials() # Standardized: host, port, username, password, database
124
+ ```
125
+
126
+ ### Slack Integration
127
+
128
+ ```python
129
+ from nui_lambda_shared_utils import SlackClient, SlackBlockBuilder
130
+
131
+ # Initialize client
132
+ slack = SlackClient()
133
+
134
+ # Simple message
135
+ response = slack.send_message(
136
+ channel='#alerts',
137
+ text='Service deployment complete'
138
+ )
139
+
140
+ # Rich formatted message with blocks
141
+ builder = SlackBlockBuilder()
142
+ blocks = (builder
143
+ .add_header("Production Alert", emoji="warning")
144
+ .add_section("Error Rate", "15.2% (above 10% threshold)")
145
+ .add_section("Time Range", "Last 10 minutes")
146
+ .add_divider()
147
+ .add_context("Alert ID: PROD-2025-001")
148
+ .build()
149
+ )
150
+
151
+ slack.send_message(channel='#incidents', blocks=blocks)
152
+
153
+ # File upload
154
+ slack.send_file(
155
+ channel='#reports',
156
+ content='Daily metrics...',
157
+ filename='metrics-2025-01-05.csv',
158
+ title='Daily Metrics Report'
159
+ )
160
+
161
+ # Thread reply
162
+ slack.reply_to_thread(
163
+ channel='#incidents',
164
+ thread_ts='1735689600.123',
165
+ text='Issue resolved!'
166
+ )
167
+ ```
168
+
169
+ ### Elasticsearch Operations
170
+
171
+ ```python
172
+ from nui_lambda_shared_utils import ElasticsearchClient, ESQueryBuilder
173
+
174
+ # Initialize client
175
+ es = ElasticsearchClient()
176
+
177
+ # Query builder for complex searches
178
+ query_builder = ESQueryBuilder()
179
+ query = (query_builder
180
+ .date_range("@timestamp", "now-1h", "now")
181
+ .term("level", "ERROR")
182
+ .wildcard("message", "*timeout*")
183
+ .build()
184
+ )
185
+
186
+ results = es.search(index="logs-*", body={"query": query})
187
+
188
+ # Built-in query helpers
189
+ error_stats = es.get_error_stats(
190
+ index="application-logs",
191
+ time_range="1h",
192
+ service_filter="payment-service"
193
+ )
194
+ ```
195
+
196
+ ### Database Connections
197
+
198
+ ```python
199
+ from nui_lambda_shared_utils import DatabaseClient
200
+
201
+ # Initialize with connection pooling
202
+ db = DatabaseClient()
203
+
204
+ # Execute queries with automatic retry
205
+ async with db.get_connection() as conn:
206
+ results = await conn.execute(
207
+ "SELECT * FROM orders WHERE created_at > %s",
208
+ [datetime.now() - timedelta(hours=1)]
209
+ )
210
+
211
+ # Bulk operations
212
+ records = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
213
+ db.bulk_insert("items", records)
214
+ ```
215
+
216
+ ### CloudWatch Metrics
217
+
218
+ ```python
219
+ from nui_lambda_shared_utils import MetricsPublisher, StandardMetrics
220
+
221
+ # Initialize publisher
222
+ metrics = MetricsPublisher(namespace="MyApplication")
223
+
224
+ # Individual metrics
225
+ metrics.put_metric("ProcessedItems", 150, "Count")
226
+ metrics.put_metric("ResponseTime", 245.5, "Milliseconds")
227
+
228
+ # Batch publishing (more efficient)
229
+ metrics.batch_publish([
230
+ StandardMetrics.count("Errors", 3),
231
+ StandardMetrics.duration("ProcessingTime", 1.2),
232
+ StandardMetrics.gauge("QueueSize", 45)
233
+ ])
234
+
235
+ # Decorator for Lambda performance tracking
236
+ @track_lambda_performance(metrics)
237
+ def lambda_handler(event, context):
238
+ # Your Lambda logic here
239
+ return {"statusCode": 200}
240
+ ```
241
+
242
+ ### Error Handling
243
+
244
+ ```python
245
+ from nui_lambda_shared_utils import with_retry, retry_on_network_error, handle_lambda_error
246
+
247
+ # Automatic retry with exponential backoff
248
+ @retry_on_network_error
249
+ def call_external_api():
250
+ response = requests.get("https://api.external-service.com/data")
251
+ return response.json()
252
+
253
+ # Custom retry configuration
254
+ @with_retry(max_attempts=5, initial_delay=2.0)
255
+ def critical_operation():
256
+ # Operation that might fail
257
+ return perform_critical_task()
258
+
259
+ # Lambda error handling wrapper
260
+ @handle_lambda_error
261
+ def lambda_handler(event, context):
262
+ # Your Lambda logic here
263
+ return {"statusCode": 200, "body": "Success"}
264
+ ```
265
+
266
+ ## Configuration
267
+
268
+ The package supports multiple configuration methods:
269
+
270
+ ### Environment Variables
271
+
272
+ ```bash
273
+ # Core settings
274
+ ES_HOST=localhost:9200 # Elasticsearch host
275
+ ES_CREDENTIALS_SECRET=elasticsearch-creds # AWS secret name for ES credentials
276
+ DB_CREDENTIALS_SECRET=database-creds # AWS secret name for DB credentials
277
+ SLACK_CREDENTIALS_SECRET=slack-bot-token # AWS secret name for Slack token
278
+
279
+ # AWS settings
280
+ AWS_REGION=us-east-1 # AWS region for services
281
+ ```
282
+
283
+ ### Programmatic Configuration
284
+
285
+ ```python
286
+ import nui_lambda_shared_utils as nui
287
+
288
+ # Configure all at once
289
+ config = nui.Config(
290
+ es_host="prod-elastic:9200",
291
+ es_credentials_secret="prod/elasticsearch",
292
+ db_credentials_secret="prod/database",
293
+ slack_credentials_secret="prod/slack",
294
+ aws_region="us-west-2"
295
+ )
296
+ nui.set_config(config)
297
+
298
+ # Or configure specific settings
299
+ nui.configure(
300
+ es_host="localhost:9200",
301
+ slack_credentials_secret="dev/slack-token"
302
+ )
303
+ ```
304
+
305
+ ## AWS Infrastructure Requirements
306
+
307
+ This package expects certain AWS resources to be available:
308
+
309
+ ### Secrets Manager
310
+
311
+ Create secrets with these structures:
312
+
313
+ ```json
314
+ // Elasticsearch credentials
315
+ {
316
+ "host": "your-elasticsearch-host:9200",
317
+ "username": "elastic",
318
+ "password": "your-password"
319
+ }
320
+
321
+ // Database credentials
322
+ {
323
+ "host": "your-db-host",
324
+ "port": 3306,
325
+ "username": "dbuser",
326
+ "password": "dbpassword",
327
+ "database": "your_database"
328
+ }
329
+
330
+ // Slack credentials
331
+ {
332
+ "bot_token": "xoxb-your-slack-bot-token",
333
+ "webhook_url": "https://hooks.slack.com/..." // optional
334
+ }
335
+ ```
336
+
337
+ ### IAM Permissions
338
+
339
+ Your Lambda execution role needs:
340
+
341
+ ```json
342
+ {
343
+ "Version": "2012-10-17",
344
+ "Statement": [
345
+ {
346
+ "Effect": "Allow",
347
+ "Action": [
348
+ "secretsmanager:GetSecretValue"
349
+ ],
350
+ "Resource": "arn:aws:secretsmanager:*:*:secret:your-secret-*"
351
+ },
352
+ {
353
+ "Effect": "Allow",
354
+ "Action": [
355
+ "cloudwatch:PutMetricData"
356
+ ],
357
+ "Resource": "*"
358
+ }
359
+ ]
360
+ }
361
+ ```
362
+
363
+ ## Testing
364
+
365
+ ```bash
366
+ # Install with dev dependencies
367
+ pip install nui-lambda-shared-utils[dev]
368
+
369
+ # Run tests
370
+ pytest
371
+
372
+ # Run tests with coverage
373
+ pytest --cov=nui_lambda_shared_utils --cov-report=html
374
+
375
+ # Run specific test categories
376
+ pytest -m unit # Unit tests only
377
+ pytest -m integration # Integration tests (requires AWS access)
378
+ ```
379
+
380
+ ## Contributing
381
+
382
+ 1. Fork the repository
383
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
384
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
385
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
386
+ 5. Open a Pull Request
387
+
388
+ ## Documentation & Support
389
+
390
+ - **GitHub Repository**: https://github.com/nuimarkets/nui-lambda-shared-utils
391
+ - **Issue Tracker**: https://github.com/nuimarkets/nui-lambda-shared-utils/issues
392
+ - **PyPI Package**: https://pypi.org/project/nui-lambda-shared-utils/
393
+
394
+ ## License
395
+
396
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
397
+
398
+ ## About NUI Markets
399
+
400
+ NUI Markets is a technology company focused on building innovative trading and marketplace platforms. This package represents our commitment to open-source tooling and enterprise-grade infrastructure patterns.
401
+