File: types.py

package info (click to toggle)
python-pebble 5.1.1-1
  • links: PTS
  • area: main
  • in suites: sid, trixie
  • size: 436 kB
  • sloc: python: 5,491; makefile: 2
file content (208 lines) | stat: -rw-r--r-- 6,394 bytes parent folder | download
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# This file is part of Pebble.
# Copyright (c) 2013-2025, Matteo Cafasso

# Pebble is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.

# Pebble is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with Pebble.  If not, see <http://www.gnu.org/licenses/>.

import asyncio

from enum import Enum, IntEnum
from dataclasses import dataclass
from concurrent.futures import Future
from typing import Any, TypeVar, Callable


P = TypeVar("P")
T = TypeVar("T")


try:
    FutureType = Future[T]
except TypeError:
    FutureType = Future


class ProcessExpired(OSError):
    """Raised when process dies unexpectedly."""
    def __init__(self, msg, code=0, pid=None):
        super(ProcessExpired, self).__init__(msg)
        self.exitcode = code
        self.pid = pid


class PebbleFuture(FutureType):
    # Same as base class, removed logline
    def set_running_or_notify_cancel(self):
        """Mark the future as running or process any cancel notifications.

        Should only be used by Executor implementations and unit tests.

        If the future has been cancelled (cancel() was called and returned
        True) then any threads waiting on the future completing (though calls
        to as_completed() or wait()) are notified and False is returned.

        If the future was not cancelled then it is put in the running state
        (future calls to running() will return True) and True is returned.

        This method should be called by Executor implementations before
        executing the work associated with this future. If this method returns
        False then the work should not be executed.

        Returns:
            False if the Future was cancelled, True otherwise.

        Raises:
            RuntimeError: if set_result() or set_exception() was called.
        """
        with self._condition:
            if self._state == FutureStatus.CANCELLED:
                self._state = FutureStatus.CANCELLED_AND_NOTIFIED
                for waiter in self._waiters:
                    waiter.add_cancelled(self)

                return False
            elif self._state == FutureStatus.PENDING:
                self._state = FutureStatus.RUNNING

                return True
            else:
                raise RuntimeError('Future in unexpected state')


try:
    PebbleFutureType = PebbleFuture[T]
except TypeError:
    PebbleFutureType = PebbleFuture


class ProcessFuture(PebbleFutureType):
    def cancel(self):
        """Cancel the future.

        Returns True if the future was cancelled, False otherwise. A future
        cannot be cancelled if it has already completed.
        """
        with self._condition:
            if self._state == FutureStatus.FINISHED:
                return False

            if self._state in (FutureStatus.CANCELLED,
                               FutureStatus.CANCELLED_AND_NOTIFIED):
                return True

            self._state = FutureStatus.CANCELLED
            self._condition.notify_all()

        self._invoke_callbacks()

        return True


class RemoteTraceback(Exception):
    """Traceback wrapper for exceptions in remote process.

    Exception.__cause__ requires a BaseException subclass.

    """

    def __init__(self, traceback):
        self.traceback = traceback

    def __str__(self):
        return self.traceback


class RemoteException:
    """Pickling wrapper for exceptions in remote process."""

    def __init__(self, exception, traceback):
        self.exception = exception
        self.traceback = traceback

    def __reduce__(self):
        return self.rebuild_exception, (self.exception, self.traceback)

    @staticmethod
    def rebuild_exception(exception, traceback):
        try:
            exception.traceback = traceback
            exception.__cause__ = RemoteTraceback(traceback)
        except AttributeError:  # Frozen exception
            pass

        return exception


class ResultStatus(IntEnum):
    """Status of results of a function execution."""
    SUCCESS = 0
    FAILURE = 1
    ERROR = 2


@dataclass
class Result:
    """Result of a function execution."""
    status: ResultStatus
    value: Any


class FutureStatus(str, Enum):
    """Borrowed from concurrent.futures."""
    PENDING = 'PENDING'
    RUNNING = 'RUNNING'
    FINISHED = 'FINISHED'
    CANCELLED = 'CANCELLED'
    CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'


@dataclass
class Consts:
    """Internal constants.

    WARNING: changing these values will affect the behaviour
    of Pools and decorators.

    """
    sleep_unit: float = 0.1
    """Any cycle which needs to periodically assess the state."""
    term_timeout: float = 3
    """On UNIX once a SIGTERM signal is issued to a process,
    the amount of seconds to wait before issuing a SIGKILL signal."""
    channel_lock_timeout: float = 60
    """The process pool relies on a pipe protected by a lock.
    The timeout when attempting to acquire the lock."""


try:
    CallableType = Callable[[P], T]
    AsyncIODecoratorReturnType = Callable[[P], asyncio.Future[T]]
    AsyncIODecoratorParamsReturnType = Callable[[Callable[[P], T]],
                                                Callable[[P], asyncio.Future[T]]]
    ThreadDecoratorReturnType = Callable[[P], Future[T]]
    ThreadDecoratorParamsReturnType = Callable[[Callable[[P], T]],
                                               Callable[[P], Future[T]]]
    ProcessDecoratorReturnType = Callable[[P], ProcessFuture[T]]
    ProcessDecoratorParamsReturnType = Callable[[Callable[[P], T]],
                                                Callable[[P], ProcessFuture[T]]]
except TypeError:
    ReturnType = Callable
    AsyncIODecoratorReturnType = Callable
    AsyncIODecoratorParamsReturnType = Callable
    ThreadDecoratorReturnType = Callable
    ThreadDecoratorParamsReturnType = Callable
    ProcessDecoratorReturnType = Callable
    ProcessDecoratorParamsReturnType = Callable


CONSTS = Consts()