FastSpine 1.0.0__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.
- fastspine/__init__.py +48 -0
- fastspine/abstract/owner_base.py +16 -0
- fastspine/alembic/__init__.py +4 -0
- fastspine/alembic/alembic.py +95 -0
- fastspine/alembic/config.py +40 -0
- fastspine/boostrap.py +78 -0
- fastspine/cache/cache_decorater.py +264 -0
- fastspine/cache/cache_encoder.py +87 -0
- fastspine/cache/cache_exception.py +4 -0
- fastspine/cache/cache_model.py +32 -0
- fastspine/cache/cache_service.py +144 -0
- fastspine/cache/key_builder.py +134 -0
- fastspine/cache/redis_cache.py +158 -0
- fastspine/celery/base_task.py +106 -0
- fastspine/celery/engine.py +52 -0
- fastspine/cli/scoped_typer.py +47 -0
- fastspine/ctx/ctx_pool.py +73 -0
- fastspine/database/engine.py +131 -0
- fastspine/decorators/contextualize_decorator.py +54 -0
- fastspine/decorators/retry_decorator.py +66 -0
- fastspine/decorators/upsert_decorator.py +107 -0
- fastspine/dependencies/database.py +193 -0
- fastspine/dependencies/profiler.py +37 -0
- fastspine/dependencies/repository_manager.py +202 -0
- fastspine/dependencies/services.py +140 -0
- fastspine/exception/access_exception.py +13 -0
- fastspine/exception/action_not_allowed_exception.py +13 -0
- fastspine/exception/base_app_exception.py +28 -0
- fastspine/exception/exception_handler.py +9 -0
- fastspine/exception/not_found_exception.py +13 -0
- fastspine/exception/security_exception.py +13 -0
- fastspine/exception/soft_delete_exception.py +13 -0
- fastspine/lib/__init__.py +4 -0
- fastspine/lib/contextualize.py +352 -0
- fastspine/lib/profiler.py +284 -0
- fastspine/mailer/mailer_service.py +44 -0
- fastspine/middleware/request_middleware.py +67 -0
- fastspine/middleware/session_middleware.py +38 -0
- fastspine/mixins/__init__.py +4 -0
- fastspine/mixins/representable.py +12 -0
- fastspine/mixins/soft_delete.py +41 -0
- fastspine/mixins/timestamps.py +35 -0
- fastspine/models/base.py +18 -0
- fastspine/redis/client.py +23 -0
- fastspine/repositories/abstract_repository.py +267 -0
- fastspine/repositories/base_repository.py +422 -0
- fastspine/repositories/external_base_repository.py +12 -0
- fastspine/repositories/repository_manager.py +101 -0
- fastspine/schemas/pagination_model.py +26 -0
- fastspine/services/api_service.py +292 -0
- fastspine/services/base_service.py +18 -0
- fastspine/settings/__init__.py +74 -0
- fastspine/settings/app_settings.py +5 -0
- fastspine/settings/cache_settings.py +32 -0
- fastspine/settings/celery_settings.py +10 -0
- fastspine/settings/mailer_settings.py +12 -0
- fastspine/settings/profiler_settings.py +10 -0
- fastspine/types/__init__.py +3 -0
- fastspine/types/types.py +6 -0
- fastspine/util/class_util.py +110 -0
- fastspine/util/conversion.py +37 -0
- fastspine/util/dataframe_util.py +30 -0
- fastspine/util/dates.py +34 -0
- fastspine/util/debug_util.py +29 -0
- fastspine/util/emails.py +14 -0
- fastspine/util/files.py +29 -0
- fastspine/util/math.py +3 -0
- fastspine-1.0.0.dist-info/METADATA +372 -0
- fastspine-1.0.0.dist-info/RECORD +71 -0
- fastspine-1.0.0.dist-info/WHEEL +4 -0
- fastspine-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import logging
|
|
3
|
+
import logging.handlers
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from contextvars import ContextVar
|
|
9
|
+
from inspect import iscoroutinefunction
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, AsyncGenerator, Dict, Generator, Optional
|
|
12
|
+
|
|
13
|
+
import ecs_logging
|
|
14
|
+
from termcolor import colored
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import celery
|
|
18
|
+
import celery.signals # Manual import needed
|
|
19
|
+
except ImportError:
|
|
20
|
+
celery = None
|
|
21
|
+
|
|
22
|
+
_EMPTY_CONTEXT: Dict[str, Any] = {}
|
|
23
|
+
log_context: ContextVar[Dict[str, Any]] = ContextVar("fastspine_log_context", default=_EMPTY_CONTEXT)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FastSpineFormatter(logging.Formatter):
|
|
27
|
+
"""Custom formatter class with colors, timestamps, log levels, and logger names."""
|
|
28
|
+
|
|
29
|
+
NAME_WIDTH: int = 16
|
|
30
|
+
|
|
31
|
+
FORMATS = {
|
|
32
|
+
logging.DEBUG: (colored("%(asctime)s", "blue") + f" DEBUG %(name)-{NAME_WIDTH:d}s %(message)s"),
|
|
33
|
+
logging.INFO: (
|
|
34
|
+
colored("%(asctime)s", "blue")
|
|
35
|
+
+ colored(" INFO ", "white", attrs=["bold"])
|
|
36
|
+
+ f" %(name)-{NAME_WIDTH:d}s %(message)s"
|
|
37
|
+
),
|
|
38
|
+
logging.WARNING: (
|
|
39
|
+
colored("%(asctime)s", "blue")
|
|
40
|
+
+ colored(" WARN ", "yellow", attrs=["bold"])
|
|
41
|
+
+ colored(f" %(name)-{NAME_WIDTH:d}s %(message)s", "yellow")
|
|
42
|
+
),
|
|
43
|
+
logging.ERROR: (
|
|
44
|
+
colored("%(asctime)s", "light_red")
|
|
45
|
+
+ colored(" ERROR", "red", attrs=["bold"])
|
|
46
|
+
+ colored(f" %(name)-{NAME_WIDTH:d}s %(message)s", "red")
|
|
47
|
+
),
|
|
48
|
+
logging.CRITICAL: (
|
|
49
|
+
colored("%(asctime)s", "black", "on_magenta")
|
|
50
|
+
+ colored(" CRIT ", "black", "on_magenta", attrs=["bold"])
|
|
51
|
+
+ colored(f" %(name)-{NAME_WIDTH:d}s %(message)s", "black", "on_magenta")
|
|
52
|
+
),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
def format(self, record):
|
|
56
|
+
"""Format the log record with colors, timestamps, log levels, and logger names."""
|
|
57
|
+
log_fmt = self.FORMATS.get(record.levelno)
|
|
58
|
+
formatter = logging.Formatter(log_fmt)
|
|
59
|
+
|
|
60
|
+
# Overwrite milisecond format to work with a dot.
|
|
61
|
+
formatter.default_msec_format = "%s.%03d"
|
|
62
|
+
return formatter.format(record)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def setup_logging(
|
|
66
|
+
log_level: str = "INFO",
|
|
67
|
+
file_pattern: str = "logs/elastic-{hostname}.log",
|
|
68
|
+
max_bytes: int = 100_000_000,
|
|
69
|
+
backup_count: int = 2,
|
|
70
|
+
**kwargs,
|
|
71
|
+
):
|
|
72
|
+
"""Set up logging with a custom formatter and a rotating file handler.
|
|
73
|
+
|
|
74
|
+
The log_level string is a space-separated list of log level instructions. See
|
|
75
|
+
`parse_log_level()` for more information. The default value is INFO.
|
|
76
|
+
The environment variable `LOG_LEVEL` is used and has precedence over the argument.
|
|
77
|
+
|
|
78
|
+
The file pattern is a string that specifies the path to the log file. The
|
|
79
|
+
format-string syntax can be used to inject the process ID (pid) or hostname
|
|
80
|
+
(hostname) into the file path.
|
|
81
|
+
|
|
82
|
+
The arguments max_bytes and backup_count are passed to the rotating file handler.
|
|
83
|
+
|
|
84
|
+
Celery imposes it's own logging configuration. However, if `import celery` succeeds,
|
|
85
|
+
`setup_logging()` instructs celery to use the custom logging configuration.
|
|
86
|
+
"""
|
|
87
|
+
log_level = os.environ.get("LOG_LEVEL", log_level)
|
|
88
|
+
|
|
89
|
+
# Fail early if the log level is invalid.
|
|
90
|
+
log_levels = parse_log_level(log_level)
|
|
91
|
+
|
|
92
|
+
# Log file
|
|
93
|
+
pid = os.getpid()
|
|
94
|
+
hostname = os.uname().nodename
|
|
95
|
+
ecs_filename = file_pattern.format(pid=pid, hostname=hostname)
|
|
96
|
+
Path(ecs_filename).parent.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
|
|
98
|
+
# Monkey patch the makeRecord method to allow for extra fields in the log record.
|
|
99
|
+
# Monkey-patch is used instead of subclassing because the patch will affect existing
|
|
100
|
+
# and future loggers, as well as the root logger.
|
|
101
|
+
if hasattr(logging, "_loggerClass"):
|
|
102
|
+
logging._loggerClass.makeRecord = make_record
|
|
103
|
+
else:
|
|
104
|
+
raise RuntimeError("logging module does not have _loggerClass attribute")
|
|
105
|
+
# ECS logging
|
|
106
|
+
ecs_handler = logging.handlers.RotatingFileHandler(ecs_filename, maxBytes=max_bytes, backupCount=backup_count)
|
|
107
|
+
ecs_handler.setFormatter(
|
|
108
|
+
ecs_logging.StdlibFormatter(
|
|
109
|
+
# add extra fields from kwargs
|
|
110
|
+
extra=kwargs,
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Stdout logging
|
|
115
|
+
stdout_handler = logging.StreamHandler()
|
|
116
|
+
stdout_handler.setFormatter(FastSpineFormatter())
|
|
117
|
+
|
|
118
|
+
# This makes sure DEBUG-level messages go to elastic if the root or model-specific log
|
|
119
|
+
# level is set to DEBUG.
|
|
120
|
+
ecs_handler.setLevel(logging.DEBUG)
|
|
121
|
+
stdout_handler.setLevel(logging.DEBUG)
|
|
122
|
+
|
|
123
|
+
logger = logging.getLogger("root")
|
|
124
|
+
logger.addHandler(ecs_handler)
|
|
125
|
+
logger.addHandler(stdout_handler)
|
|
126
|
+
|
|
127
|
+
# Set log levels
|
|
128
|
+
for module, level in log_levels.items():
|
|
129
|
+
logger = logging.getLogger(module)
|
|
130
|
+
logger.setLevel(level)
|
|
131
|
+
|
|
132
|
+
if celery:
|
|
133
|
+
# Overwrite logging setup handler
|
|
134
|
+
celery.signals.setup_logging.connect(_on_setup_logging)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _on_setup_logging(**kwargs: Any) -> None:
|
|
138
|
+
"""No-op function to overwrite Celery's logging setup."""
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def parse_log_level(log_level: str) -> dict[str, int]:
|
|
143
|
+
"""Parse a log level string and return a dictionary of log levels for each module.
|
|
144
|
+
|
|
145
|
+
The log level string is a space-separated list of log level instructions. The first
|
|
146
|
+
instruction sets the root log level, and the rest set the log levels for specific
|
|
147
|
+
modules. Each instruction after the root is in the form `module=LEVEL`, where
|
|
148
|
+
`module` is the name of the logger and `LEVEL` is the log level. Whitespace around
|
|
149
|
+
instructions is ignored. The log level for the root logger is mandatory. All other
|
|
150
|
+
instructions are optional.
|
|
151
|
+
|
|
152
|
+
If an invalid log level instruction is provided, a ValueError is raised. By default,
|
|
153
|
+
the following log level are supported: DEBUG, INFO, WARNING, ERROR, CRITICAL.
|
|
154
|
+
|
|
155
|
+
The return value is a dictionary where the keys are the module names and the values
|
|
156
|
+
are the integer-valued log levels.
|
|
157
|
+
|
|
158
|
+
Examples:
|
|
159
|
+
To set to the universal log level to WARNING, the log level string would
|
|
160
|
+
be `"WARNING"`.
|
|
161
|
+
|
|
162
|
+
To set the root log level to INFO and the log level for the `app` module
|
|
163
|
+
to DEBUG, the log level string would be `"INFO app=DEBUG"`.
|
|
164
|
+
|
|
165
|
+
To set the root log level to INFO and the log level of the `library`
|
|
166
|
+
module to ERROR, the log level string would be `"INFO library=ERROR"`.
|
|
167
|
+
"""
|
|
168
|
+
log_consts = {
|
|
169
|
+
"DEBUG": logging.DEBUG,
|
|
170
|
+
"INFO": logging.INFO,
|
|
171
|
+
"WARNING": logging.WARNING,
|
|
172
|
+
"ERROR": logging.ERROR,
|
|
173
|
+
"CRITICAL": logging.CRITICAL,
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
mapping: dict[str, Any] = {}
|
|
177
|
+
root_instruction, *instructions = re.split(r"\s+", log_level.strip())
|
|
178
|
+
|
|
179
|
+
if root_instruction not in log_consts:
|
|
180
|
+
raise ValueError(f"Invalid root log level: {root_instruction}")
|
|
181
|
+
mapping["root"] = log_consts[root_instruction]
|
|
182
|
+
|
|
183
|
+
for instruction in instructions:
|
|
184
|
+
match = re.match(r"([a-zA-Z0-9_.]+)=([A-Z]+)", instruction)
|
|
185
|
+
if not match:
|
|
186
|
+
raise ValueError(f"Invalid log instruction: {instruction}")
|
|
187
|
+
module = match.group(1)
|
|
188
|
+
level = match.group(2)
|
|
189
|
+
|
|
190
|
+
if level not in log_consts:
|
|
191
|
+
raise ValueError(f"Invalid log level: {level}")
|
|
192
|
+
mapping[module] = log_consts[level]
|
|
193
|
+
|
|
194
|
+
return mapping
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@contextlib.contextmanager
|
|
198
|
+
def contextualize(**kwargs: Any) -> Generator[Dict[str, Any], None, None]:
|
|
199
|
+
"""Add the current context to the logger with enhanced tracking.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
**kwargs: Context variables to add to logging context
|
|
203
|
+
|
|
204
|
+
Yields:
|
|
205
|
+
Dict containing the current logging context
|
|
206
|
+
|
|
207
|
+
Example:
|
|
208
|
+
with contextualize(user_id=123, request_id="abc"):
|
|
209
|
+
logger.info("Processing request") # Will include user_id and request_id
|
|
210
|
+
"""
|
|
211
|
+
# Generate correlation_id if not provided
|
|
212
|
+
if "correlation_id" not in kwargs:
|
|
213
|
+
kwargs["correlation_id"] = str(uuid.uuid4())
|
|
214
|
+
|
|
215
|
+
# Add timestamp for context creation
|
|
216
|
+
if "context_created_at" not in kwargs:
|
|
217
|
+
kwargs["context_created_at"] = time.time()
|
|
218
|
+
|
|
219
|
+
current_context = log_context.get()
|
|
220
|
+
new_context = {**current_context, **kwargs}
|
|
221
|
+
token = log_context.set(new_context)
|
|
222
|
+
|
|
223
|
+
try:
|
|
224
|
+
yield new_context
|
|
225
|
+
finally:
|
|
226
|
+
log_context.reset(token)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@contextlib.asynccontextmanager
|
|
230
|
+
async def acontextualize(**kwargs: Any) -> AsyncGenerator[Dict[str, Any], None]:
|
|
231
|
+
"""Async version of contextualize for use with async functions.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
**kwargs: Context variables to add to logging context
|
|
235
|
+
|
|
236
|
+
Yields:
|
|
237
|
+
Dict containing the current logging context
|
|
238
|
+
|
|
239
|
+
Example:
|
|
240
|
+
async with acontextualize(user_id=123, request_id="abc"):
|
|
241
|
+
logger.info("Processing async request")
|
|
242
|
+
"""
|
|
243
|
+
# Generate correlation_id if not provided
|
|
244
|
+
if "correlation_id" not in kwargs:
|
|
245
|
+
kwargs["correlation_id"] = str(uuid.uuid4())
|
|
246
|
+
|
|
247
|
+
# Add timestamp for context creation
|
|
248
|
+
if "context_created_at" not in kwargs:
|
|
249
|
+
kwargs["context_created_at"] = time.time()
|
|
250
|
+
|
|
251
|
+
current_context = log_context.get()
|
|
252
|
+
new_context = {**current_context, **kwargs}
|
|
253
|
+
token = log_context.set(new_context)
|
|
254
|
+
|
|
255
|
+
try:
|
|
256
|
+
yield new_context
|
|
257
|
+
finally:
|
|
258
|
+
log_context.reset(token)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def get_current_context() -> Dict[str, Any]:
|
|
262
|
+
"""Get the current logging context.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
Dictionary containing current context variables
|
|
266
|
+
"""
|
|
267
|
+
return log_context.get().copy()
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def update_context(**kwargs: Any) -> None:
|
|
271
|
+
"""Update the current context with new values.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
**kwargs: Context variables to add or update
|
|
275
|
+
|
|
276
|
+
Note:
|
|
277
|
+
This modifies the current context in-place. Use with caution
|
|
278
|
+
in concurrent environments.
|
|
279
|
+
"""
|
|
280
|
+
current_context = log_context.get()
|
|
281
|
+
new_context = {**current_context, **kwargs}
|
|
282
|
+
log_context.set(new_context)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def clear_context() -> None:
|
|
286
|
+
"""Clear the current logging context."""
|
|
287
|
+
log_context.set({})
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def with_context(context: Dict[str, Any]):
|
|
291
|
+
"""Decorator to add context to a function.
|
|
292
|
+
|
|
293
|
+
Args:
|
|
294
|
+
context: Context variables to add
|
|
295
|
+
|
|
296
|
+
Example:
|
|
297
|
+
@with_context({"module": "user_service"})
|
|
298
|
+
def process_user(user_id):
|
|
299
|
+
logger.info(f"Processing user {user_id}")
|
|
300
|
+
"""
|
|
301
|
+
|
|
302
|
+
def decorator(func):
|
|
303
|
+
if iscoroutinefunction(func):
|
|
304
|
+
|
|
305
|
+
async def async_wrapper(*args, **kwargs):
|
|
306
|
+
async with acontextualize(**context):
|
|
307
|
+
return await func(*args, **kwargs)
|
|
308
|
+
|
|
309
|
+
return async_wrapper
|
|
310
|
+
|
|
311
|
+
def sync_wrapper(*args, **kwargs):
|
|
312
|
+
with contextualize(**context):
|
|
313
|
+
return func(*args, **kwargs)
|
|
314
|
+
|
|
315
|
+
return sync_wrapper
|
|
316
|
+
|
|
317
|
+
return decorator
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def make_record(
|
|
321
|
+
self,
|
|
322
|
+
name: str,
|
|
323
|
+
level: int,
|
|
324
|
+
fn: str,
|
|
325
|
+
lno: int,
|
|
326
|
+
msg: Any,
|
|
327
|
+
args: tuple,
|
|
328
|
+
exc_info,
|
|
329
|
+
func: Optional[str] = None,
|
|
330
|
+
extra: Optional[Dict[str, Any]] = None,
|
|
331
|
+
sinfo: Optional[str] = None,
|
|
332
|
+
) -> logging.LogRecord:
|
|
333
|
+
"""Enhanced factory method for creating LogRecords with context.
|
|
334
|
+
|
|
335
|
+
This method is monkey-patched into the logging system to automatically
|
|
336
|
+
include context variables in all log records.
|
|
337
|
+
"""
|
|
338
|
+
rv = logging.getLogRecordFactory()(name, level, fn, lno, msg, args, exc_info, func, sinfo)
|
|
339
|
+
context = log_context.get()
|
|
340
|
+
|
|
341
|
+
if extra is None:
|
|
342
|
+
extra = {}
|
|
343
|
+
|
|
344
|
+
# Merge context with extra, giving priority to extra
|
|
345
|
+
merged_extra = {**context, **extra}
|
|
346
|
+
|
|
347
|
+
# Add timing information if context was created with timestamp
|
|
348
|
+
if "context_created_at" in context:
|
|
349
|
+
merged_extra["context_duration"] = time.time() - context["context_created_at"]
|
|
350
|
+
|
|
351
|
+
rv.__dict__["extra"] = merged_extra
|
|
352
|
+
return rv
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from contextlib import contextmanager
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Generator, List, Tuple
|
|
9
|
+
|
|
10
|
+
import psutil
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ProfileMetrics:
|
|
17
|
+
"""Container for profiling metrics."""
|
|
18
|
+
|
|
19
|
+
duration: float = 0.0
|
|
20
|
+
memory_usage: float = 0.0
|
|
21
|
+
peak_memory: float = 0.0
|
|
22
|
+
call_count: int = 0
|
|
23
|
+
timestamp: float = field(default_factory=time.time)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Profiler:
|
|
27
|
+
"""Advanced performance profiler with timing, memory tracking, and checkpoint capabilities.
|
|
28
|
+
|
|
29
|
+
This class provides comprehensive profiling including:
|
|
30
|
+
- Automatic timing with checkpoints
|
|
31
|
+
- Memory usage tracking
|
|
32
|
+
- Thread-safe operations
|
|
33
|
+
- Context manager support
|
|
34
|
+
- Named operation tracking
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
name: str | None = "default",
|
|
40
|
+
track_memory: bool | None = False,
|
|
41
|
+
enabled: bool | None = False,
|
|
42
|
+
level: int | None = logging.INFO,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Initialize profiler with current timestamp.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
name: Name of this profiler instance
|
|
48
|
+
track_memory: Whether to track memory usage
|
|
49
|
+
enabled: Whether the profiler is enabled
|
|
50
|
+
"""
|
|
51
|
+
self._name = name
|
|
52
|
+
self._track_memory = track_memory
|
|
53
|
+
self._start_time = time.time()
|
|
54
|
+
self._last_timestamp = 0.0
|
|
55
|
+
self._checkpoints: dict[str, List[ProfileMetrics]] = defaultdict(list)
|
|
56
|
+
self._lock = threading.RLock()
|
|
57
|
+
self._process = psutil.Process(os.getpid()) if track_memory else None
|
|
58
|
+
self._start_memory = self._get_memory_usage() if track_memory else 0.0
|
|
59
|
+
self._enabled = enabled
|
|
60
|
+
self._level_ = level
|
|
61
|
+
|
|
62
|
+
def _get_memory_usage(self) -> float:
|
|
63
|
+
"""Get current memory usage in MB."""
|
|
64
|
+
if not self._process:
|
|
65
|
+
return 0.0
|
|
66
|
+
try:
|
|
67
|
+
return self._process.memory_info().rss / 1024 / 1024
|
|
68
|
+
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|
69
|
+
return 0.0
|
|
70
|
+
|
|
71
|
+
def _create_metrics(self, elapsed: float) -> ProfileMetrics:
|
|
72
|
+
"""Create ProfileMetrics with current state."""
|
|
73
|
+
current_memory = self._get_memory_usage() if self._track_memory else 0.0
|
|
74
|
+
return ProfileMetrics(
|
|
75
|
+
duration=elapsed,
|
|
76
|
+
memory_usage=current_memory,
|
|
77
|
+
peak_memory=max(current_memory, getattr(self, "_peak_memory", 0.0)),
|
|
78
|
+
call_count=1,
|
|
79
|
+
timestamp=time.time(),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
@contextmanager
|
|
83
|
+
def checkpoint(self, name: str) -> Generator[ProfileMetrics, None, None]:
|
|
84
|
+
"""Context manager for named checkpoints with automatic metrics collection.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
name: Name of the checkpoint
|
|
88
|
+
|
|
89
|
+
Yields:
|
|
90
|
+
ProfileMetrics object that gets updated on exit
|
|
91
|
+
"""
|
|
92
|
+
with self._lock:
|
|
93
|
+
start_time = time.time()
|
|
94
|
+
start_memory = self._get_memory_usage() if self._track_memory else 0.0
|
|
95
|
+
|
|
96
|
+
metrics = ProfileMetrics(timestamp=start_time)
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
yield metrics
|
|
100
|
+
finally:
|
|
101
|
+
end_time = time.time()
|
|
102
|
+
elapsed = end_time - start_time
|
|
103
|
+
end_memory = self._get_memory_usage() if self._track_memory else 0.0
|
|
104
|
+
|
|
105
|
+
metrics.duration = elapsed
|
|
106
|
+
metrics.memory_usage = end_memory - start_memory
|
|
107
|
+
metrics.peak_memory = end_memory
|
|
108
|
+
|
|
109
|
+
self._checkpoints[name].append(metrics)
|
|
110
|
+
|
|
111
|
+
def get_checkpoint_stats(self, name: str) -> dict[str, float] | None:
|
|
112
|
+
"""Get statistics for a named checkpoint.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
name: Name of the checkpoint
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Dictionary with avg_duration, total_calls, avg_memory_usage, etc.
|
|
119
|
+
"""
|
|
120
|
+
with self._lock:
|
|
121
|
+
if name not in self._checkpoints or not self._checkpoints[name]:
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
metrics = self._checkpoints[name]
|
|
125
|
+
return {
|
|
126
|
+
"total_calls": len(metrics),
|
|
127
|
+
"avg_duration": sum(m.duration for m in metrics) / len(metrics),
|
|
128
|
+
"total_duration": sum(m.duration for m in metrics),
|
|
129
|
+
"min_duration": min(m.duration for m in metrics),
|
|
130
|
+
"max_duration": max(m.duration for m in metrics),
|
|
131
|
+
"avg_memory_usage": sum(m.memory_usage for m in metrics) / len(metrics) if self._track_memory else 0.0,
|
|
132
|
+
"peak_memory": max(m.peak_memory for m in metrics) if self._track_memory else 0.0,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
def stamp(self, message: str, checkpoint_name: str | None = None) -> Tuple[float, str]:
|
|
136
|
+
"""Create timestamp for message with elapsed time and optional checkpoint.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
message: The message to timestamp
|
|
140
|
+
checkpoint_name: Optional checkpoint name to record
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
Tuple of (elapsed_seconds, formatted_message)
|
|
144
|
+
"""
|
|
145
|
+
with self._lock:
|
|
146
|
+
elapsed = time.time() - self._start_time
|
|
147
|
+
memory_info = ""
|
|
148
|
+
|
|
149
|
+
if self._track_memory:
|
|
150
|
+
current_memory = self._get_memory_usage()
|
|
151
|
+
memory_delta = current_memory - self._start_memory
|
|
152
|
+
memory_info = f" [mem: {current_memory:.1f}MB, Δ{memory_delta:+.1f}MB]"
|
|
153
|
+
|
|
154
|
+
formatted_message = f"{message} @{elapsed:.3f}s{memory_info}"
|
|
155
|
+
|
|
156
|
+
if checkpoint_name:
|
|
157
|
+
metrics = self._create_metrics(elapsed)
|
|
158
|
+
self._checkpoints[checkpoint_name].append(metrics)
|
|
159
|
+
|
|
160
|
+
return elapsed, formatted_message
|
|
161
|
+
|
|
162
|
+
def log(self, level: int, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
163
|
+
"""Log message with automatic timing and memory information.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
level: Logging level (DEBUG, INFO, WARNING, ERROR, etc.)
|
|
167
|
+
message: Message to log
|
|
168
|
+
*args: Additional arguments for message formatting
|
|
169
|
+
checkpoint_name: Optional checkpoint name to record metrics
|
|
170
|
+
**kwds: Additional keyword arguments for logger
|
|
171
|
+
"""
|
|
172
|
+
if not self._enabled:
|
|
173
|
+
return
|
|
174
|
+
with self._lock:
|
|
175
|
+
elapsed, timed_message = self.stamp(message, checkpoint_name)
|
|
176
|
+
time_delta = elapsed - self._last_timestamp
|
|
177
|
+
self._last_timestamp = elapsed
|
|
178
|
+
|
|
179
|
+
# Prepare extra timing data
|
|
180
|
+
extra_data: dict[str, Any] = kwds.get("extra", {})
|
|
181
|
+
extra_data.update(
|
|
182
|
+
{
|
|
183
|
+
"profiler_name": self._name,
|
|
184
|
+
"duration": elapsed,
|
|
185
|
+
"time_delta": time_delta,
|
|
186
|
+
"checkpoint_name": checkpoint_name,
|
|
187
|
+
}
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
if self._track_memory:
|
|
191
|
+
extra_data["memory_usage"] = self._get_memory_usage()
|
|
192
|
+
extra_data["memory_delta"] = self._get_memory_usage() - self._start_memory
|
|
193
|
+
|
|
194
|
+
# Update kwargs with timing data
|
|
195
|
+
log_kwargs = dict(kwds)
|
|
196
|
+
log_kwargs["extra"] = extra_data
|
|
197
|
+
log_kwargs.setdefault("stacklevel", 3)
|
|
198
|
+
|
|
199
|
+
logger.log(level, timed_message, *args, **log_kwargs)
|
|
200
|
+
|
|
201
|
+
def debug(self, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
202
|
+
"""Log debug message with timing information."""
|
|
203
|
+
self.log(logging.DEBUG, message, *args, checkpoint_name=checkpoint_name, **kwds)
|
|
204
|
+
|
|
205
|
+
def info(self, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
206
|
+
"""Log info message with timing information."""
|
|
207
|
+
self.log(logging.INFO, message, *args, checkpoint_name=checkpoint_name, **kwds)
|
|
208
|
+
|
|
209
|
+
def warn(self, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
210
|
+
"""Log warning message with timing information."""
|
|
211
|
+
self.log(logging.WARNING, message, *args, checkpoint_name=checkpoint_name, **kwds)
|
|
212
|
+
|
|
213
|
+
def warning(self, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
214
|
+
"""Log warning message with timing information."""
|
|
215
|
+
self.log(logging.WARNING, message, *args, checkpoint_name=checkpoint_name, **kwds)
|
|
216
|
+
|
|
217
|
+
def error(self, message: str, *args: Any, checkpoint_name: str | None = None, **kwds: Any) -> None:
|
|
218
|
+
"""Log error message with timing information."""
|
|
219
|
+
self.log(logging.ERROR, message, *args, checkpoint_name=checkpoint_name, **kwds)
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def elapsed_time(self) -> float:
|
|
223
|
+
"""Get total elapsed time since profiler creation."""
|
|
224
|
+
return time.time() - self._start_time
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def name(self) -> str | None:
|
|
228
|
+
"""Get profiler name."""
|
|
229
|
+
return self._name
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def memory_usage(self) -> float:
|
|
233
|
+
"""Get current memory usage in MB."""
|
|
234
|
+
return self._get_memory_usage()
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def memory_delta(self) -> float:
|
|
238
|
+
"""Get memory delta since profiler creation in MB."""
|
|
239
|
+
return self._get_memory_usage() - self._start_memory
|
|
240
|
+
|
|
241
|
+
def get_all_checkpoint_names(self) -> List[str]:
|
|
242
|
+
"""Get list of all checkpoint names."""
|
|
243
|
+
with self._lock:
|
|
244
|
+
return list(self._checkpoints.keys())
|
|
245
|
+
|
|
246
|
+
def get_summary(self) -> dict[str, Any]:
|
|
247
|
+
"""Get comprehensive profiler summary."""
|
|
248
|
+
with self._lock:
|
|
249
|
+
summary: dict[str, Any] = {
|
|
250
|
+
"name": self._name,
|
|
251
|
+
"total_elapsed_time": self.elapsed_time,
|
|
252
|
+
"memory_tracking_enabled": self._track_memory,
|
|
253
|
+
"current_memory_usage": self._get_memory_usage() if self._track_memory else None,
|
|
254
|
+
"memory_delta": self.memory_delta if self._track_memory else None,
|
|
255
|
+
"checkpoint_count": len(self._checkpoints),
|
|
256
|
+
"checkpoints": {},
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
for name in self._checkpoints:
|
|
260
|
+
stats = self.get_checkpoint_stats(name)
|
|
261
|
+
if stats:
|
|
262
|
+
summary["checkpoints"][name] = stats
|
|
263
|
+
|
|
264
|
+
return summary
|
|
265
|
+
|
|
266
|
+
def clear_checkpoints(self, name: str | None = None) -> None:
|
|
267
|
+
"""Clear checkpoints.
|
|
268
|
+
|
|
269
|
+
Args:
|
|
270
|
+
name: Specific checkpoint name to clear, or None to clear all
|
|
271
|
+
"""
|
|
272
|
+
with self._lock:
|
|
273
|
+
if name is None:
|
|
274
|
+
self._checkpoints.clear()
|
|
275
|
+
elif name in self._checkpoints:
|
|
276
|
+
del self._checkpoints[name]
|
|
277
|
+
|
|
278
|
+
def reset(self) -> None:
|
|
279
|
+
"""Reset profiler timing to current moment and clear checkpoints."""
|
|
280
|
+
with self._lock:
|
|
281
|
+
self._start_time = time.time()
|
|
282
|
+
self._last_timestamp = 0.0
|
|
283
|
+
self._start_memory = self._get_memory_usage() if self._track_memory else 0.0
|
|
284
|
+
self._checkpoints.clear()
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
|
|
3
|
+
from fastapi_mail import ConnectionConfig, FastMail, MessageSchema, MessageType
|
|
4
|
+
|
|
5
|
+
from ..services.base_service import BaseService
|
|
6
|
+
from ..settings import get_core_settings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MailerService(BaseService):
|
|
10
|
+
"""Service class for managing mailer settings and operations."""
|
|
11
|
+
|
|
12
|
+
@lru_cache()
|
|
13
|
+
@staticmethod
|
|
14
|
+
def _get_conf():
|
|
15
|
+
"""Get the mail configuration."""
|
|
16
|
+
settings = get_core_settings()
|
|
17
|
+
|
|
18
|
+
return ConnectionConfig(
|
|
19
|
+
MAIL_USERNAME=MailerService._required(settings.MAIL_USERNAME, "MAIL_USERNAME"),
|
|
20
|
+
MAIL_PASSWORD=MailerService._required(settings.MAIL_PASSWORD, "MAIL_PASSWORD"),
|
|
21
|
+
MAIL_FROM=MailerService._required(settings.MAIL_FROM, "MAIL_FROM"),
|
|
22
|
+
MAIL_PORT=MailerService._required(settings.MAIL_PORT, "MAIL_PORT"),
|
|
23
|
+
MAIL_SERVER=MailerService._required(settings.MAIL_SERVER, "MAIL_SERVER"),
|
|
24
|
+
MAIL_STARTTLS=MailerService._required(settings.MAIL_STARTTLS, "MAIL_STARTTLS"),
|
|
25
|
+
MAIL_SSL_TLS=MailerService._required(settings.MAIL_SSL_TLS, "MAIL_SSL_TLS"),
|
|
26
|
+
USE_CREDENTIALS=MailerService._required(settings.USE_CREDENTIALS, "USE_CREDENTIALS"),
|
|
27
|
+
VALIDATE_CERTS=MailerService._required(settings.VALIDATE_CERTS, "VALIDATE_CERTS"),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def _required(value, name):
|
|
32
|
+
if value is None:
|
|
33
|
+
raise RuntimeError(f"Missing required mail setting: {name}")
|
|
34
|
+
return value
|
|
35
|
+
|
|
36
|
+
def get_fm(self):
|
|
37
|
+
"""Get the FastMail instance configured with the mail settings."""
|
|
38
|
+
return FastMail(MailerService._get_conf())
|
|
39
|
+
|
|
40
|
+
async def send_email(self, to: str, subject: str, body: str):
|
|
41
|
+
"""Send an email using the configured mailer settings."""
|
|
42
|
+
message = MessageSchema(subject=subject, recipients=[to], body=body, subtype=MessageType.html)
|
|
43
|
+
|
|
44
|
+
return await self.get_fm().send_message(message)
|