EOX GitLab Instance

common.py 3.78 KB
Newer Older
Fabian Schindler's avatar
Fabian Schindler committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# ------------------------------------------------------------------------------
#
# Project: vsq <https://gitlab.eox.at/esa/prism/vsq>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
# ------------------------------------------------------------------------------
# Copyright (C) 2021 EOX IT Services GmbH
#
# 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:
#
# The above copyright notice and this permission notice shall be included in
# all copies of this Software or works derived from this Software.
#
# 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.
# ------------------------------------------------------------------------------

Fabian Schindler's avatar
Fabian Schindler committed
28
import enum
29
from dataclasses import dataclass, field
Fabian Schindler's avatar
Fabian Schindler committed
30
from datetime import datetime, timezone
31
32
33
import json
from typing import Dict, List, Union, Optional
from uuid import uuid4
Fabian Schindler's avatar
Fabian Schindler committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

MessageType = Union[
    str, int, float, List['MessageType'], Dict[str, 'MessageType']
]


def now():
    return datetime.now(timezone.utc)


class QueueClosedError(Exception):
    pass


class TaskFailedException(Exception):
    def __init__(self, error):
        self.error = error


class TaskTimeoutException(Exception):
Fabian Schindler's avatar
Fabian Schindler committed
54
    pass
Fabian Schindler's avatar
Fabian Schindler committed
55
56
57
58
59
60
61


class TaskStatus(enum.Enum):
    ACCEPTED = 'ACCEPTED'
    PROCESSING = 'PROCESSING'
    DONE = 'DONE'
    FAILED = 'FAILED'
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121


@dataclass
class TaskCommon:
    """
    """

    status: TaskStatus = TaskStatus.ACCEPTED
    id: str = field(default_factory=lambda: uuid4().hex)
    message: Optional[MessageType] = None
    result: Optional[MessageType] = None
    error: Optional[MessageType] = None
    created: Optional[datetime] = field(default_factory=now)
    started: Optional[datetime] = None
    finished: Optional[datetime] = None

    def encode(self):
        def default(o):
            if isinstance(o, datetime):
                return o.isoformat()
            elif isinstance(o, Exception):
                return str(o)
            elif isinstance(o, TaskStatus):
                return o.value

        dct = {
            'status': self.status,
            'id': self.id,
            'message': self.message,
            'result': self.result,
            'error': self.error,
            'created': self.created,
            'started': self.started,
            'finished': self.finished,
        }
        return json.dumps(dct, default=default)

    @classmethod
    def decode(cls, raw_value) -> 'TaskCommon':
        values = json.loads(raw_value)
        started = (
            datetime.fromisoformat(values['started'])
            if values['started'] else
            None
        )
        finished = (
            datetime.fromisoformat(values['finished'])
            if values['finished'] else
            None
        )
        return cls(
            status=TaskStatus(values['status']),
            id=values['id'],
            message=values['message'],
            result=values['result'],
            error=values['error'],
            created=datetime.fromisoformat(values['created']),
            started=started,
            finished=finished,
        )