Passed
Pull Request — master (#974)
by Konstantin
02:57
created

ocrd_network.utils.call_sync()   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 10
rs 9.95
c 0
b 0
f 0
cc 2
nop 1
1
from datetime import datetime
2
from functools import wraps
3
from re import match as re_match
4
from pika import URLParameters
5
from pymongo import uri_parser as mongo_uri_parser
6
from uuid import uuid4
7
8
9
# Based on: https://gist.github.com/phizaz/20c36c6734878c6ec053245a477572ec
10
def call_sync(func):
11
    import asyncio
12
13
    @wraps(func)
14
    def func_wrapper(*args, **kwargs):
15
        result = func(*args, **kwargs)
16
        if asyncio.iscoroutine(result):
17
            return asyncio.get_event_loop().run_until_complete(result)
18
        return result
19
    return func_wrapper
20
21
22
def calculate_execution_time(start: datetime, end: datetime) -> int:
23
    """
24
    Calculates the difference between `start` and `end` datetime.
25
    Returns the result in milliseconds
26
    """
27
    return int((end - start).total_seconds() * 1000)
28
29
30
def generate_created_time() -> int:
31
    return int(datetime.utcnow().timestamp())
32
33
34
def generate_id() -> str:
35
    """
36
    Generate the id to be used for processing job ids.
37
    Note, workspace_id and workflow_id in the reference
38
    WebAPI implementation are produced in the same manner
39
    """
40
    return str(uuid4())
41
42
43
def verify_database_uri(mongodb_address: str) -> str:
44
    try:
45
        # perform validation check
46
        mongo_uri_parser.parse_uri(uri=mongodb_address, validate=True)
47
    except Exception as error:
48
        raise ValueError(f"The database address '{mongodb_address}' is in wrong format, {error}")
49
    return mongodb_address
50
51
52
def verify_and_parse_mq_uri(rabbitmq_address: str):
53
    """
54
    Check the full list of available parameters in the docs here:
55
    https://pika.readthedocs.io/en/stable/_modules/pika/connection.html#URLParameters
56
    """
57
58
    uri_pattern = r"^(?:([^:\/?#\s]+):\/{2})?(?:([^@\/?#\s]+)@)?([^\/?#\s]+)?(?:\/([^?#\s]*))?(?:[?]([^#\s]+))?\S*$"
59
    match = re_match(pattern=uri_pattern, string=rabbitmq_address)
60
    if not match:
61
        raise ValueError(f"The message queue server address is in wrong format: '{rabbitmq_address}'")
62
    url_params = URLParameters(rabbitmq_address)
63
64
    parsed_data = {
65
        'username': url_params.credentials.username,
66
        'password': url_params.credentials.password,
67
        'host': url_params.host,
68
        'port': url_params.port,
69
        'vhost': url_params.virtual_host
70
    }
71
    return parsed_data
72