filedgr-pkg-utils 0.8.4__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.
- filedgr_pkg_utils-0.8.4/PKG-INFO +171 -0
- filedgr_pkg_utils-0.8.4/README.md +138 -0
- filedgr_pkg_utils-0.8.4/pyproject.toml +64 -0
- filedgr_pkg_utils-0.8.4/setup.cfg +11 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/__init__.py +1 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/caching/__init__.py +1 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/caching/memoize.py +54 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/canonicalization/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/canonicalization/canonical_json_mixin.py +38 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/__init__.py +7 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_brotli.py +31 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_zip.py +45 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_zstd.py +35 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algortihm_gzip.py +34 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/compression_algorithm.py +24 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/compression_utils.py +37 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/converters/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/converters/abstract_converter.py +21 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/hashing/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/hashing/conversion_utils.py +4 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/hashing/hash_algorithm.py +101 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/hashing/hash_utils.py +18 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/__init__.py +6 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/conversion_utils.py +27 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/hmac_signature_algorithm.py +15 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/secp256k1_evm_signature_algorithm.py +20 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/secp256k1_signature_algorithm.py +46 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/signature_algorithm.py +10 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/cryptography/signing/signature_utils.py +31 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/evm/__init__.py +8 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/evm/hex_utils.py +81 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/filesystem/__init__.py +1 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/filesystem/atomic.py +124 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/filesystem/tar_utils.py +50 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/fldgr_logging/__init__.py +1 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/fldgr_logging/sanitizer_logger_adapter.py +22 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/fldgr_logging/structured_logger.py +78 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/hooks/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/hooks/decorators.py +246 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/__init__.py +6 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/algorithms/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_ahash.py +33 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_dhash.py +33 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/algorithms/image_hashing_algorithm_phash.py +33 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/image_hash_algorithm.py +14 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/images/hashing/image_hash_utils.py +31 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/mixins/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/mixins/without_keys_mixin.py +7 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/resilience/__init__.py +5 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/resilience/decorators.py +192 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/security/__init__.py +0 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/security/sanitizer.py +60 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/security/sanitizer_decorators.py +30 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils.egg-info/PKG-INFO +171 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils.egg-info/SOURCES.txt +60 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils.egg-info/dependency_links.txt +1 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils.egg-info/requires.txt +23 -0
- filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: filedgr-pkg-utils
|
|
3
|
+
Version: 0.8.4
|
|
4
|
+
Summary: A library of python based utils needed in the filedgr code stack
|
|
5
|
+
Author-email: Filedgr <code@filedgr.com>
|
|
6
|
+
Project-URL: repository, https://github.com/Filedgr/filedgr-pkg-utils
|
|
7
|
+
Keywords: filedgr,pkg,utils
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: pydantic<3.0.0,>=2.12.5
|
|
14
|
+
Requires-Dist: cryptography<50.0.0,>=49.0.0
|
|
15
|
+
Requires-Dist: orjson<4.0.0,>=3.11.5
|
|
16
|
+
Requires-Dist: web3<8.0.0,>=7.14.0
|
|
17
|
+
Requires-Dist: zstandard<1.0.0,>=0.22.0
|
|
18
|
+
Requires-Dist: Brotli<2.0.0,>=1.1.0
|
|
19
|
+
Requires-Dist: aiofiles<26.0.0,>=25.1.0
|
|
20
|
+
Provides-Extra: build
|
|
21
|
+
Requires-Dist: build; extra == "build"
|
|
22
|
+
Requires-Dist: twine; extra == "build"
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: black; extra == "dev"
|
|
25
|
+
Requires-Dist: bumpver; extra == "dev"
|
|
26
|
+
Requires-Dist: isort; extra == "dev"
|
|
27
|
+
Requires-Dist: mypy; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest; extra == "dev"
|
|
29
|
+
Requires-Dist: flake8; extra == "dev"
|
|
30
|
+
Provides-Extra: images
|
|
31
|
+
Requires-Dist: ImageHash<5.0.0,>=4.3.0; extra == "images"
|
|
32
|
+
Requires-Dist: Pillow<11.0.0,>=10.0.0; extra == "images"
|
|
33
|
+
|
|
34
|
+
# filedgr-pkg-utils
|
|
35
|
+
|
|
36
|
+

