BeatKeeper 0.1.0__6-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.
- BeatKeeper/Calendar.py +57 -0
- BeatKeeper/Cron.py +152 -0
- BeatKeeper/Executor.py +246 -0
- BeatKeeper/Pool.py +116 -0
- BeatKeeper/Properties.py +27 -0
- BeatKeeper/Startup.py +114 -0
- BeatKeeper/Task.py +119 -0
- BeatKeeper/Worker.py +198 -0
- BeatKeeper/__init__.py +41 -0
- beatkeeper-0.1.0.dist-info/METADATA +150 -0
- beatkeeper-0.1.0.dist-info/RECORD +14 -0
- beatkeeper-0.1.0.dist-info/WHEEL +6 -0
- beatkeeper-0.1.0.dist-info/licenses/LICENSE +674 -0
- beatkeeper-0.1.0.dist-info/top_level.txt +1 -0
BeatKeeper/Calendar.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from typing import (
|
|
2
|
+
Optional,
|
|
3
|
+
Union,
|
|
4
|
+
)
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CalendarPattern(str):
|
|
8
|
+
"""
|
|
9
|
+
단일 값 또는 시작과 끝이 포함된 cron 범위를 표현한다.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __new__(
|
|
13
|
+
cls,
|
|
14
|
+
start: Union[str, int],
|
|
15
|
+
end: Optional[Union[str, int]] = None,
|
|
16
|
+
) -> "CalendarPattern":
|
|
17
|
+
if isinstance(start, bool) or not isinstance(start, (str, int)):
|
|
18
|
+
raise TypeError("시작 값은 문자열 또는 정수여야 합니다")
|
|
19
|
+
if end is not None and (isinstance(end, bool) or not isinstance(end, (str, int))):
|
|
20
|
+
raise TypeError("끝 값은 문자열 또는 정수여야 합니다")
|
|
21
|
+
pattern: str = str(start)
|
|
22
|
+
if end is not None:
|
|
23
|
+
pattern = f"{pattern}-{end}"
|
|
24
|
+
return super().__new__(cls, pattern)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Weekday(CalendarPattern):
|
|
28
|
+
"""
|
|
29
|
+
요일 상수와 cron 요일 범위를 제공한다.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
SUNDAY: str = "SUN"
|
|
33
|
+
MONDAY: str = "MON"
|
|
34
|
+
TUESDAY: str = "TUE"
|
|
35
|
+
WEDNESDAY: str = "WED"
|
|
36
|
+
THURSDAY: str = "THU"
|
|
37
|
+
FRIDAY: str = "FRI"
|
|
38
|
+
SATURDAY: str = "SAT"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Month(CalendarPattern):
|
|
42
|
+
"""
|
|
43
|
+
월 상수와 cron 월 범위를 제공한다.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
JANUARY: str = "JAN"
|
|
47
|
+
FEBRUARY: str = "FEB"
|
|
48
|
+
MARCH: str = "MAR"
|
|
49
|
+
APRIL: str = "APR"
|
|
50
|
+
MAY: str = "MAY"
|
|
51
|
+
JUNE: str = "JUN"
|
|
52
|
+
JULY: str = "JUL"
|
|
53
|
+
AUGUST: str = "AUG"
|
|
54
|
+
SEPTEMBER: str = "SEP"
|
|
55
|
+
OCTOBER: str = "OCT"
|
|
56
|
+
NOVEMBER: str = "NOV"
|
|
57
|
+
DECEMBER: str = "DEC"
|
BeatKeeper/Cron.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import (
|
|
3
|
+
FrozenSet,
|
|
4
|
+
Mapping,
|
|
5
|
+
Tuple,
|
|
6
|
+
)
|
|
7
|
+
|
|
8
|
+
from .Properties import Properties
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
MONTHS: Mapping[str, int] = dict(zip(
|
|
12
|
+
(
|
|
13
|
+
"JAN",
|
|
14
|
+
"FEB",
|
|
15
|
+
"MAR",
|
|
16
|
+
"APR",
|
|
17
|
+
"MAY",
|
|
18
|
+
"JUN",
|
|
19
|
+
"JUL",
|
|
20
|
+
"AUG",
|
|
21
|
+
"SEP",
|
|
22
|
+
"OCT",
|
|
23
|
+
"NOV",
|
|
24
|
+
"DEC",
|
|
25
|
+
),
|
|
26
|
+
range(1, 13),
|
|
27
|
+
))
|
|
28
|
+
DAYS: Mapping[str, int] = dict(zip(
|
|
29
|
+
(
|
|
30
|
+
"SUN",
|
|
31
|
+
"MON",
|
|
32
|
+
"TUE",
|
|
33
|
+
"WED",
|
|
34
|
+
"THU",
|
|
35
|
+
"FRI",
|
|
36
|
+
"SAT",
|
|
37
|
+
),
|
|
38
|
+
range(7),
|
|
39
|
+
))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def parse_value(
|
|
43
|
+
text: str,
|
|
44
|
+
minimum: int,
|
|
45
|
+
maximum: int,
|
|
46
|
+
names: Mapping[str, int],
|
|
47
|
+
) -> int:
|
|
48
|
+
value: int
|
|
49
|
+
if text.upper() in names:
|
|
50
|
+
value = names[text.upper()]
|
|
51
|
+
elif text.isascii() and text.isdecimal():
|
|
52
|
+
value = int(text)
|
|
53
|
+
else:
|
|
54
|
+
raise ValueError(f"잘못된 cron 값: {text!r}")
|
|
55
|
+
if not minimum <= value <= maximum:
|
|
56
|
+
raise ValueError(f"cron 값 범위 초과: {text!r}")
|
|
57
|
+
return value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_field(
|
|
61
|
+
text: str,
|
|
62
|
+
minimum: int,
|
|
63
|
+
maximum: int,
|
|
64
|
+
names: Mapping[str, int],
|
|
65
|
+
) -> Tuple[FrozenSet[int], bool]:
|
|
66
|
+
"""
|
|
67
|
+
필드의 값과 wildcard 포함 여부를 검증한다.
|
|
68
|
+
"""
|
|
69
|
+
values: set[int] = set()
|
|
70
|
+
wildcard: bool = False
|
|
71
|
+
for item in text.split(","):
|
|
72
|
+
parts: list[str] = item.split("/")
|
|
73
|
+
if len(parts) > 2 or not parts[0]:
|
|
74
|
+
raise ValueError(f"잘못된 cron 항목: {item!r}")
|
|
75
|
+
base: str = parts[0]
|
|
76
|
+
step: int = 1
|
|
77
|
+
if len(parts) == 2:
|
|
78
|
+
if not parts[1].isascii() or not parts[1].isdecimal():
|
|
79
|
+
raise ValueError(f"잘못된 cron 단계: {item!r}")
|
|
80
|
+
step = int(parts[1])
|
|
81
|
+
if step < 1 or (base != "*" and "-" not in base):
|
|
82
|
+
raise ValueError(f"잘못된 cron 단계: {item!r}")
|
|
83
|
+
if base == "*":
|
|
84
|
+
wildcard = True
|
|
85
|
+
start: int = minimum
|
|
86
|
+
end: int = maximum
|
|
87
|
+
elif "-" in base:
|
|
88
|
+
bounds: list[str] = base.split("-")
|
|
89
|
+
if len(bounds) != 2:
|
|
90
|
+
raise ValueError(f"잘못된 cron 범위: {item!r}")
|
|
91
|
+
start = parse_value(bounds[0], minimum, maximum, names)
|
|
92
|
+
end = parse_value(bounds[1], minimum, maximum, names)
|
|
93
|
+
if start > end:
|
|
94
|
+
raise ValueError(f"역순 cron 범위: {item!r}")
|
|
95
|
+
else:
|
|
96
|
+
start = parse_value(base, minimum, maximum, names)
|
|
97
|
+
end = start
|
|
98
|
+
values.update(range(start, end + 1, step))
|
|
99
|
+
return frozenset(values), wildcard
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class Cron:
|
|
103
|
+
"""
|
|
104
|
+
Properties의 필드 패턴을 검증하고 로컬 시각과 비교한다.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
properties: Properties,
|
|
110
|
+
) -> None:
|
|
111
|
+
if not isinstance(properties, Properties):
|
|
112
|
+
raise TypeError("cron 설정은 Properties 인스턴스여야 합니다")
|
|
113
|
+
self.minutes: FrozenSet[int] = parse_field(properties.minute, 0, 59, {})[0]
|
|
114
|
+
self.hours: FrozenSet[int] = parse_field(properties.hour, 0, 23, {})[0]
|
|
115
|
+
self.month_days: FrozenSet[int]
|
|
116
|
+
self.month_day_wildcard: bool
|
|
117
|
+
self.month_days, self.month_day_wildcard = parse_field(
|
|
118
|
+
properties.day,
|
|
119
|
+
1,
|
|
120
|
+
31,
|
|
121
|
+
{},
|
|
122
|
+
)
|
|
123
|
+
self.months: FrozenSet[int] = parse_field(properties.month, 1, 12, MONTHS)[0]
|
|
124
|
+
days: FrozenSet[int]
|
|
125
|
+
self.week_day_wildcard: bool
|
|
126
|
+
days, self.week_day_wildcard = parse_field(
|
|
127
|
+
properties.weekday,
|
|
128
|
+
0,
|
|
129
|
+
7,
|
|
130
|
+
DAYS,
|
|
131
|
+
)
|
|
132
|
+
self.week_days: FrozenSet[int] = frozenset(day % 7 for day in days)
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
def matches(
|
|
136
|
+
self,
|
|
137
|
+
local_time: datetime,
|
|
138
|
+
) -> bool:
|
|
139
|
+
"""
|
|
140
|
+
시스템 로컬 시각의 분이 표현식과 일치하는지 판정한다.
|
|
141
|
+
"""
|
|
142
|
+
if (
|
|
143
|
+
local_time.minute not in self.minutes
|
|
144
|
+
or local_time.hour not in self.hours
|
|
145
|
+
or local_time.month not in self.months
|
|
146
|
+
):
|
|
147
|
+
return False
|
|
148
|
+
month_day_matches: bool = local_time.day in self.month_days
|
|
149
|
+
week_day_matches: bool = (local_time.weekday() + 1) % 7 in self.week_days
|
|
150
|
+
if self.month_day_wildcard or self.week_day_wildcard:
|
|
151
|
+
return month_day_matches and week_day_matches
|
|
152
|
+
return month_day_matches or week_day_matches
|
BeatKeeper/Executor.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
from multiprocessing import get_context
|
|
2
|
+
from multiprocessing.managers import SyncManager
|
|
3
|
+
from pickle import (
|
|
4
|
+
dumps,
|
|
5
|
+
loads,
|
|
6
|
+
)
|
|
7
|
+
from queue import (
|
|
8
|
+
Empty,
|
|
9
|
+
Queue,
|
|
10
|
+
)
|
|
11
|
+
from threading import (
|
|
12
|
+
Lock,
|
|
13
|
+
Thread,
|
|
14
|
+
)
|
|
15
|
+
from typing import (
|
|
16
|
+
Any,
|
|
17
|
+
Callable,
|
|
18
|
+
Optional,
|
|
19
|
+
Sequence,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Executor:
|
|
24
|
+
@staticmethod
|
|
25
|
+
def cleanup(cleanup_hooks: Sequence[Callable[[], None]]) -> None:
|
|
26
|
+
failure: Optional[BaseException] = None
|
|
27
|
+
for cleanup in cleanup_hooks:
|
|
28
|
+
try:
|
|
29
|
+
cleanup()
|
|
30
|
+
except BaseException as error:
|
|
31
|
+
if failure is not None:
|
|
32
|
+
error.__context__ = failure
|
|
33
|
+
failure = error
|
|
34
|
+
if failure is not None:
|
|
35
|
+
raise failure
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def send(
|
|
40
|
+
outgoing: Any,
|
|
41
|
+
message: tuple[Optional[int], bool, object],
|
|
42
|
+
process: bool,
|
|
43
|
+
) -> None:
|
|
44
|
+
if process:
|
|
45
|
+
try:
|
|
46
|
+
payload: bytes = dumps(message)
|
|
47
|
+
except Exception as error:
|
|
48
|
+
payload = dumps((
|
|
49
|
+
message[0],
|
|
50
|
+
False,
|
|
51
|
+
RuntimeError("Cannot serialize execution outcome: " + repr(error)),
|
|
52
|
+
))
|
|
53
|
+
outgoing.put(payload)
|
|
54
|
+
else:
|
|
55
|
+
outgoing.put(message)
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def execute(
|
|
60
|
+
incoming: Any,
|
|
61
|
+
outgoing: Any,
|
|
62
|
+
setups: Sequence[Callable[[], None]],
|
|
63
|
+
cleanup_hooks: Sequence[Callable[[], None]],
|
|
64
|
+
process: bool,
|
|
65
|
+
) -> None:
|
|
66
|
+
ready: bool = False
|
|
67
|
+
try:
|
|
68
|
+
for setup in setups:
|
|
69
|
+
setup()
|
|
70
|
+
ready = True
|
|
71
|
+
while True:
|
|
72
|
+
message: Any = incoming.get()
|
|
73
|
+
if message is None:
|
|
74
|
+
break
|
|
75
|
+
task_id: int
|
|
76
|
+
payload: Any
|
|
77
|
+
task_id, payload = message
|
|
78
|
+
try:
|
|
79
|
+
function: Callable[..., Any]
|
|
80
|
+
args: tuple[Any, ...]
|
|
81
|
+
kwargs: dict[str, Any]
|
|
82
|
+
function, args, kwargs = loads(payload) if process else payload
|
|
83
|
+
result: Any = function(*args, **kwargs)
|
|
84
|
+
except BaseException as error:
|
|
85
|
+
Executor.send(outgoing, (task_id, False, error), process)
|
|
86
|
+
else:
|
|
87
|
+
Executor.send(outgoing, (task_id, True, result), process)
|
|
88
|
+
except BaseException as error:
|
|
89
|
+
Executor.send(outgoing, (None, False, error), process)
|
|
90
|
+
finally:
|
|
91
|
+
if ready:
|
|
92
|
+
try:
|
|
93
|
+
Executor.cleanup(cleanup_hooks)
|
|
94
|
+
except BaseException as error:
|
|
95
|
+
Executor.send(outgoing, (None, False, error), process)
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
max_workers: int,
|
|
101
|
+
setups: Sequence[Callable[[], None]],
|
|
102
|
+
cleanups: Sequence[Callable[[], None]],
|
|
103
|
+
process: bool = False,
|
|
104
|
+
) -> None:
|
|
105
|
+
self.max_workers: int = max_workers
|
|
106
|
+
self.setups: Sequence[Callable[[], None]] = setups
|
|
107
|
+
self.cleanups: Sequence[Callable[[], None]] = cleanups
|
|
108
|
+
self.process: bool = process
|
|
109
|
+
self.lock: Lock = Lock()
|
|
110
|
+
self.workers: list[Any] = []
|
|
111
|
+
self.incoming: Any = None
|
|
112
|
+
self.outgoing: Any = None
|
|
113
|
+
self.manager: Optional[SyncManager] = None
|
|
114
|
+
self.started: bool = False
|
|
115
|
+
self.closed: bool = False
|
|
116
|
+
self.sequence: int = 0
|
|
117
|
+
self.pending: set[int] = set()
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
def start(self) -> None:
|
|
121
|
+
self.started = True
|
|
122
|
+
try:
|
|
123
|
+
if self.process:
|
|
124
|
+
context = get_context("spawn")
|
|
125
|
+
self.incoming = context.Queue()
|
|
126
|
+
self.manager = context.Manager()
|
|
127
|
+
self.outgoing = self.manager.Queue()
|
|
128
|
+
else:
|
|
129
|
+
context = None
|
|
130
|
+
self.incoming = Queue()
|
|
131
|
+
self.outgoing = Queue()
|
|
132
|
+
for index in range(self.max_workers):
|
|
133
|
+
args = (
|
|
134
|
+
self.incoming,
|
|
135
|
+
self.outgoing,
|
|
136
|
+
self.setups,
|
|
137
|
+
self.cleanups,
|
|
138
|
+
self.process,
|
|
139
|
+
)
|
|
140
|
+
if context is not None:
|
|
141
|
+
worker = context.Process(target=Executor.execute, args=args)
|
|
142
|
+
else:
|
|
143
|
+
worker = Thread(target=Executor.execute, args=args, name=f"PoolWorker-{index}")
|
|
144
|
+
worker.start()
|
|
145
|
+
self.workers.append(worker)
|
|
146
|
+
except BaseException:
|
|
147
|
+
for _ in self.workers:
|
|
148
|
+
self.incoming.put(None)
|
|
149
|
+
for worker in self.workers:
|
|
150
|
+
worker.join()
|
|
151
|
+
if self.process and self.incoming is not None:
|
|
152
|
+
self.incoming.close()
|
|
153
|
+
self.incoming.join_thread()
|
|
154
|
+
if self.manager is not None:
|
|
155
|
+
self.manager.shutdown()
|
|
156
|
+
self.closed = True
|
|
157
|
+
raise
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
def submit(
|
|
161
|
+
self,
|
|
162
|
+
fn: Callable[..., Any],
|
|
163
|
+
/,
|
|
164
|
+
*args: Any,
|
|
165
|
+
**kwargs: Any,
|
|
166
|
+
) -> int:
|
|
167
|
+
payload: Any = (fn, args, kwargs)
|
|
168
|
+
if self.process:
|
|
169
|
+
payload = dumps(payload)
|
|
170
|
+
with self.lock:
|
|
171
|
+
if self.closed:
|
|
172
|
+
raise RuntimeError("Pool is closed")
|
|
173
|
+
if not self.started:
|
|
174
|
+
self.start()
|
|
175
|
+
task_id: int = self.sequence
|
|
176
|
+
self.sequence += 1
|
|
177
|
+
self.incoming.put((task_id, payload))
|
|
178
|
+
self.pending.add(task_id)
|
|
179
|
+
return task_id
|
|
180
|
+
|
|
181
|
+
def receive(
|
|
182
|
+
self,
|
|
183
|
+
timeout: float = 0,
|
|
184
|
+
) -> Optional[tuple[Optional[int], bool, object]]:
|
|
185
|
+
if not self.started:
|
|
186
|
+
return None
|
|
187
|
+
try:
|
|
188
|
+
message: Any = self.outgoing.get(timeout=timeout)
|
|
189
|
+
except Empty:
|
|
190
|
+
if not self.closed and any(not worker.is_alive() for worker in self.workers):
|
|
191
|
+
raise RuntimeError("Pool worker exited unexpectedly")
|
|
192
|
+
return None
|
|
193
|
+
if self.process:
|
|
194
|
+
message = loads(message)
|
|
195
|
+
task_id: Optional[int]
|
|
196
|
+
success: bool
|
|
197
|
+
result: object
|
|
198
|
+
task_id, success, result = message
|
|
199
|
+
if task_id is not None:
|
|
200
|
+
with self.lock:
|
|
201
|
+
self.pending.remove(task_id)
|
|
202
|
+
return task_id, success, result
|
|
203
|
+
|
|
204
|
+
def shutdown(self) -> None:
|
|
205
|
+
with self.lock:
|
|
206
|
+
if self.closed:
|
|
207
|
+
return
|
|
208
|
+
self.closed = True
|
|
209
|
+
for _ in self.workers:
|
|
210
|
+
self.incoming.put(None)
|
|
211
|
+
for worker in self.workers:
|
|
212
|
+
worker.join()
|
|
213
|
+
failure: Optional[BaseException] = None
|
|
214
|
+
try:
|
|
215
|
+
while self.started:
|
|
216
|
+
message: Optional[tuple[Optional[int], bool, object]] = self.receive()
|
|
217
|
+
if message is None:
|
|
218
|
+
break
|
|
219
|
+
_, success, result = message
|
|
220
|
+
if not success and failure is None:
|
|
221
|
+
if not isinstance(result, BaseException):
|
|
222
|
+
raise TypeError("Pool failure is not an exception")
|
|
223
|
+
failure = result
|
|
224
|
+
finally:
|
|
225
|
+
if self.process and self.started:
|
|
226
|
+
if self.pending:
|
|
227
|
+
self.incoming.cancel_join_thread()
|
|
228
|
+
self.incoming.close()
|
|
229
|
+
if not self.pending:
|
|
230
|
+
self.incoming.join_thread()
|
|
231
|
+
if self.manager is not None:
|
|
232
|
+
self.manager.shutdown()
|
|
233
|
+
if failure is not None:
|
|
234
|
+
raise failure
|
|
235
|
+
if self.pending:
|
|
236
|
+
raise RuntimeError("Pool stopped before all tasks completed")
|
|
237
|
+
if self.process and any(worker.exitcode != 0 for worker in self.workers):
|
|
238
|
+
raise RuntimeError("Pool worker exited unexpectedly")
|
|
239
|
+
return
|
|
240
|
+
|
|
241
|
+
def __enter__(self) -> "Executor":
|
|
242
|
+
return self
|
|
243
|
+
|
|
244
|
+
def __exit__(self, *args: object) -> None:
|
|
245
|
+
self.shutdown()
|
|
246
|
+
return
|
BeatKeeper/Pool.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from abc import (
|
|
2
|
+
ABC,
|
|
3
|
+
abstractmethod,
|
|
4
|
+
)
|
|
5
|
+
from os import cpu_count
|
|
6
|
+
from typing import (
|
|
7
|
+
Callable,
|
|
8
|
+
Optional,
|
|
9
|
+
Sequence,
|
|
10
|
+
Union,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from .Executor import Executor
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PoolSetup(ABC):
|
|
17
|
+
"""
|
|
18
|
+
실행 환경이 준비될 때 호출되는 hook 계약이다.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def __call__(self) -> None:
|
|
23
|
+
raise NotImplementedError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PoolCleanup(ABC):
|
|
27
|
+
"""
|
|
28
|
+
실행 환경이 종료될 때 호출되는 hook 계약이다.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def __call__(self) -> None:
|
|
33
|
+
raise NotImplementedError
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Pool(Executor):
|
|
37
|
+
@staticmethod
|
|
38
|
+
def cb(
|
|
39
|
+
hooks: Optional[Union[Callable[[], None], Sequence[Callable[[], None]]]],
|
|
40
|
+
) -> tuple[Callable[[], None], ...]:
|
|
41
|
+
result: tuple[Callable[[], None], ...]
|
|
42
|
+
if hooks is None:
|
|
43
|
+
result = ()
|
|
44
|
+
elif isinstance(hooks, Sequence):
|
|
45
|
+
result = tuple(hooks)
|
|
46
|
+
else:
|
|
47
|
+
result = (hooks,)
|
|
48
|
+
if not all(callable(hook) for hook in result):
|
|
49
|
+
raise TypeError("Pool hooks must be callable")
|
|
50
|
+
return result
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def resolve_pool_size(max: Optional[int]) -> int:
|
|
54
|
+
if max is None:
|
|
55
|
+
return cpu_count() or 1
|
|
56
|
+
if isinstance(max, bool) or not isinstance(max, int) or max < 1:
|
|
57
|
+
raise ValueError("Pool size must be a positive integer")
|
|
58
|
+
return max
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
max: Optional[int] = None,
|
|
63
|
+
setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
|
|
64
|
+
cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
|
|
65
|
+
process: bool = False,
|
|
66
|
+
) -> None:
|
|
67
|
+
size: int = self.resolve_pool_size(max)
|
|
68
|
+
super().__init__(
|
|
69
|
+
size,
|
|
70
|
+
self.cb(setups),
|
|
71
|
+
self.cb(cleanups),
|
|
72
|
+
process=process,
|
|
73
|
+
)
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
def size(self) -> int:
|
|
77
|
+
return self.max_workers
|
|
78
|
+
|
|
79
|
+
def count(self) -> int:
|
|
80
|
+
with self.lock:
|
|
81
|
+
return len(self.pending)
|
|
82
|
+
|
|
83
|
+
def stop(self) -> None:
|
|
84
|
+
self.shutdown()
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ThreadPool(Pool):
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
max: Optional[int] = None,
|
|
92
|
+
setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
|
|
93
|
+
cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
|
|
94
|
+
) -> None:
|
|
95
|
+
super().__init__(
|
|
96
|
+
max,
|
|
97
|
+
setups,
|
|
98
|
+
cleanups,
|
|
99
|
+
)
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class ProcessPool(Pool):
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
max: Optional[int] = None,
|
|
107
|
+
setups: Optional[Union[PoolSetup, Sequence[PoolSetup]]] = None,
|
|
108
|
+
cleanups: Optional[Union[PoolCleanup, Sequence[PoolCleanup]]] = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
super().__init__(
|
|
111
|
+
max,
|
|
112
|
+
setups,
|
|
113
|
+
cleanups,
|
|
114
|
+
process=True,
|
|
115
|
+
)
|
|
116
|
+
return
|
BeatKeeper/Properties.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True, kw_only=True)
|
|
5
|
+
class Properties:
|
|
6
|
+
"""
|
|
7
|
+
개별 cron 필드 패턴을 담는다.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
minute: str = "*"
|
|
11
|
+
hour: str = "*"
|
|
12
|
+
day: str = "*"
|
|
13
|
+
month: str = "*"
|
|
14
|
+
weekday: str = "*"
|
|
15
|
+
|
|
16
|
+
def __post_init__(self) -> None:
|
|
17
|
+
patterns: tuple[tuple[str, str], ...] = (
|
|
18
|
+
("minute", self.minute),
|
|
19
|
+
("hour", self.hour),
|
|
20
|
+
("day", self.day),
|
|
21
|
+
("month", self.month),
|
|
22
|
+
("weekday", self.weekday),
|
|
23
|
+
)
|
|
24
|
+
for name, pattern in patterns:
|
|
25
|
+
if not isinstance(pattern, str):
|
|
26
|
+
raise TypeError(f"{name} 패턴은 문자열이어야 합니다")
|
|
27
|
+
return
|
BeatKeeper/Startup.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from os import (
|
|
3
|
+
environ,
|
|
4
|
+
getpid,
|
|
5
|
+
)
|
|
6
|
+
from typing import (
|
|
7
|
+
Callable,
|
|
8
|
+
Sequence,
|
|
9
|
+
TYPE_CHECKING,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from .Pool import Pool
|
|
13
|
+
from .Properties import Properties
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from .Worker import Worker
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# https://patorjk.com/software/taag/#p=display&f=Coder+Mini&t=JustStream&x=none&v=4&h=4&w=80&we=false
|
|
21
|
+
LOGO = r"""
|
|
22
|
+
▄▄▄▄▄▄▄ ▄▄▄ ▄▄▄
|
|
23
|
+
███▀▀███▄ ██ ███ ▄███▀
|
|
24
|
+
███▄▄███▀ ▄█▀█▄ ▀▀█▄ ▀██▀▀ ███████ ▄█▀█▄ ▄█▀█▄ ████▄ ▄█▀█▄ ████▄
|
|
25
|
+
███ ███▄ ██▄█▀ ▄█▀██ ██ ███▀███▄ ██▄█▀ ██▄█▀ ██ ██ ██▄█▀ ██ ▀▀
|
|
26
|
+
████████▀ ▀█▄▄▄ ▀█▄██ ██ ███ ▀███ ▀█▄▄▄ ▀█▄▄▄ ████▀ ▀█▄▄▄ ██
|
|
27
|
+
██
|
|
28
|
+
▀▀
|
|
29
|
+
|
|
30
|
+
"Keep your tasks in rhythm."
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def supports_color() -> bool:
|
|
35
|
+
return (
|
|
36
|
+
getattr(sys.stdout, 'isatty', lambda: False)()
|
|
37
|
+
and not environ.get('NO_COLOR')
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def colorize_logo(logo: str) -> str:
|
|
42
|
+
colors = (
|
|
43
|
+
'\033[38;5;39m',
|
|
44
|
+
'\033[38;5;45m',
|
|
45
|
+
'\033[38;5;51m',
|
|
46
|
+
'\033[38;5;87m',
|
|
47
|
+
'\033[38;5;51m',
|
|
48
|
+
'\033[38;5;45m',
|
|
49
|
+
'\033[38;5;39m',
|
|
50
|
+
)
|
|
51
|
+
reset = '\033[0m'
|
|
52
|
+
colorized_lines = []
|
|
53
|
+
art_line = 0
|
|
54
|
+
for line in logo.splitlines(keepends=True):
|
|
55
|
+
if line.strip() and art_line < len(colors):
|
|
56
|
+
newline = '\n' if line.endswith('\n') else ''
|
|
57
|
+
colorized_lines.append(
|
|
58
|
+
f'{colors[art_line]}{line[:-1] if newline else line}'
|
|
59
|
+
f'{reset}{newline}',
|
|
60
|
+
)
|
|
61
|
+
art_line += 1
|
|
62
|
+
else:
|
|
63
|
+
colorized_lines.append(line)
|
|
64
|
+
return ''.join(colorized_lines)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def hook_names(hooks: Sequence[Callable[..., object]]) -> str:
|
|
68
|
+
if not hooks:
|
|
69
|
+
return "-"
|
|
70
|
+
names: list[str] = [
|
|
71
|
+
getattr(hook, "__qualname__", type(hook).__qualname__)
|
|
72
|
+
for hook in hooks
|
|
73
|
+
]
|
|
74
|
+
return ", ".join(names)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def startup(
|
|
78
|
+
worker: "Worker",
|
|
79
|
+
) -> None:
|
|
80
|
+
"""
|
|
81
|
+
워커 시작 시 실행 환경과 등록된 작업을 표시한다.
|
|
82
|
+
"""
|
|
83
|
+
logo: str = LOGO
|
|
84
|
+
title: str = "Starting Worker"
|
|
85
|
+
if supports_color():
|
|
86
|
+
logo = colorize_logo(LOGO)
|
|
87
|
+
title = f"\033[1;38;5;51m{title}\033[0m"
|
|
88
|
+
lines: list[str] = [
|
|
89
|
+
logo,
|
|
90
|
+
"",
|
|
91
|
+
title,
|
|
92
|
+
f" PID: {getpid()}",
|
|
93
|
+
]
|
|
94
|
+
if isinstance(worker.executor, Pool):
|
|
95
|
+
pool: Pool = worker.executor
|
|
96
|
+
lines.append(f" Pool: {type(pool).__qualname__} (concurrency={pool.size()})")
|
|
97
|
+
lines.append(f" setups: {hook_names(pool.setups)}")
|
|
98
|
+
lines.append(f" cleanups: {hook_names(pool.cleanups)}")
|
|
99
|
+
else:
|
|
100
|
+
lines.append(f" Executor: {type(worker.executor).__qualname__}")
|
|
101
|
+
lines.append(f" Tasks: {len(worker.tasks)} tasks")
|
|
102
|
+
for task in worker.tasks:
|
|
103
|
+
properties: Properties = task.properties
|
|
104
|
+
lines.append(f" - {task.__qualname__}")
|
|
105
|
+
lines.append(
|
|
106
|
+
f" minute={properties.minute!r} hour={properties.hour!r} "
|
|
107
|
+
f"day={properties.day!r} month={properties.month!r} "
|
|
108
|
+
f"weekday={properties.weekday!r}"
|
|
109
|
+
)
|
|
110
|
+
lines.append(f" setups: {hook_names(task.setups)}")
|
|
111
|
+
lines.append(f" completes: {hook_names(task.completes)}")
|
|
112
|
+
lines.append(f" errors: {hook_names(task.errors)}")
|
|
113
|
+
print("\n".join(lines) + "\n", flush=True)
|
|
114
|
+
return
|