kaiju-s3 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.
kaiju_s3-1.0.0/LICENSE ADDED
@@ -0,0 +1,14 @@
1
+
2
+ Copyright 2023 Anton A. Taraskin antonnidhoggr@me.com
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
@@ -0,0 +1,4 @@
1
+ graft src
2
+ global-exclude __pycache__
3
+ global-exclude *.py[cod]
4
+ global-exclude tests
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: kaiju-s3
3
+ Version: 1.0.0
4
+ Summary: S3 services and classes for kaiju libraries
5
+ Author-email: Taraskin Anton <antonnidhoggr@me.com>
6
+ Maintainer-email: Taraskin Anton <antonnidhoggr@me.com>
7
+ Project-URL: Homepage, https://gitlab.com/kaiju-python/kaiju-s3
8
+ Project-URL: Documentation, https://kaiju-tools.readthedocs.io
9
+ Keywords: kaiju,s3
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: Implementation :: CPython
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/x-rst
16
+ License-File: LICENSE
17
+ Requires-Dist: boto3
18
+ Requires-Dist: kaiju-tools<3.0,>=2.4.27
19
+ Provides-Extra: dev
20
+ Requires-Dist: uv; extra == "dev"
21
+ Requires-Dist: pre-commit; extra == "dev"
22
+ Requires-Dist: bump-my-version; extra == "dev"
23
+ Requires-Dist: black; extra == "dev"
24
+ Requires-Dist: isort; extra == "dev"
25
+ Requires-Dist: bandit; extra == "dev"
26
+ Requires-Dist: pyupgrade; extra == "dev"
27
+ Requires-Dist: pyroma; extra == "dev"
28
+ Requires-Dist: pylint; extra == "dev"
29
+ Requires-Dist: pytest; extra == "dev"
30
+ Requires-Dist: pytest-asyncio; extra == "dev"
31
+ Requires-Dist: pytest-aiohttp; extra == "dev"
32
+ Requires-Dist: docker; extra == "dev"
33
+ Provides-Extra: docs
34
+ Requires-Dist: sphinx; extra == "docs"
35
+ Requires-Dist: python-docs-theme; extra == "docs"
36
+ Dynamic: license-file
File without changes
@@ -0,0 +1,6 @@
1
+ from .logging import *
2
+
3
+ __version__ = "1.0.0"
4
+ __python_version__ = "3.11"
5
+ __author__ = "antonnidhoggr@me.com"
6
+ __service_package__ = True
@@ -0,0 +1,194 @@
1
+ import gzip
2
+ import logging.handlers
3
+ import mimetypes
4
+ from datetime import date
5
+ from io import BytesIO
6
+ from time import sleep
7
+ from typing import Any, cast
8
+
9
+ import boto3 as s3
10
+ import botocore.client
11
+ from kaiju_tools.logging import HANDLERS, DataFormatter, HandlerInterface, TextFormatter, _LogRecord
12
+ from kaiju_tools.types import OverflowQueue
13
+
14
+ __all__ = ["S3TextHandler", "S3JSONHandler"]
15
+
16
+
17
+ class _S3FileHandler(HandlerInterface):
18
+ """Modified stream handler with `sys.stdout` by default."""
19
+
20
+ MIME_TYPES = {
21
+ "application/json": ".json",
22
+ "application/xml": ".xml",
23
+ "text/plain": ".txt",
24
+ }
25
+
26
+ def __init__(
27
+ self,
28
+ client: botocore.client.BaseClient,
29
+ name: str,
30
+ bucket_id: str,
31
+ content_type: str,
32
+ ext: str,
33
+ compress_logs: bool,
34
+ compression_level: int,
35
+ log_prefix: str,
36
+ ):
37
+ super().__init__()
38
+ self.name = name
39
+ self.log_prefix = f"{log_prefix}/{self.name}"
40
+ self.bucket_id = bucket_id
41
+ self.content_type = content_type
42
+ self.ext = ext
43
+ self.compress_logs = compress_logs
44
+ self.compression_level = compression_level
45
+ self.s3_client = client
46
+
47
+ def emit(self, record):
48
+ headers = {"ContentType": self.content_type}
49
+ file_name = f"{int(record.created * 1000)}{self.ext}"
50
+ msg = self.format(record)
51
+ if type(msg) is str:
52
+ msg = msg.encode("utf-8")
53
+ if self.compress_logs:
54
+ data = gzip.compress(msg, compresslevel=self.compression_level)
55
+ headers["ContentEncoding"] = "gzip"
56
+ file_name = f"{file_name}.gz"
57
+ else:
58
+ data = msg
59
+
60
+ key = [self.log_prefix, date.today().isoformat(), record.name]
61
+ _cid = getattr(record, "_cid")
62
+ if _cid:
63
+ key.append(_cid)
64
+ key.append(file_name)
65
+ key = "/".join(key)
66
+ self.s3_client.upload_fileobj(BytesIO(data), self.bucket_id, key, ExtraArgs=headers)
67
+
68
+ def close(self):
69
+ self.s3_client.close()
70
+ super().close()
71
+
72
+
73
+ class _S3QueueListener(logging.handlers.QueueListener):
74
+ """Queued log listener with buffering.
75
+
76
+ Used by the log handlers to store log records.
77
+ """
78
+
79
+ def _monitor(self):
80
+ """Monitor the queue for records, and ask the handler to deal with them."""
81
+ q: OverflowQueue[_LogRecord] = self.queue # noqa
82
+ handler = cast(_S3FileHandler, self.handlers[0])
83
+ emit = handler.emit
84
+ while True:
85
+ try:
86
+ record = q.get(True)
87
+ if record is None:
88
+ return
89
+ emit(record)
90
+ except Exception as e:
91
+ print(e)
92
+ finally:
93
+ q.task_done()
94
+ sleep(0)
95
+
96
+
97
+ class S3TextHandler(logging.handlers.QueueHandler, HandlerInterface):
98
+ """Human-readable text log queue handler for S3 storage."""
99
+
100
+ MIME_TYPES = {
101
+ "application/json": ".json",
102
+ "application/xml": ".xml",
103
+ "text/plain": ".txt",
104
+ }
105
+
106
+ formatter_cls = TextFormatter
107
+ handler_cls = _S3FileHandler
108
+ listener_cls = _S3QueueListener
109
+ content_type = "text/plain"
110
+
111
+ def __init__(
112
+ self,
113
+ app=None,
114
+ formatter: dict | None = None,
115
+ bucket_id: str | None = None,
116
+ content_type: str | None = None,
117
+ compress_logs: bool = True,
118
+ compression_level: int = 1,
119
+ log_prefix: str = "logs",
120
+ s3_client: botocore.client.BaseClient | None = None,
121
+ conn_settings: dict[str, Any] | None = None,
122
+ queue_size: int = 5_000,
123
+ ):
124
+ """Initialize.
125
+
126
+ :param app: web app.
127
+ :param formatter: formatter class settings.
128
+ :param conn_settings: S3 client connection settings.
129
+ :param queue_size: log queue max size.
130
+ :param bucket_id: S3 bucket id.
131
+ :param content_type: logs mime type.
132
+ :param compress_logs: use gzip compression.
133
+ :param compression_level: gzip comp level.
134
+ :param log_prefix: bucket root dir for logs.
135
+ :param s3_client: you can pass either `conn_settings` or `s3_client` to create an actual S3 client.
136
+ :param conn_settings: S3 client init args.
137
+ """
138
+
139
+ if bucket_id is None:
140
+ raise ValueError("bucket_id is required for logging `S3TextHandler`")
141
+
142
+ q = OverflowQueue(queue_size)
143
+ logging.handlers.QueueHandler.__init__(self, q)
144
+
145
+ if content_type is None:
146
+ content_type = self.__class__.content_type
147
+
148
+ ext = self.MIME_TYPES.get(self.content_type)
149
+ if not ext:
150
+ ext = mimetypes.guess_extension(self.content_type)
151
+ if not ext:
152
+ ext = ".log"
153
+
154
+ if not s3_client:
155
+ if conn_settings is None:
156
+ conn_settings = {}
157
+ s3_client = s3.client("s3", **conn_settings)
158
+
159
+ self._handler = self.handler_cls(
160
+ client=s3_client,
161
+ name=app.name if app else "python",
162
+ bucket_id=bucket_id,
163
+ content_type=content_type,
164
+ ext=ext,
165
+ compress_logs=compress_logs,
166
+ compression_level=compression_level,
167
+ log_prefix=log_prefix,
168
+ )
169
+ self._listener = _S3QueueListener(q, self._handler)
170
+ if formatter is None:
171
+ formatter = {}
172
+ self._handler.setFormatter(self.formatter_cls(**formatter))
173
+ self.app = app
174
+ self._listener.start()
175
+
176
+ def setFormatter(self, fmt) -> None:
177
+ self._handler.setFormatter(fmt)
178
+
179
+ def prepare(self, record):
180
+ # Ignoring all possible log handler conflicts for now.
181
+ return record
182
+
183
+ def close(self):
184
+ self._listener.stop()
185
+ self._handler.close()
186
+
187
+
188
+ class S3JSONHandler(S3TextHandler):
189
+ formatter_cls = DataFormatter
190
+ content_type = "application/json"
191
+
192
+
193
+ HANDLERS.register(S3TextHandler)
194
+ HANDLERS.register(S3JSONHandler)
File without changes
@@ -0,0 +1,68 @@
1
+ import logging
2
+ from uuid import uuid4
3
+
4
+ import pytest # noqa: pycharm
5
+
6
+ from kaiju_tools.docker import DockerContainer, DockerImage
7
+ from kaiju_tools.tests.fixtures import *
8
+
9
+ __all__ = ["s3", "s3_glob", "s3_client", "s3_bucket"]
10
+
11
+
12
+ def _s3_container(app):
13
+ return DockerContainer(
14
+ image=DockerImage(app=app, tag="pgsty/minio", version="latest"),
15
+ name="pytest-s3",
16
+ command='server /home --console-address ":9001"',
17
+ ports={"9000": "9000", "9001": "9001"},
18
+ env={"MINIO_ROOT_USER": "minioadmin", "MINIO_ROOT_PASSWORD": "minioadmin", "AWS_EC2_METADATA_DISABLED": "true"},
19
+ sleep_interval=5,
20
+ remove_on_exit=True,
21
+ app=app,
22
+ )
23
+
24
+
25
+ @pytest.fixture
26
+ def s3(app):
27
+ """Return a new database container. See `kaiju_tools.tests.fixtures.container` for more info."""
28
+ with _s3_container(app) as c:
29
+ yield c
30
+
31
+
32
+ @pytest.fixture(scope="session")
33
+ def s3_glob():
34
+ """Return a new database container. See `kaiju_tools.tests.fixtures.per_session_container` for more info."""
35
+ logger = logging.getLogger("pytest")
36
+ logger.setLevel("DEBUG")
37
+ app = get_app(logger)
38
+ with _s3_container(app) as c:
39
+ yield c
40
+
41
+
42
+ @pytest.fixture(scope="session")
43
+ def s3_client(s3_glob):
44
+ import boto3
45
+
46
+ client = boto3.client(
47
+ "s3",
48
+ endpoint_url="http://0.0.0.0:9000",
49
+ aws_access_key_id="minioadmin",
50
+ aws_secret_access_key="minioadmin",
51
+ region_name="us-east-1",
52
+ )
53
+ yield client
54
+ client.close()
55
+
56
+
57
+ @pytest.fixture(scope="class")
58
+ def s3_bucket(s3_client):
59
+ bucket_id = uuid4().hex
60
+ s3_client.create_bucket(Bucket=bucket_id)
61
+ yield bucket_id
62
+ resp = s3_client.list_objects_v2(Bucket=bucket_id)
63
+ if "Contents" in resp:
64
+ s3_client.delete_objects(
65
+ Bucket=bucket_id,
66
+ Delete={"Objects": [{"Key": o["Key"]} for o in resp["Contents"]]},
67
+ )
68
+ s3_client.delete_bucket(Bucket=bucket_id)
@@ -0,0 +1,29 @@
1
+ import logging
2
+ import time
3
+
4
+ import pytest
5
+
6
+ from kaiju_s3.logging import *
7
+
8
+
9
+ @pytest.mark.docker
10
+ class TestS3Logging:
11
+ """Test postgres connector."""
12
+
13
+ def test_log_handler(self, s3_client, s3_bucket):
14
+ handler = S3TextHandler(
15
+ bucket_id=s3_bucket,
16
+ conn_settings={
17
+ "endpoint_url": "http://0.0.0.0:9000",
18
+ "aws_access_key_id": "minioadmin",
19
+ "aws_secret_access_key": "minioadmin",
20
+ "region_name": "us-east-1",
21
+ },
22
+ )
23
+ logger = logging.getLogger("s3")
24
+ logger.addHandler(handler)
25
+ logger.info("TEST")
26
+ time.sleep(1)
27
+ resp = s3_client.list_objects_v2(Bucket=s3_bucket)
28
+ assert resp.get("Contents"), "a log record should be created"
29
+ handler.close()
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: kaiju-s3
3
+ Version: 1.0.0
4
+ Summary: S3 services and classes for kaiju libraries
5
+ Author-email: Taraskin Anton <antonnidhoggr@me.com>
6
+ Maintainer-email: Taraskin Anton <antonnidhoggr@me.com>
7
+ Project-URL: Homepage, https://gitlab.com/kaiju-python/kaiju-s3
8
+ Project-URL: Documentation, https://kaiju-tools.readthedocs.io
9
+ Keywords: kaiju,s3
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: Implementation :: CPython
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/x-rst
16
+ License-File: LICENSE
17
+ Requires-Dist: boto3
18
+ Requires-Dist: kaiju-tools<3.0,>=2.4.27
19
+ Provides-Extra: dev
20
+ Requires-Dist: uv; extra == "dev"
21
+ Requires-Dist: pre-commit; extra == "dev"
22
+ Requires-Dist: bump-my-version; extra == "dev"
23
+ Requires-Dist: black; extra == "dev"
24
+ Requires-Dist: isort; extra == "dev"
25
+ Requires-Dist: bandit; extra == "dev"
26
+ Requires-Dist: pyupgrade; extra == "dev"
27
+ Requires-Dist: pyroma; extra == "dev"
28
+ Requires-Dist: pylint; extra == "dev"
29
+ Requires-Dist: pytest; extra == "dev"
30
+ Requires-Dist: pytest-asyncio; extra == "dev"
31
+ Requires-Dist: pytest-aiohttp; extra == "dev"
32
+ Requires-Dist: docker; extra == "dev"
33
+ Provides-Extra: docs
34
+ Requires-Dist: sphinx; extra == "docs"
35
+ Requires-Dist: python-docs-theme; extra == "docs"
36
+ Dynamic: license-file
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ kaiju_s3/__init__.py
6
+ kaiju_s3/logging.py
7
+ kaiju_s3.egg-info/PKG-INFO
8
+ kaiju_s3.egg-info/SOURCES.txt
9
+ kaiju_s3.egg-info/dependency_links.txt
10
+ kaiju_s3.egg-info/requires.txt
11
+ kaiju_s3.egg-info/top_level.txt
12
+ kaiju_s3/tests/__init__.py
13
+ kaiju_s3/tests/fixtures.py
14
+ kaiju_s3/tests/test_logging.py
@@ -0,0 +1,21 @@
1
+ boto3
2
+ kaiju-tools<3.0,>=2.4.27
3
+
4
+ [dev]
5
+ uv
6
+ pre-commit
7
+ bump-my-version
8
+ black
9
+ isort
10
+ bandit
11
+ pyupgrade
12
+ pyroma
13
+ pylint
14
+ pytest
15
+ pytest-asyncio
16
+ pytest-aiohttp
17
+ docker
18
+
19
+ [docs]
20
+ sphinx
21
+ python-docs-theme
@@ -0,0 +1 @@
1
+ kaiju_s3
@@ -0,0 +1,114 @@
1
+ [project]
2
+ name = "kaiju-s3"
3
+ version = "1.0.0"
4
+ description = "S3 services and classes for kaiju libraries"
5
+ keywords = ["kaiju", "s3"]
6
+ requires-python = ">=3.11"
7
+ authors = [
8
+ {name = "Taraskin Anton", email = "antonnidhoggr@me.com"}
9
+ ]
10
+ maintainers = [
11
+ {name = "Taraskin Anton", email = "antonnidhoggr@me.com"}
12
+ ]
13
+ readme = {file = "README.rst", content-type = "text/x-rst"}
14
+ license-files = ["LICENSE"]
15
+ dependencies = [
16
+ "boto3",
17
+ "kaiju-tools>=2.4.27,<3.0"
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: Implementation :: CPython"
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://gitlab.com/kaiju-python/kaiju-s3"
28
+ Documentation = "https://kaiju-tools.readthedocs.io"
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "uv",
33
+ "pre-commit",
34
+ "bump-my-version",
35
+ "black",
36
+ "isort",
37
+ "bandit",
38
+ "pyupgrade",
39
+ "pyroma",
40
+ "pylint",
41
+ "pytest",
42
+ "pytest-asyncio",
43
+ "pytest-aiohttp",
44
+ "docker"
45
+ ]
46
+ docs = [
47
+ "sphinx",
48
+ "python-docs-theme"
49
+ ]
50
+
51
+ # --- BUILD CONFIGURATION ---
52
+
53
+ [build-system]
54
+ requires = ["setuptools >= 76.0"]
55
+ build-backend = "setuptools.build_meta"
56
+
57
+ # --- TOOL CONFIGURATION ---
58
+
59
+ [tool.bandit]
60
+ skips = ["B101"] # , "B105", "B110", "B310", "B311", "B404", "B601", "B602", "B603", "B608", "B701"
61
+
62
+ [tool.black]
63
+ line-length = 120
64
+ target-version = ['py311']
65
+
66
+ [tool.bumpversion]
67
+ parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
68
+ serialize = ["{major}.{minor}.{patch}"]
69
+ search = "{current_version}"
70
+ replace = "{new_version}"
71
+ regex = false
72
+ ignore_missing_version = false
73
+ tag = true
74
+ sign_tags = true
75
+ tag_name = "{new_version}"
76
+ tag_message = "Bump version: {current_version} → {new_version}"
77
+ allow_dirty = false
78
+ commit = true
79
+ message = "Bump version: {current_version} → {new_version}"
80
+ commit_args = ""
81
+
82
+ [tool.isort]
83
+ profile = "black"
84
+ multi_line_output = 3
85
+ skip_gitignore = true
86
+ balanced_wrapping = true
87
+ line_length = 120
88
+ wrap_length = 120
89
+ src_paths = ['kaiju_s3']
90
+ known_first_party = ['kaiju_s3']
91
+ skip = ['conftest.py', '__init__.py', '__main__.py', 'setup.py']
92
+ skip_glob = ['docs/*', 'kaiju_s3/tests/*']
93
+
94
+ [tool.pylint]
95
+ load-plugins = [
96
+ 'pylint.extensions.check_elif',
97
+ 'pylint.extensions.docstyle',
98
+ 'pylint.extensions.dunder',
99
+ 'pylint.extensions.eq_without_hash',
100
+ 'pylint.extensions.mccabe',
101
+ 'pylint.extensions.overlapping_exceptions',
102
+ 'pylint.extensions.private_import'
103
+ ]
104
+ disable = ['C0116', 'C0114', 'W0622', 'W0718', 'R0903', 'R0913', 'R0902', 'R1705', 'C0123', 'R1702', 'R0912', 'R1260', 'C0302', 'W0212', 'C0103', 'R0917', 'W0614', 'W0237', 'R0914', 'W0612', 'W0401']
105
+ max-line-length = 120
106
+
107
+ [tool.pytest.ini_options]
108
+ log_cli = true
109
+ log_level = "DEBUG"
110
+ log_format = '"%(name)s %(levelname)s %(message)s"'
111
+ log_cli_level = "DEBUG"
112
+ addopts = "--doctest-modules --doctest-continue-on-failure --ignore=docs/source/conf.py --ignore=conftest.py --ignore=setup.py"
113
+ markers = ['docker', 'benchmark']
114
+ asyncio_mode = "auto"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+