|
|
37
|
+

|
|
38
|
+

|
|
39
|
+
[](https://pypi.org/project/filedgr-pkg-utils/)
|
|
40
|
+

|
|
41
|
+
|
|
42
|
+
A comprehensive, production-ready Python utility toolkit for modern distributed systems, Web3 integrations, and data-heavy microservices.
|
|
43
|
+
|
|
44
|
+
`filedgr-pkg-utils` provides a unified, protocol-driven API for cryptography, resilient networking, deterministic data serialization, compression, and structured logging.
|
|
45
|
+
|
|
46
|
+
## 📦 Installation
|
|
47
|
+
|
|
48
|
+
Install the base package (extremely lightweight, ideal for AWS Lambda):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install filedgr-pkg-utils
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Install with optional image perceptual hashing support (includes Pillow and ImageHash):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install "filedgr-pkg-utils[images]"
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 🚀 Prominent Features & Examples
|
|
61
|
+
|
|
62
|
+
### 1. Resilience & Aspect-Oriented Hooks
|
|
63
|
+
|
|
64
|
+
Stop writing try/except blocks with `time.sleep()`. Stack our context-aware decorators to build bulletproof network calls and clean up your business logic.
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from filedgr_pkg_utils.resilience.decorators import retry, circuit_breaker, fallback
|
|
68
|
+
from filedgr_pkg_utils.hooks.post_action import post_action
|
|
69
|
+
|
|
70
|
+
def audit_log(result, *args, **kwargs):
|
|
71
|
+
print(f"Audit: Successfully fetched data {result}")
|
|
72
|
+
|
|
73
|
+
def serve_stale_data(*args, **kwargs):
|
|
74
|
+
return {"status": "stale", "data": []}
|
|
75
|
+
|
|
76
|
+
@post_action(callback=audit_log)
|
|
77
|
+
@fallback(fallback_function=serve_stale_data)
|
|
78
|
+
@circuit_breaker(failure_threshold=5, recovery_timeout_seconds=30)
|
|
79
|
+
@retry(max_attempts=3, backoff_multiplier=2.0)
|
|
80
|
+
async def fetch_web3_data(node_url: str):
|
|
81
|
+
# This function is completely protected.
|
|
82
|
+
# It will retry on failure, trip a circuit breaker if the node is down,
|
|
83
|
+
# serve stale data if all else fails, and log the result when successful.
|
|
84
|
+
pass
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 2. Unified Compression
|
|
88
|
+
|
|
89
|
+
A single, clean protocol for zip, gzip, zstd, and brotli. Easily swap algorithms without changing your application code.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from filedgr_pkg_utils.compression import CompressionUtils, ZstdAlgorithm, ZipAlgorithm
|
|
93
|
+
|
|
94
|
+
# Swap from standard Zip to high-performance Zstd in one line
|
|
95
|
+
utils = CompressionUtils(ZstdAlgorithm(level=3))
|
|
96
|
+
|
|
97
|
+
# Compress bytes
|
|
98
|
+
compressed_data = utils.compress(b"Hello World")
|
|
99
|
+
|
|
100
|
+
# Compress files and directories
|
|
101
|
+
utils.compress_file("data.json", "data.json.zst")
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 3. Canonical Serialization & Cryptography
|
|
105
|
+
|
|
106
|
+
Generate deterministic, whitespace-free, and alphabetically sorted JSON payloads—perfect for creating verifiable hashes and blockchain signatures.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from filedgr_pkg_utils.canonicalization.canonical_json_mixin import CanonicalJsonMixin
|
|
110
|
+
from datetime import datetime, timezone
|
|
111
|
+
|
|
112
|
+
class BlockchainPayload(CanonicalJsonMixin):
|
|
113
|
+
z_field: str
|
|
114
|
+
a_field: int
|
|
115
|
+
timestamp: datetime
|
|
116
|
+
|
|
117
|
+
payload = BlockchainPayload(
|
|
118
|
+
z_field="last",
|
|
119
|
+
a_field=1,
|
|
120
|
+
timestamp=datetime(2023, 10, 25, 12, 30, 0, tzinfo=timezone.utc)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Output is strictly deterministic: {"a_field":1,"timestamp":"2023-10-25T12:30:00.000Z","z_field":"last"}
|
|
124
|
+
json_string = payload.canonical_json()
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### 4. Zero-Config Structured JSON Logging
|
|
128
|
+
|
|
129
|
+
Output logs as deterministic JSON for flawless Datadog or AWS CloudWatch ingestion. Fully integrates with Python's standard logging library.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from filedgr_pkg_utils.logging import LoggerFactory
|
|
133
|
+
|
|
134
|
+
# Automatically reads FILEDGR_LOGGING_ENABLED env var
|
|
135
|
+
logger = LoggerFactory.get_logger(__name__)
|
|
136
|
+
|
|
137
|
+
logger.info("Processing file", extra={"file_id": "ABC-123", "correlation_id": "999"})
|
|
138
|
+
# Output: {"timestamp": "2026-05-14T12:00:00.000Z", "level": "INFO", "logger": "__main__", "message": "Processing file", "file_id": "ABC-123", "correlation_id": "999"}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### 5. Perceptual Image Hashing (Optional)
|
|
142
|
+
|
|
143
|
+
Detect visually similar images, compression artifacts, and resized duplicates using Hamming distance.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from filedgr_pkg_utils.images.hashing import PHashAlgorithm, ImageHashUtils
|
|
147
|
+
|
|
148
|
+
utils = ImageHashUtils(PHashAlgorithm())
|
|
149
|
+
|
|
150
|
+
hash_orig = utils.hash_image("original.png")
|
|
151
|
+
hash_comp = utils.hash_image("compressed_artifact.jpg")
|
|
152
|
+
|
|
153
|
+
if utils.is_similar(hash_orig, hash_comp, max_distance=5):
|
|
154
|
+
print("These images are visually similar!")
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## 🛠️ Development & Testing
|
|
158
|
+
|
|
159
|
+
This project enforces high coverage and clean coding standards.
|
|
160
|
+
|
|
161
|
+
To run the test suite with coverage:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
make test-coverage
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
To run the linter:
|
|
168
|
+
|
|
169
|
+
```bash
|
|
170
|
+
make lint
|
|
171
|
+
```
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# filedgr-pkg-utils
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+

|
|
5
|
+

|
|
6
|
+
[](https://pypi.org/project/filedgr-pkg-utils/)
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
A comprehensive, production-ready Python utility toolkit for modern distributed systems, Web3 integrations, and data-heavy microservices.
|
|
10
|
+
|
|
11
|
+
`filedgr-pkg-utils` provides a unified, protocol-driven API for cryptography, resilient networking, deterministic data serialization, compression, and structured logging.
|
|
12
|
+
|
|
13
|
+
## 📦 Installation
|
|
14
|
+
|
|
15
|
+
Install the base package (extremely lightweight, ideal for AWS Lambda):
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install filedgr-pkg-utils
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Install with optional image perceptual hashing support (includes Pillow and ImageHash):
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install "filedgr-pkg-utils[images]"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 🚀 Prominent Features & Examples
|
|
28
|
+
|
|
29
|
+
### 1. Resilience & Aspect-Oriented Hooks
|
|
30
|
+
|
|
31
|
+
Stop writing try/except blocks with `time.sleep()`. Stack our context-aware decorators to build bulletproof network calls and clean up your business logic.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from filedgr_pkg_utils.resilience.decorators import retry, circuit_breaker, fallback
|
|
35
|
+
from filedgr_pkg_utils.hooks.post_action import post_action
|
|
36
|
+
|
|
37
|
+
def audit_log(result, *args, **kwargs):
|
|
38
|
+
print(f"Audit: Successfully fetched data {result}")
|
|
39
|
+
|
|
40
|
+
def serve_stale_data(*args, **kwargs):
|
|
41
|
+
return {"status": "stale", "data": []}
|
|
42
|
+
|
|
43
|
+
@post_action(callback=audit_log)
|
|
44
|
+
@fallback(fallback_function=serve_stale_data)
|
|
45
|
+
@circuit_breaker(failure_threshold=5, recovery_timeout_seconds=30)
|
|
46
|
+
@retry(max_attempts=3, backoff_multiplier=2.0)
|
|
47
|
+
async def fetch_web3_data(node_url: str):
|
|
48
|
+
# This function is completely protected.
|
|
49
|
+
# It will retry on failure, trip a circuit breaker if the node is down,
|
|
50
|
+
# serve stale data if all else fails, and log the result when successful.
|
|
51
|
+
pass
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 2. Unified Compression
|
|
55
|
+
|
|
56
|
+
A single, clean protocol for zip, gzip, zstd, and brotli. Easily swap algorithms without changing your application code.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from filedgr_pkg_utils.compression import CompressionUtils, ZstdAlgorithm, ZipAlgorithm
|
|
60
|
+
|
|
61
|
+
# Swap from standard Zip to high-performance Zstd in one line
|
|
62
|
+
utils = CompressionUtils(ZstdAlgorithm(level=3))
|
|
63
|
+
|
|
64
|
+
# Compress bytes
|
|
65
|
+
compressed_data = utils.compress(b"Hello World")
|
|
66
|
+
|
|
67
|
+
# Compress files and directories
|
|
68
|
+
utils.compress_file("data.json", "data.json.zst")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 3. Canonical Serialization & Cryptography
|
|
72
|
+
|
|
73
|
+
Generate deterministic, whitespace-free, and alphabetically sorted JSON payloads—perfect for creating verifiable hashes and blockchain signatures.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from filedgr_pkg_utils.canonicalization.canonical_json_mixin import CanonicalJsonMixin
|
|
77
|
+
from datetime import datetime, timezone
|
|
78
|
+
|
|
79
|
+
class BlockchainPayload(CanonicalJsonMixin):
|
|
80
|
+
z_field: str
|
|
81
|
+
a_field: int
|
|
82
|
+
timestamp: datetime
|
|
83
|
+
|
|
84
|
+
payload = BlockchainPayload(
|
|
85
|
+
z_field="last",
|
|
86
|
+
a_field=1,
|
|
87
|
+
timestamp=datetime(2023, 10, 25, 12, 30, 0, tzinfo=timezone.utc)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# Output is strictly deterministic: {"a_field":1,"timestamp":"2023-10-25T12:30:00.000Z","z_field":"last"}
|
|
91
|
+
json_string = payload.canonical_json()
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 4. Zero-Config Structured JSON Logging
|
|
95
|
+
|
|
96
|
+
Output logs as deterministic JSON for flawless Datadog or AWS CloudWatch ingestion. Fully integrates with Python's standard logging library.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
from filedgr_pkg_utils.logging import LoggerFactory
|
|
100
|
+
|
|
101
|
+
# Automatically reads FILEDGR_LOGGING_ENABLED env var
|
|
102
|
+
logger = LoggerFactory.get_logger(__name__)
|
|
103
|
+
|
|
104
|
+
logger.info("Processing file", extra={"file_id": "ABC-123", "correlation_id": "999"})
|
|
105
|
+
# Output: {"timestamp": "2026-05-14T12:00:00.000Z", "level": "INFO", "logger": "__main__", "message": "Processing file", "file_id": "ABC-123", "correlation_id": "999"}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 5. Perceptual Image Hashing (Optional)
|
|
109
|
+
|
|
110
|
+
Detect visually similar images, compression artifacts, and resized duplicates using Hamming distance.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from filedgr_pkg_utils.images.hashing import PHashAlgorithm, ImageHashUtils
|
|
114
|
+
|
|
115
|
+
utils = ImageHashUtils(PHashAlgorithm())
|
|
116
|
+
|
|
117
|
+
hash_orig = utils.hash_image("original.png")
|
|
118
|
+
hash_comp = utils.hash_image("compressed_artifact.jpg")
|
|
119
|
+
|
|
120
|
+
if utils.is_similar(hash_orig, hash_comp, max_distance=5):
|
|
121
|
+
print("These images are visually similar!")
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## 🛠️ Development & Testing
|
|
125
|
+
|
|
126
|
+
This project enforces high coverage and clean coding standards.
|
|
127
|
+
|
|
128
|
+
To run the test suite with coverage:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
make test-coverage
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
To run the linter:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
make lint
|
|
138
|
+
```
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "filedgr-pkg-utils"
|
|
7
|
+
version = "0.8.4"
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
description = "A library of python based utils needed in the filedgr code stack"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
authors = [{ name = "Filedgr", email = "code@filedgr.com" }]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"License :: OSI Approved :: MIT License",
|
|
14
|
+
"Programming Language :: Python",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
]
|
|
17
|
+
keywords = ["filedgr", "pkg", "utils"]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"pydantic>=2.12.5, <3.0.0",
|
|
20
|
+
"cryptography>=49.0.0, <50.0.0",
|
|
21
|
+
"orjson>=3.11.5, <4.0.0",
|
|
22
|
+
"web3>=7.14.0, <8.0.0",
|
|
23
|
+
"zstandard>=0.22.0, <1.0.0",
|
|
24
|
+
"Brotli>=1.1.0, <2.0.0",
|
|
25
|
+
"aiofiles>=25.1.0, <26.0.0"
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
build = ["build", "twine"]
|
|
30
|
+
dev = ["black", "bumpver", "isort", "mypy", "pytest", "flake8"]
|
|
31
|
+
images = [
|
|
32
|
+
"ImageHash>=4.3.0, <5.0.0",
|
|
33
|
+
"Pillow>=10.0.0, <11.0.0"
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
repository = "https://github.com/Filedgr/filedgr-pkg-utils"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
41
|
+
exclude = ["tests*"]
|
|
42
|
+
|
|
43
|
+
[tool.bumpver]
|
|
44
|
+
current_version = "0.8.4"
|
|
45
|
+
version_pattern = "MAJOR.MINOR.PATCH[-PYTAGNUM]"
|
|
46
|
+
commit_message = "bump version {old_version} -> {new_version}"
|
|
47
|
+
commit = false
|
|
48
|
+
tag = false
|
|
49
|
+
push = false
|
|
50
|
+
|
|
51
|
+
[tool.bumpver.file_patterns]
|
|
52
|
+
"pyproject.toml" = [
|
|
53
|
+
'version = "{version}"',
|
|
54
|
+
]
|
|
55
|
+
"src/filedgr_pkg_utils/__init__.py" = ["{version}"]
|
|
56
|
+
|
|
57
|
+
[tool.isort]
|
|
58
|
+
profile = "black"
|
|
59
|
+
import_heading_stdlib = "Standard library imports"
|
|
60
|
+
import_heading_thirdparty = "Third party imports"
|
|
61
|
+
import_heading_firstparty = "Reader imports"
|
|
62
|
+
|
|
63
|
+
[tool.pytest.ini_options]
|
|
64
|
+
pythonpath = [".", "src"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.8.4"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .memoize import ttl_cache
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import inspect
|
|
3
|
+
from functools import wraps
|
|
4
|
+
from typing import Callable, Any, Dict, Tuple
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def ttl_cache(maxsize: int = 128, ttl_seconds: int = 3600):
|
|
8
|
+
"""
|
|
9
|
+
LRU-style in-memory cache with Time-To-Live (TTL).
|
|
10
|
+
Supports both sync and async functions.
|
|
11
|
+
"""
|
|
12
|
+
def decorator(func: Callable) -> Callable:
|
|
13
|
+
cache: Dict[Tuple, Tuple[float, Any]] = {}
|
|
14
|
+
|
|
15
|
+
def get_cache_key(args, kwargs):
|
|
16
|
+
return (args, tuple(sorted(kwargs.items())))
|
|
17
|
+
|
|
18
|
+
def check_cache(key):
|
|
19
|
+
current_time = time.time()
|
|
20
|
+
if key in cache:
|
|
21
|
+
expiration_time, result = cache[key]
|
|
22
|
+
if current_time < expiration_time:
|
|
23
|
+
return True, result
|
|
24
|
+
return False, None
|
|
25
|
+
|
|
26
|
+
def save_cache(key, result):
|
|
27
|
+
if len(cache) >= maxsize:
|
|
28
|
+
oldest_key = next(iter(cache))
|
|
29
|
+
del cache[oldest_key]
|
|
30
|
+
cache[key] = (time.time() + ttl_seconds, result)
|
|
31
|
+
|
|
32
|
+
if inspect.iscoroutinefunction(func):
|
|
33
|
+
@wraps(func)
|
|
34
|
+
async def async_wrapper(*args, **kwargs):
|
|
35
|
+
key = get_cache_key(args, kwargs)
|
|
36
|
+
hit, result = check_cache(key)
|
|
37
|
+
if hit:
|
|
38
|
+
return result
|
|
39
|
+
result = await func(*args, **kwargs)
|
|
40
|
+
save_cache(key, result)
|
|
41
|
+
return result
|
|
42
|
+
return async_wrapper
|
|
43
|
+
else:
|
|
44
|
+
@wraps(func)
|
|
45
|
+
def sync_wrapper(*args, **kwargs):
|
|
46
|
+
key = get_cache_key(args, kwargs)
|
|
47
|
+
hit, result = check_cache(key)
|
|
48
|
+
if hit:
|
|
49
|
+
return result
|
|
50
|
+
result = func(*args, **kwargs)
|
|
51
|
+
save_cache(key, result)
|
|
52
|
+
return result
|
|
53
|
+
return sync_wrapper
|
|
54
|
+
return decorator
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import orjson
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CanonicalJsonMixin(BaseModel):
|
|
8
|
+
"""
|
|
9
|
+
Deterministic, whitespace-free, sorted-key JSON serialization.
|
|
10
|
+
Suitable for hashing, signing, and blockchain payloads.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
@staticmethod
|
|
14
|
+
def _default(obj: Any):
|
|
15
|
+
if isinstance(obj, datetime):
|
|
16
|
+
# Enforce UTC + milliseconds + Z
|
|
17
|
+
return (
|
|
18
|
+
obj.astimezone(timezone.utc)
|
|
19
|
+
.isoformat(timespec="milliseconds")
|
|
20
|
+
.replace("+00:00", "Z")
|
|
21
|
+
)
|
|
22
|
+
raise TypeError
|
|
23
|
+
|
|
24
|
+
def canonical_json_bytes(self) -> bytes:
|
|
25
|
+
"""
|
|
26
|
+
Canonical JSON as bytes (best for hashing & signing).
|
|
27
|
+
"""
|
|
28
|
+
return orjson.dumps(
|
|
29
|
+
self.model_dump(mode="json"),
|
|
30
|
+
option=orjson.OPT_SORT_KEYS,
|
|
31
|
+
default=self._default,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
def canonical_json(self) -> str:
|
|
35
|
+
"""
|
|
36
|
+
Canonical JSON as UTF-8 string.
|
|
37
|
+
"""
|
|
38
|
+
return self.canonical_json_bytes().decode("utf-8")
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from .algorithms.compression_algorithm_zip import ZipAlgorithm
|
|
2
|
+
from .algorithms.compression_algortihm_gzip import GzipAlgorithm
|
|
3
|
+
from .algorithms.compression_algorithm_zstd import ZstdAlgorithm
|
|
4
|
+
from .algorithms.compression_algorithm_brotli import BrotliAlgorithm
|
|
5
|
+
|
|
6
|
+
from .compression_algorithm import CompressionAlgorithm
|
|
7
|
+
from .compression_utils import CompressionUtils
|
|
File without changes
|
filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_brotli.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import brotli
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BrotliAlgorithm:
|
|
5
|
+
name = "brotli"
|
|
6
|
+
|
|
7
|
+
def __init__(self, quality: int = 11):
|
|
8
|
+
"""
|
|
9
|
+
:param quality: 0 (fastest/lowest) to 11 (slowest/highest). Default is 11.
|
|
10
|
+
"""
|
|
11
|
+
self.quality = quality
|
|
12
|
+
|
|
13
|
+
def compress(self, data: bytes) -> bytes:
|
|
14
|
+
return brotli.compress(data, quality=self.quality)
|
|
15
|
+
|
|
16
|
+
def decompress(self, data: bytes) -> bytes:
|
|
17
|
+
return brotli.decompress(data)
|
|
18
|
+
|
|
19
|
+
def compress_file(self, src: str, dest: str) -> None:
|
|
20
|
+
with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
|
|
21
|
+
f_out.write(brotli.compress(f_in.read(), quality=self.quality))
|
|
22
|
+
|
|
23
|
+
def decompress_file(self, src: str, dest: str) -> None:
|
|
24
|
+
with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
|
|
25
|
+
f_out.write(brotli.decompress(f_in.read()))
|
|
26
|
+
|
|
27
|
+
def compress_folder(self, src: str, dest: str) -> None:
|
|
28
|
+
raise NotImplementedError("Brotli does not natively support folder compression. Use a tarball instead.")
|
|
29
|
+
|
|
30
|
+
def decompress_folder(self, src: str, dest: str) -> None:
|
|
31
|
+
raise NotImplementedError("Brotli does not natively support folder decompression. Use a tarball instead.")
|
filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_zip.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import zipfile
|
|
4
|
+
import zlib
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ZipAlgorithm:
|
|
8
|
+
name = "zip"
|
|
9
|
+
|
|
10
|
+
def __init__(self, compresslevel: int = 6):
|
|
11
|
+
"""
|
|
12
|
+
:param compresslevel: 0 (no compression), 1 (fastest) to 9 (slowest/highest).
|
|
13
|
+
Default is 6 zlib default.
|
|
14
|
+
"""
|
|
15
|
+
self.compresslevel = compresslevel
|
|
16
|
+
|
|
17
|
+
def compress(self, data: bytes) -> bytes:
|
|
18
|
+
return zlib.compress(data, level=self.compresslevel)
|
|
19
|
+
|
|
20
|
+
def decompress(self, data: bytes) -> bytes:
|
|
21
|
+
return zlib.decompress(data)
|
|
22
|
+
|
|
23
|
+
def compress_file(self, src: str, dest: str) -> None:
|
|
24
|
+
with zipfile.ZipFile(dest, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=self.compresslevel) as zf:
|
|
25
|
+
zf.write(src, arcname=os.path.basename(src))
|
|
26
|
+
|
|
27
|
+
def decompress_file(self, src: str, dest: str) -> None:
|
|
28
|
+
with zipfile.ZipFile(src, 'r') as zf:
|
|
29
|
+
names = zf.namelist()
|
|
30
|
+
if not names:
|
|
31
|
+
return
|
|
32
|
+
with zf.open(names[0]) as f_in, open(dest, 'wb') as f_out:
|
|
33
|
+
shutil.copyfileobj(f_in, f_out)
|
|
34
|
+
|
|
35
|
+
def compress_folder(self, src: str, dest: str) -> None:
|
|
36
|
+
with zipfile.ZipFile(dest, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=self.compresslevel) as zf:
|
|
37
|
+
for root, _, files in os.walk(src):
|
|
38
|
+
for file in files:
|
|
39
|
+
file_path = os.path.join(root, file)
|
|
40
|
+
arcname = os.path.relpath(file_path, start=src)
|
|
41
|
+
zf.write(file_path, arcname=arcname)
|
|
42
|
+
|
|
43
|
+
def decompress_folder(self, src: str, dest: str) -> None:
|
|
44
|
+
with zipfile.ZipFile(src, 'r') as zf:
|
|
45
|
+
zf.extractall(path=dest)
|
filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algorithm_zstd.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import zstandard as zstd
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ZstdAlgorithm:
|
|
5
|
+
name = "zstd"
|
|
6
|
+
|
|
7
|
+
def __init__(self, level: int = 3):
|
|
8
|
+
"""
|
|
9
|
+
:param level: 1 (fastest) to 22 (slowest/highest). Default is usually 3.
|
|
10
|
+
"""
|
|
11
|
+
self.level = level
|
|
12
|
+
|
|
13
|
+
def compress(self, data: bytes) -> bytes:
|
|
14
|
+
compressor = zstd.ZstdCompressor(level=self.level)
|
|
15
|
+
return compressor.compress(data)
|
|
16
|
+
|
|
17
|
+
def decompress(self, data: bytes) -> bytes:
|
|
18
|
+
decompressor = zstd.ZstdDecompressor()
|
|
19
|
+
return decompressor.decompress(data)
|
|
20
|
+
|
|
21
|
+
def compress_file(self, src: str, dest: str) -> None:
|
|
22
|
+
cctx = zstd.ZstdCompressor(level=self.level)
|
|
23
|
+
with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
|
|
24
|
+
cctx.copy_stream(f_in, f_out)
|
|
25
|
+
|
|
26
|
+
def decompress_file(self, src: str, dest: str) -> None:
|
|
27
|
+
dctx = zstd.ZstdDecompressor()
|
|
28
|
+
with open(src, 'rb') as f_in, open(dest, 'wb') as f_out:
|
|
29
|
+
dctx.copy_stream(f_in, f_out)
|
|
30
|
+
|
|
31
|
+
def compress_folder(self, src: str, dest: str) -> None:
|
|
32
|
+
raise NotImplementedError("Zstd does not natively support folder compression. Use a tarball instead.")
|
|
33
|
+
|
|
34
|
+
def decompress_folder(self, src: str, dest: str) -> None:
|
|
35
|
+
raise NotImplementedError("Zstd does not natively support folder decompression. Use a tarball instead.")
|
filedgr_pkg_utils-0.8.4/src/filedgr_pkg_utils/compression/algorithms/compression_algortihm_gzip.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import gzip
|
|
2
|
+
import shutil
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class GzipAlgorithm:
|
|
6
|
+
name = "gzip"
|
|
7
|
+
|
|
8
|
+
def __init__(self, compresslevel: int = 9):
|
|
9
|
+
"""
|
|
10
|
+
:param compresslevel: 1 (fastest/lowest) to 9 (slowest/highest). Default is 9.
|
|
11
|
+
"""
|
|
12
|
+
self.compresslevel = compresslevel
|
|
13
|
+
|
|
14
|
+
def compress(self, data: bytes) -> bytes:
|
|
15
|
+
return gzip.compress(data, compresslevel=self.compresslevel)
|
|
16
|
+
|
|
17
|
+
def decompress(self, data: bytes) -> bytes:
|
|
18
|
+
return gzip.decompress(data)
|
|
19
|
+
|
|
20
|
+
def compress_file(self, src: str, dest: str) -> None:
|
|
21
|
+
with open(src, 'rb') as f_in:
|
|
22
|
+
with gzip.open(dest, 'wb', compresslevel=self.compresslevel) as f_out:
|
|
23
|
+
shutil.copyfileobj(f_in, f_out)
|
|
24
|
+
|
|
25
|
+
def decompress_file(self, src: str, dest: str) -> None:
|
|
26
|
+
with gzip.open(src, 'rb') as f_in:
|
|
27
|
+
with open(dest, 'wb') as f_out:
|
|
28
|
+
shutil.copyfileobj(f_in, f_out)
|
|
29
|
+
|
|
30
|
+
def compress_folder(self, src: str, dest: str) -> None:
|
|
31
|
+
raise NotImplementedError("Gzip does not natively support folder compression. Use a tarball instead.")
|
|
32
|
+
|
|
33
|
+
def decompress_folder(self, src: str, dest: str) -> None:
|
|
34
|
+
raise NotImplementedError("Gzip does not natively support folder decompression. Use a tarball instead.")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from typing import Protocol
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CompressionAlgorithm(Protocol):
|
|
5
|
+
"""Pure compression contract: handles bytes, files, and directories."""
|
|
6
|
+
name: str
|
|
7
|
+
|
|
8
|
+
def compress(self, data: bytes) -> bytes:
|
|
9
|
+
...
|
|
10
|
+
|
|
11
|
+
def decompress(self, data: bytes) -> bytes:
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
def compress_file(self, src: str, dest: str) -> None:
|
|
15
|
+
...
|
|
16
|
+
|
|
17
|
+
def decompress_file(self, src: str, dest: str) -> None:
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
def compress_folder(self, src: str, dest: str) -> None:
|
|
21
|
+
...
|
|
22
|
+
|
|
23
|
+
def decompress_folder(self, src: str, dest: str) -> None:
|
|
24
|
+
...
|