Source code for luna_python_matcher.crutches_on_wheels.utils.rid
"""
Module realizes getting and checking request id
"""
import os
import time
import uuid
from contextvars import ContextVar
from .regexps import REQUEST_ID_REGEXP
# var contains actual requst id
requestIdCtx = ContextVar("requestId", default=None) # pylint: disable-msg=C0103
TIME_ZONE_DELTA = time.timezone #: correction for getting timestamp in utc
[docs]def getLogTimestamp(timeIsLocal: bool) -> int:
"""
Generate timestamp for logs
Args:
timeIsLocal: timestamp generate in localtime or not
Returns:
timestamp with
"""
if timeIsLocal:
timestamp = int(time.time() - TIME_ZONE_DELTA)
else:
timestamp = int(time.time())
return timestamp
def _getDefaultRequestId() -> str:
"""
Get default request id for record which is initiated of the service.
Format '{ts_start_service},00000000-0000-4000-a000-{pid}'
Returns:
request id
"""
timestamp = getLogTimestamp(timeIsLocal=True)
return f"{timestamp:08d},00000000-0000-4000-a000-{os.getpid():012d}"
DEFAULT_REQUEST_ID = _getDefaultRequestId() #: request id for record which is initiated of the service
[docs]def generateRequestId(timeIsLocal: bool) -> str:
"""
Generate correct request id.
Args:
timeIsLocal: timestamp generate in localtime or not
Returns:
standard request id string.
"""
requestId = f"{getLogTimestamp(timeIsLocal)},{uuid.uuid4()}"
return requestId
[docs]def checkRequestId(requestId: str) -> bool:
"""
Validate request id str
Args:
requestId: str for checking
Returns:
True if requestId match with REQUEST_ID_REGEXP otherwise False
"""
match = REQUEST_ID_REGEXP.match(requestId)
return match is not None