kstlib 0.0.1a0__py3-none-any.whl → 1.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.
Files changed (166) hide show
  1. kstlib/__init__.py +266 -1
  2. kstlib/__main__.py +16 -0
  3. kstlib/alerts/__init__.py +110 -0
  4. kstlib/alerts/channels/__init__.py +36 -0
  5. kstlib/alerts/channels/base.py +197 -0
  6. kstlib/alerts/channels/email.py +227 -0
  7. kstlib/alerts/channels/slack.py +389 -0
  8. kstlib/alerts/exceptions.py +72 -0
  9. kstlib/alerts/manager.py +651 -0
  10. kstlib/alerts/models.py +142 -0
  11. kstlib/alerts/throttle.py +263 -0
  12. kstlib/auth/__init__.py +139 -0
  13. kstlib/auth/callback.py +399 -0
  14. kstlib/auth/config.py +502 -0
  15. kstlib/auth/errors.py +127 -0
  16. kstlib/auth/models.py +316 -0
  17. kstlib/auth/providers/__init__.py +14 -0
  18. kstlib/auth/providers/base.py +393 -0
  19. kstlib/auth/providers/oauth2.py +645 -0
  20. kstlib/auth/providers/oidc.py +821 -0
  21. kstlib/auth/session.py +338 -0
  22. kstlib/auth/token.py +482 -0
  23. kstlib/cache/__init__.py +50 -0
  24. kstlib/cache/decorator.py +261 -0
  25. kstlib/cache/strategies.py +516 -0
  26. kstlib/cli/__init__.py +8 -0
  27. kstlib/cli/app.py +195 -0
  28. kstlib/cli/commands/__init__.py +5 -0
  29. kstlib/cli/commands/auth/__init__.py +39 -0
  30. kstlib/cli/commands/auth/common.py +122 -0
  31. kstlib/cli/commands/auth/login.py +325 -0
  32. kstlib/cli/commands/auth/logout.py +74 -0
  33. kstlib/cli/commands/auth/providers.py +57 -0
  34. kstlib/cli/commands/auth/status.py +291 -0
  35. kstlib/cli/commands/auth/token.py +199 -0
  36. kstlib/cli/commands/auth/whoami.py +106 -0
  37. kstlib/cli/commands/config.py +89 -0
  38. kstlib/cli/commands/ops/__init__.py +39 -0
  39. kstlib/cli/commands/ops/attach.py +49 -0
  40. kstlib/cli/commands/ops/common.py +269 -0
  41. kstlib/cli/commands/ops/list_sessions.py +252 -0
  42. kstlib/cli/commands/ops/logs.py +49 -0
  43. kstlib/cli/commands/ops/start.py +98 -0
  44. kstlib/cli/commands/ops/status.py +138 -0
  45. kstlib/cli/commands/ops/stop.py +60 -0
  46. kstlib/cli/commands/rapi/__init__.py +60 -0
  47. kstlib/cli/commands/rapi/call.py +341 -0
  48. kstlib/cli/commands/rapi/list.py +99 -0
  49. kstlib/cli/commands/rapi/show.py +206 -0
  50. kstlib/cli/commands/secrets/__init__.py +35 -0
  51. kstlib/cli/commands/secrets/common.py +425 -0
  52. kstlib/cli/commands/secrets/decrypt.py +88 -0
  53. kstlib/cli/commands/secrets/doctor.py +743 -0
  54. kstlib/cli/commands/secrets/encrypt.py +242 -0
  55. kstlib/cli/commands/secrets/shred.py +96 -0
  56. kstlib/cli/common.py +86 -0
  57. kstlib/config/__init__.py +76 -0
  58. kstlib/config/exceptions.py +110 -0
  59. kstlib/config/export.py +225 -0
  60. kstlib/config/loader.py +963 -0
  61. kstlib/config/sops.py +287 -0
  62. kstlib/db/__init__.py +54 -0
  63. kstlib/db/aiosqlcipher.py +137 -0
  64. kstlib/db/cipher.py +112 -0
  65. kstlib/db/database.py +367 -0
  66. kstlib/db/exceptions.py +25 -0
  67. kstlib/db/pool.py +302 -0
  68. kstlib/helpers/__init__.py +35 -0
  69. kstlib/helpers/exceptions.py +11 -0
  70. kstlib/helpers/time_trigger.py +396 -0
  71. kstlib/kstlib.conf.yml +890 -0
  72. kstlib/limits.py +963 -0
  73. kstlib/logging/__init__.py +108 -0
  74. kstlib/logging/manager.py +633 -0
  75. kstlib/mail/__init__.py +42 -0
  76. kstlib/mail/builder.py +626 -0
  77. kstlib/mail/exceptions.py +27 -0
  78. kstlib/mail/filesystem.py +248 -0
  79. kstlib/mail/transport.py +224 -0
  80. kstlib/mail/transports/__init__.py +19 -0
  81. kstlib/mail/transports/gmail.py +268 -0
  82. kstlib/mail/transports/resend.py +324 -0
  83. kstlib/mail/transports/smtp.py +326 -0
  84. kstlib/meta.py +72 -0
  85. kstlib/metrics/__init__.py +88 -0
  86. kstlib/metrics/decorators.py +1090 -0
  87. kstlib/metrics/exceptions.py +14 -0
  88. kstlib/monitoring/__init__.py +116 -0
  89. kstlib/monitoring/_styles.py +163 -0
  90. kstlib/monitoring/cell.py +57 -0
  91. kstlib/monitoring/config.py +424 -0
  92. kstlib/monitoring/delivery.py +579 -0
  93. kstlib/monitoring/exceptions.py +63 -0
  94. kstlib/monitoring/image.py +220 -0
  95. kstlib/monitoring/kv.py +79 -0
  96. kstlib/monitoring/list.py +69 -0
  97. kstlib/monitoring/metric.py +88 -0
  98. kstlib/monitoring/monitoring.py +341 -0
  99. kstlib/monitoring/renderer.py +139 -0
  100. kstlib/monitoring/service.py +392 -0
  101. kstlib/monitoring/table.py +129 -0
  102. kstlib/monitoring/types.py +56 -0
  103. kstlib/ops/__init__.py +86 -0
  104. kstlib/ops/base.py +148 -0
  105. kstlib/ops/container.py +577 -0
  106. kstlib/ops/exceptions.py +209 -0
  107. kstlib/ops/manager.py +407 -0
  108. kstlib/ops/models.py +176 -0
  109. kstlib/ops/tmux.py +372 -0
  110. kstlib/ops/validators.py +287 -0
  111. kstlib/py.typed +0 -0
  112. kstlib/rapi/__init__.py +118 -0
  113. kstlib/rapi/client.py +875 -0
  114. kstlib/rapi/config.py +861 -0
  115. kstlib/rapi/credentials.py +887 -0
  116. kstlib/rapi/exceptions.py +213 -0
  117. kstlib/resilience/__init__.py +101 -0
  118. kstlib/resilience/circuit_breaker.py +440 -0
  119. kstlib/resilience/exceptions.py +95 -0
  120. kstlib/resilience/heartbeat.py +491 -0
  121. kstlib/resilience/rate_limiter.py +506 -0
  122. kstlib/resilience/shutdown.py +417 -0
  123. kstlib/resilience/watchdog.py +637 -0
  124. kstlib/secrets/__init__.py +29 -0
  125. kstlib/secrets/exceptions.py +19 -0
  126. kstlib/secrets/models.py +62 -0
  127. kstlib/secrets/providers/__init__.py +79 -0
  128. kstlib/secrets/providers/base.py +58 -0
  129. kstlib/secrets/providers/environment.py +66 -0
  130. kstlib/secrets/providers/keyring.py +107 -0
  131. kstlib/secrets/providers/kms.py +223 -0
  132. kstlib/secrets/providers/kwargs.py +101 -0
  133. kstlib/secrets/providers/sops.py +209 -0
  134. kstlib/secrets/resolver.py +221 -0
  135. kstlib/secrets/sensitive.py +130 -0
  136. kstlib/secure/__init__.py +23 -0
  137. kstlib/secure/fs.py +194 -0
  138. kstlib/secure/permissions.py +70 -0
  139. kstlib/ssl.py +347 -0
  140. kstlib/ui/__init__.py +23 -0
  141. kstlib/ui/exceptions.py +26 -0
  142. kstlib/ui/panels.py +484 -0
  143. kstlib/ui/spinner.py +864 -0
  144. kstlib/ui/tables.py +382 -0
  145. kstlib/utils/__init__.py +48 -0
  146. kstlib/utils/dict.py +36 -0
  147. kstlib/utils/formatting.py +338 -0
  148. kstlib/utils/http_trace.py +237 -0
  149. kstlib/utils/lazy.py +49 -0
  150. kstlib/utils/secure_delete.py +205 -0
  151. kstlib/utils/serialization.py +247 -0
  152. kstlib/utils/text.py +56 -0
  153. kstlib/utils/validators.py +124 -0
  154. kstlib/websocket/__init__.py +97 -0
  155. kstlib/websocket/exceptions.py +214 -0
  156. kstlib/websocket/manager.py +1102 -0
  157. kstlib/websocket/models.py +361 -0
  158. kstlib-1.0.1.dist-info/METADATA +201 -0
  159. kstlib-1.0.1.dist-info/RECORD +163 -0
  160. {kstlib-0.0.1a0.dist-info → kstlib-1.0.1.dist-info}/WHEEL +1 -1
  161. kstlib-1.0.1.dist-info/entry_points.txt +2 -0
  162. kstlib-1.0.1.dist-info/licenses/LICENSE.md +9 -0
  163. kstlib-0.0.1a0.dist-info/METADATA +0 -29
  164. kstlib-0.0.1a0.dist-info/RECORD +0 -6
  165. kstlib-0.0.1a0.dist-info/licenses/LICENSE.md +0 -5
  166. {kstlib-0.0.1a0.dist-info → kstlib-1.0.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,326 @@
1
+ """SMTP transport backend with TRACE-level debugging.
2
+
3
+ When the logger level is set to TRACE, this transport logs detailed
4
+ information about the SMTP session including:
5
+ - Connection and EHLO exchange
6
+ - STARTTLS negotiation and SSL/TLS cipher details
7
+ - Authentication flow (credentials redacted)
8
+ - Message envelope (MAIL FROM, RCPT TO)
9
+
10
+ Enable trace logging via configuration:
11
+ logger:
12
+ preset: trace_mail # Or set level: TRACE directly
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ # pylint: disable=too-many-instance-attributes,too-many-arguments,too-few-public-methods
18
+ import io
19
+ import logging
20
+ import smtplib
21
+ import ssl
22
+ import sys
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+ from typing import TYPE_CHECKING, Any
26
+
27
+ from kstlib.logging import TRACE_LEVEL
28
+ from kstlib.mail.exceptions import MailTransportError
29
+ from kstlib.mail.transport import MailTransport
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Iterator
33
+ from email.message import EmailMessage
34
+
35
+ # Module logger - uses kstlib hierarchy for config-driven trace
36
+ log = logging.getLogger(__name__)
37
+
38
+
39
+ @contextmanager
40
+ def _capture_smtp_debug() -> Iterator[io.StringIO]:
41
+ """Capture smtplib debug output to a StringIO buffer.
42
+
43
+ smtplib.set_debuglevel() writes to stderr. This context manager
44
+ temporarily redirects stderr to capture the debug output.
45
+
46
+ Yields:
47
+ StringIO buffer containing captured debug output.
48
+ """
49
+ buffer = io.StringIO()
50
+ old_stderr = sys.stderr
51
+ try:
52
+ sys.stderr = buffer
53
+ yield buffer
54
+ finally:
55
+ sys.stderr = old_stderr
56
+
57
+
58
+ def _extract_cn_from_cert_field(field: Any) -> str | None:
59
+ """Extract commonName from a certificate subject or issuer field.
60
+
61
+ Certificate fields (subject, issuer) are nested tuples of RDNs (Relative
62
+ Distinguished Names), each containing attribute tuples like ('commonName', 'value').
63
+
64
+ Args:
65
+ field: Nested tuple structure from peer_cert['subject'] or ['issuer'].
66
+
67
+ Returns:
68
+ The commonName value if found, None otherwise.
69
+ """
70
+ if not field or not isinstance(field, tuple):
71
+ return None
72
+ for rdn in field:
73
+ if not isinstance(rdn, tuple):
74
+ continue
75
+ for attr in rdn:
76
+ if isinstance(attr, tuple) and len(attr) >= 2 and attr[0] == "commonName":
77
+ return str(attr[1])
78
+ return None
79
+
80
+
81
+ def _extract_cipher_info(sock: ssl.SSLSocket) -> dict[str, Any]:
82
+ """Extract cipher information from SSL socket.
83
+
84
+ Args:
85
+ sock: The SSL socket after handshake.
86
+
87
+ Returns:
88
+ Dictionary with cipher_name, cipher_protocol, cipher_bits.
89
+ """
90
+ info: dict[str, Any] = {}
91
+ try:
92
+ cipher = sock.cipher()
93
+ if cipher:
94
+ info["cipher_name"] = cipher[0]
95
+ info["cipher_protocol"] = cipher[1]
96
+ info["cipher_bits"] = cipher[2]
97
+ except Exception: # pylint: disable=broad-exception-caught
98
+ pass
99
+ return info
100
+
101
+
102
+ def _extract_cert_info(sock: ssl.SSLSocket) -> dict[str, Any]:
103
+ """Extract peer certificate information from SSL socket.
104
+
105
+ Args:
106
+ sock: The SSL socket after handshake.
107
+
108
+ Returns:
109
+ Dictionary with peer_cn, issuer_cn, valid_from, valid_until.
110
+ """
111
+ info: dict[str, Any] = {}
112
+ try:
113
+ peer_cert = sock.getpeercert()
114
+ if peer_cert:
115
+ peer_cn = _extract_cn_from_cert_field(peer_cert.get("subject"))
116
+ if peer_cn:
117
+ info["peer_cn"] = peer_cn
118
+ issuer_cn = _extract_cn_from_cert_field(peer_cert.get("issuer"))
119
+ if issuer_cn:
120
+ info["issuer_cn"] = issuer_cn
121
+ if "notBefore" in peer_cert:
122
+ info["valid_from"] = peer_cert["notBefore"]
123
+ if "notAfter" in peer_cert:
124
+ info["valid_until"] = peer_cert["notAfter"]
125
+ except Exception: # pylint: disable=broad-exception-caught
126
+ pass
127
+ return info
128
+
129
+
130
+ def _extract_ssl_info(sock: ssl.SSLSocket | None) -> dict[str, Any]:
131
+ """Extract SSL/TLS session information for trace logging.
132
+
133
+ Args:
134
+ sock: The SSL socket after handshake.
135
+
136
+ Returns:
137
+ Dictionary with SSL session details (version, cipher, peer cert).
138
+ """
139
+ if sock is None:
140
+ return {}
141
+
142
+ info: dict[str, Any] = {}
143
+
144
+ try:
145
+ info["version"] = sock.version()
146
+ except Exception: # pylint: disable=broad-exception-caught
147
+ info["version"] = "unknown"
148
+
149
+ info.update(_extract_cipher_info(sock))
150
+ info.update(_extract_cert_info(sock))
151
+
152
+ return info
153
+
154
+
155
+ def _log_ssl_info(client: smtplib.SMTP | smtplib.SMTP_SSL, protocol_label: str) -> None:
156
+ """Log SSL/TLS session information at TRACE level.
157
+
158
+ Args:
159
+ client: The SMTP client with an SSL socket.
160
+ protocol_label: Label for the protocol (e.g., "SSL" or "TLS").
161
+ """
162
+ ssl_sock = getattr(client, "sock", None)
163
+ if ssl_sock is None or not hasattr(ssl_sock, "version"):
164
+ return
165
+
166
+ ssl_info = _extract_ssl_info(ssl_sock)
167
+ if not ssl_info:
168
+ return
169
+
170
+ log.log(
171
+ TRACE_LEVEL,
172
+ "[SMTP] %s: %s, cipher=%s (%d bits)",
173
+ protocol_label,
174
+ ssl_info.get("version", "unknown"),
175
+ ssl_info.get("cipher_name", "unknown"),
176
+ ssl_info.get("cipher_bits", 0),
177
+ )
178
+ if "peer_cn" in ssl_info:
179
+ log.log(
180
+ TRACE_LEVEL,
181
+ "[SMTP] %s peer: CN=%s, issuer=%s",
182
+ protocol_label,
183
+ ssl_info.get("peer_cn", "unknown"),
184
+ ssl_info.get("issuer_cn", "unknown"),
185
+ )
186
+
187
+
188
+ def _log_smtp_debug_output(buffer: io.StringIO) -> None:
189
+ """Parse and log captured smtplib debug output at TRACE level.
190
+
191
+ Args:
192
+ buffer: StringIO containing captured debug output.
193
+ """
194
+ if not log.isEnabledFor(TRACE_LEVEL):
195
+ return
196
+
197
+ content = buffer.getvalue()
198
+ if not content:
199
+ return
200
+
201
+ for line in content.strip().split("\n"):
202
+ line = line.strip()
203
+ if not line:
204
+ continue
205
+ # smtplib debug format: "send: 'EHLO ...'" or "reply: retcode (...);"
206
+ if line.startswith("send:"):
207
+ log.log(TRACE_LEVEL, "[SMTP] >>> %s", line[5:].strip().strip("'\""))
208
+ elif line.startswith("reply:"):
209
+ log.log(TRACE_LEVEL, "[SMTP] <<< %s", line[6:].strip())
210
+ else:
211
+ log.log(TRACE_LEVEL, "[SMTP] %s", line)
212
+
213
+
214
+ @dataclass(frozen=True, slots=True)
215
+ class SMTPCredentials:
216
+ """SMTP authentication bundle."""
217
+
218
+ username: str
219
+ password: str | None = None
220
+
221
+
222
+ @dataclass(frozen=True, slots=True)
223
+ class SMTPSecurity:
224
+ """SMTP security preferences."""
225
+
226
+ use_ssl: bool = False
227
+ use_starttls: bool = True
228
+ ssl_context: ssl.SSLContext | None = None
229
+
230
+
231
+ class SMTPTransport(MailTransport):
232
+ """Deliver messages using the standard SMTP protocol."""
233
+
234
+ def __init__(
235
+ self,
236
+ host: str,
237
+ port: int = 587,
238
+ *,
239
+ credentials: SMTPCredentials | None = None,
240
+ security: SMTPSecurity | None = None,
241
+ timeout: float | None = None,
242
+ ) -> None:
243
+ """Configure connection parameters for the SMTP backend."""
244
+ self._host = host
245
+ self._port = port
246
+ self._timeout = timeout
247
+
248
+ self._username = credentials.username if credentials else None
249
+ self._password = credentials.password if credentials else None
250
+
251
+ effective_security = security or SMTPSecurity()
252
+ self._use_ssl = effective_security.use_ssl
253
+ self._use_starttls = effective_security.use_starttls if not effective_security.use_ssl else False
254
+ self._ssl_context = effective_security.ssl_context or ssl.create_default_context()
255
+
256
+ def send(self, message: EmailMessage) -> None:
257
+ """Send *message* through the configured SMTP server.
258
+
259
+ When TRACE logging is enabled, detailed session information is logged
260
+ including SMTP commands, SSL/TLS handshake details, and message envelope.
261
+ """
262
+ trace_enabled = log.isEnabledFor(TRACE_LEVEL)
263
+ client_kwargs: dict[str, Any] = {"host": self._host, "port": self._port, "timeout": self._timeout}
264
+ client_cls = smtplib.SMTP_SSL if self._use_ssl else smtplib.SMTP
265
+ protocol = "SMTP_SSL" if self._use_ssl else "SMTP"
266
+
267
+ if trace_enabled:
268
+ log.log(TRACE_LEVEL, "[SMTP] Connecting to %s:%d (%s)", self._host, self._port, protocol)
269
+
270
+ try:
271
+ with _capture_smtp_debug() as debug_buffer, client_cls(**client_kwargs) as client:
272
+ # Enable smtplib debug if trace is on
273
+ if trace_enabled:
274
+ client.set_debuglevel(2)
275
+
276
+ # Initial EHLO
277
+ client.ehlo()
278
+
279
+ # Log initial SSL info for SMTP_SSL
280
+ if trace_enabled and self._use_ssl:
281
+ _log_ssl_info(client, "SSL")
282
+
283
+ # STARTTLS upgrade
284
+ if self._use_starttls and client.has_extn("STARTTLS"):
285
+ if trace_enabled:
286
+ log.log(TRACE_LEVEL, "[SMTP] Upgrading to TLS via STARTTLS")
287
+ client.starttls(context=self._ssl_context)
288
+ client.ehlo()
289
+
290
+ # Log SSL info after STARTTLS
291
+ if trace_enabled:
292
+ _log_ssl_info(client, "TLS")
293
+
294
+ # Authentication
295
+ if self._username:
296
+ if trace_enabled:
297
+ log.log(TRACE_LEVEL, "[SMTP] Authenticating as: %s", self._username)
298
+ client.login(self._username, self._password or "")
299
+ if trace_enabled:
300
+ log.log(TRACE_LEVEL, "[SMTP] Authentication successful")
301
+
302
+ # Send message
303
+ if trace_enabled:
304
+ sender = message.get("From", "unknown")
305
+ recipients = message.get("To", "unknown")
306
+ subject = message.get("Subject", "(no subject)")
307
+ log.log(TRACE_LEVEL, "[SMTP] MAIL FROM: %s", sender)
308
+ log.log(TRACE_LEVEL, "[SMTP] RCPT TO: %s", recipients)
309
+ log.log(TRACE_LEVEL, "[SMTP] Subject: %s", subject)
310
+
311
+ client.send_message(message)
312
+
313
+ if trace_enabled:
314
+ log.log(TRACE_LEVEL, "[SMTP] Message sent successfully")
315
+
316
+ # Log captured smtplib debug output
317
+ if trace_enabled:
318
+ _log_smtp_debug_output(debug_buffer)
319
+
320
+ except smtplib.SMTPException as exc: # pragma: no cover - network dependent
321
+ if trace_enabled:
322
+ log.log(TRACE_LEVEL, "[SMTP] Error: %s", exc)
323
+ raise MailTransportError(str(exc)) from exc
324
+
325
+
326
+ __all__ = ["SMTPCredentials", "SMTPSecurity", "SMTPTransport"]
kstlib/meta.py ADDED
@@ -0,0 +1,72 @@
1
+ """Metadata and constants for kstlib package.
2
+
3
+ This module defines the package metadata including name, version, author information,
4
+ and ASCII art logo used in CLI output.
5
+ """
6
+
7
+ __logo__ = (
8
+ """
9
+ {{ FRM }}################################################################################################## {{ G }}### {{ R }}### {{ FRM }}####
10
+ ################################################################################################## {{ G }}### {{ R }}### {{ FRM }}####
11
+ ## ##
12
+ ## {{ R }}################## .#######: {{ G }}.######. {{ R }}########################################## {{ FRM }}##
13
+ ## {{ R }}##################..#########. {{ G }}.#########. {{ R }}########################################## {{ FRM }}##
14
+ ## {{ R }}### ########. {{ G }}:###########: {{ R }}### {{ FRM }}##
15
+ ## {{ R }}### ######. {{ G }}.##########:. {{ R }}### {{ FRM }}##
16
+ ## {{ R }}### ####. {{ G }}.#########:. {{ R }}### {{ FRM }}##
17
+ ## {{ R }}### ##. {{ G }}.####### {{ R }}### {{ FRM }}##
18
+ ## {{ R }}### " {{ G }}.###### {{ R }}### {{ FRM }}##
19
+ ## {{ R }}### {{ G }}.:###### {{ R }}############### {{ FRM }}##
20
+ ## {{ R }}### {{ G }}.##########:. .:#######. {{ R }}############### {{ FRM }}##
21
+ ## {{ R }}### {{ G }}:########################################. {{ R }}### {{ FRM }}##
22
+ ## {{ R }}### {{ G }}:################# {{ FRM }}L I B {{ G }}##################: {{ R }}### {{ FRM }}##
23
+ ## {{ R }}### {{ G }}.########################################. {{ R }}### {{ FRM }}##
24
+ ## {{ R }}### {{ G }}:######:. ###########. {{ R }}### {{ FRM }}##
25
+ ## {{ R }}### {{ G }}:######:. {{ R }}### {{ FRM }}##
26
+ ## {{ R }}### . {{ G }}:######:. {{ R }}. ### {{ FRM }}##
27
+ ## {{ R }}### ## {{ G }}.:######. {{ R }}## ### {{ FRM }}##
28
+ ## {{ R }}### #### {{ G }}.:#########. {{ R }}### ### {{ FRM }}##
29
+ ## {{ R }}### ###### {{ G }}:###########: {{ R }}### ### {{ FRM }}##
30
+ ## {{ R }}### ######## {{ G }}:###########: {{ R }}### ### {{ FRM }}##
31
+ ## {{ R }}##################..##########. {{ G }}":#########" {{ R }}################## {{ FRM }}##
32
+ ## {{ R }}################## .#########: {{ G }}":######:" {{ R }}################## {{ FRM }}##
33
+ ## ##
34
+ ###################################################################################################[ Michel TRUONG ]####
35
+ ########################################################################################################################
36
+ """.replace("{{ FRM }}", "[bright_black]")
37
+ .replace("{{ G }}", "[chartreuse2]")
38
+ .replace("{{ R }}", "[deep_pink2]")
39
+ )
40
+
41
+ __app_name__ = "kstlib"
42
+ __version__ = "1.0.1"
43
+ __description__ = (
44
+ "Config-driven helpers for Python projects (dynamic config, secure secrets, preset logging, and more…)"
45
+ )
46
+ __author__ = "Michel TRUONG"
47
+ __email__ = "michel.truong@gmail.com"
48
+ __url__ = "https://kstlib.io"
49
+ __keywords__ = ["kstlib"]
50
+ __classifiers__ = [
51
+ "Development Status :: 5 - Production/Stable",
52
+ "Intended Audience :: Developers",
53
+ "License :: OSI Approved :: MIT License",
54
+ "Programming Language :: Python :: 3",
55
+ "Programming Language :: Python :: 3.10",
56
+ "Programming Language :: Python :: 3.11",
57
+ "Programming Language :: Python :: 3.12",
58
+ "Programming Language :: Python :: 3.13",
59
+ "Programming Language :: Python :: 3.14",
60
+ ]
61
+ __license_type__ = "MIT"
62
+ __license__ = """
63
+ MIT License
64
+
65
+ Copyright © • 2025 • Michel TRUONG
66
+
67
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
68
+
69
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
70
+
71
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
72
+ """
@@ -0,0 +1,88 @@
1
+ """Metrics and timing utilities for measuring execution performance.
2
+
3
+ This module provides a unified decorator and tools for:
4
+
5
+ - **Time Measurement**: Track execution time of functions and code blocks
6
+ - **Memory Tracking**: Monitor peak memory usage with tracemalloc
7
+ - **Call Statistics**: Track call count, avg/min/max durations
8
+ - **Step Tracking**: Numbered step tracking with summary
9
+
10
+ All behavior is config-driven with sensible defaults.
11
+
12
+ Examples:
13
+ Unified metrics decorator (config defaults):
14
+
15
+ >>> from kstlib.metrics import metrics
16
+ >>> @metrics
17
+ ... def slow_function():
18
+ ... return sum(range(1000000))
19
+ >>> slow_function() # doctest: +SKIP
20
+ [slow_function] ⏱ 0.023s | 🧠 Peak: 128 KB
21
+
22
+ Step tracking for pipelines:
23
+
24
+ >>> from kstlib.metrics import metrics, metrics_summary, clear_metrics
25
+ >>> @metrics(step=True)
26
+ ... def load_data():
27
+ ... pass
28
+ >>> @metrics(step=True, title="Process records")
29
+ ... def process():
30
+ ... pass
31
+ >>> load_data() # doctest: +SKIP
32
+ [STEP 1] load_data ⏱ 0.001s
33
+ >>> process() # doctest: +SKIP
34
+ [STEP 2] Process records ⏱ 0.002s
35
+ >>> metrics_summary() # doctest: +SKIP
36
+ # Displays summary table with all steps
37
+
38
+ Context manager usage:
39
+
40
+ >>> from kstlib.metrics import metrics_context
41
+ >>> with metrics_context("Data loading"): # doctest: +SKIP
42
+ ... data = load_large_file()
43
+ [Data loading] ⏱ 2.34s | 🧠 Peak: 512 MB
44
+
45
+ Manual stopwatch:
46
+
47
+ >>> from kstlib.metrics import Stopwatch
48
+ >>> sw = Stopwatch("Pipeline")
49
+ >>> sw.start() # doctest: +SKIP
50
+ >>> # ... work ...
51
+ >>> sw.lap("Step 1") # doctest: +SKIP
52
+ >>> sw.stop() # doctest: +SKIP
53
+ >>> sw.summary() # doctest: +SKIP
54
+ """
55
+
56
+ from kstlib.metrics.decorators import (
57
+ CallStats,
58
+ MetricsRecord,
59
+ Stopwatch,
60
+ call_stats,
61
+ clear_metrics,
62
+ get_all_call_stats,
63
+ get_call_stats,
64
+ get_metrics,
65
+ metrics,
66
+ metrics_context,
67
+ metrics_summary,
68
+ print_all_call_stats,
69
+ reset_all_call_stats,
70
+ )
71
+ from kstlib.metrics.exceptions import MetricsError
72
+
73
+ __all__ = [
74
+ "CallStats",
75
+ "MetricsError",
76
+ "MetricsRecord",
77
+ "Stopwatch",
78
+ "call_stats",
79
+ "clear_metrics",
80
+ "get_all_call_stats",
81
+ "get_call_stats",
82
+ "get_metrics",
83
+ "metrics",
84
+ "metrics_context",
85
+ "metrics_summary",
86
+ "print_all_call_stats",
87
+ "reset_all_call_stats",
88
+ ]