taskex 0.0.1__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.
taskex/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .env import Env as Env
2
+ from .models import ShellProcess as ShellProcess
3
+ from .task_runner import TaskRunner as TaskRunner
4
+ from .util import TimeParser as TimeParser
taskex/env.py ADDED
@@ -0,0 +1,30 @@
1
+ from typing import Callable, Dict, Union, Literal
2
+
3
+ import psutil
4
+ from pydantic import BaseModel, StrictInt, StrictStr
5
+ PrimaryType = Union[str, int, float, bytes, bool]
6
+
7
+
8
+ class Env(BaseModel):
9
+ MERCURY_SYNC_EXECUTOR_TYPE: Literal['thread', 'process'] = 'process'
10
+ MERCURY_SYNC_LOG_LEVEL: StrictStr = "info"
11
+ MERCURY_SYNC_CLEANUP_INTERVAL: StrictStr = '1s'
12
+ MERCURY_SYNC_TASK_RUNNER_MAX_THREADS: StrictInt = psutil.cpu_count(logical=False)
13
+ MERCURY_SYNC_MAX_RUNNING_WORKFLOWS: StrictInt = 1
14
+ MERCURY_SYNC_MAX_PENDING_WORKFLOWS: StrictInt = 100
15
+ MERCURY_SYNC_CONTEXT_POLL_RATE: StrictStr = "0.1s"
16
+ MERCURY_SYNC_SHUTDOWN_POLL_RATE: StrictStr = "0.1s"
17
+ MERCURY_SYNC_DUPLICATE_JOB_POLICY: Literal["reject", "replace"] = "replace"
18
+
19
+ @classmethod
20
+ def types_map(self) -> Dict[str, Callable[[str], PrimaryType]]:
21
+ return {
22
+ "MERCURY_SYNC_EXECUTOR_TYPE": str,
23
+ "MERCURY_SYNC_CLEANUP_INTERVAL": str,
24
+ "MERCURY_SYNC_LOG_LEVEL": str,
25
+ "MERCURY_SYNC_TASK_RUNNER_MAX_THREADS": int,
26
+ "MERCURY_SYNC_MAX_WORKFLOWS": int,
27
+ "MERCURY_SYNC_CONTEXT_POLL_RATE": str,
28
+ "MERCURY_SYNC_SHUTDOWN_POLL_RATE": str,
29
+ "MERCURY_SYNC_DUPLICATE_JOB_POLICY": str,
30
+ }
@@ -0,0 +1,6 @@
1
+ from .run_status import RunStatus as RunStatus
2
+ from .shell_process import ShellProcess as ShellProcess
3
+ from .shell_process import CommandType as CommandType
4
+ from .task_run import TaskRun as TaskRun
5
+ from .task_status import TaskStatus as TaskStatus
6
+ from .task_type import TaskType as TaskType
@@ -0,0 +1,23 @@
1
+ from enum import Enum
2
+ from typing import Literal
3
+
4
+
5
+ class RunStatus(Enum):
6
+ CREATED = "CREATED"
7
+ PENDING = "PENDING"
8
+ IDLE = "IDLE"
9
+ RUNNING = "RUNNING"
10
+ COMPLETE = "COMPLETE"
11
+ CANCELLED = "CANCELLED"
12
+ FAILED = "FAILED"
13
+
14
+
15
+ RunStatusName = Literal[
16
+ 'CREATED',
17
+ 'PENDING',
18
+ 'IDLE',
19
+ 'RUNNING',
20
+ 'COMPLETE',
21
+ 'CANCELLED',
22
+ 'FAILED',
23
+ ]
@@ -0,0 +1,36 @@
1
+ import time
2
+ from pydantic import (
3
+ BaseModel,
4
+ StrictInt,
5
+ StrictFloat,
6
+ StrictStr,
7
+ StrictBytes,
8
+ )
9
+ from typing import Literal, Any, Dict, Tuple
10
+ from .run_status import RunStatus
11
+ from .task_type import TaskType
12
+
13
+
14
+ CommandType = Literal['shell', 'subprocess']
15
+
16
+
17
+ class ShellProcess(BaseModel):
18
+ run_id: StrictInt
19
+ process_id: StrictInt
20
+ command: StrictStr
21
+ status: RunStatus
22
+ args: Tuple[str, ...] | None = None
23
+ return_code: StrictInt | None = None
24
+ env: Dict[str, Any] | None = None
25
+ working_directory: StrictStr | None = None
26
+ command_type: CommandType = 'subprocess'
27
+ error: StrictStr | StrictBytes | None = None
28
+ trace: StrictStr | StrictBytes | None = None
29
+ start: StrictInt | StrictFloat = time.monotonic()
30
+ end: StrictInt | StrictFloat | None = None
31
+ elapsed: StrictInt | StrictFloat = 0
32
+ result: StrictStr | StrictBytes | None = None
33
+ task_type: TaskType = TaskType.SHELL
34
+
35
+ def complete(self):
36
+ return self.status in [RunStatus.COMPLETE, RunStatus.CANCELLED, RunStatus.FAILED]
@@ -0,0 +1,26 @@
1
+ import time
2
+ from typing import Any, Optional
3
+ from pydantic import (
4
+ BaseModel,
5
+ StrictFloat,
6
+ StrictInt,
7
+ StrictStr,
8
+ )
9
+
10
+ from .run_status import RunStatus
11
+ from .task_type import TaskType
12
+
13
+
14
+ class TaskRun(BaseModel):
15
+ run_id: StrictInt
16
+ status: RunStatus
17
+ error: Optional[StrictStr] = None
18
+ trace: Optional[StrictStr] = None
19
+ start: StrictInt | StrictFloat = time.monotonic()
20
+ end: Optional[StrictInt | StrictFloat] = None
21
+ elapsed: StrictInt | StrictFloat = 0
22
+ result: Optional[Any] = None
23
+ task_type: TaskType = TaskType.CALLABLE
24
+
25
+ def complete(self):
26
+ return self.status in [RunStatus.COMPLETE, RunStatus.CANCELLED, RunStatus.FAILED]
@@ -0,0 +1,11 @@
1
+ from enum import Enum
2
+
3
+
4
+ class TaskStatus(Enum):
5
+ CREATED = "CREATED"
6
+ PENDING = "PENDING"
7
+ IDLE = "IDLE"
8
+ RUNNING = "RUNNING"
9
+ COMPLETE = "COMPLETE"
10
+ CANCELLED = "CANCELLED"
11
+ FAILED = "FAILED"
@@ -0,0 +1,6 @@
1
+ from enum import Enum
2
+
3
+
4
+ class TaskType(Enum):
5
+ CALLABLE = 'CALLABLE'
6
+ SHELL = 'SHELL'
taskex/run.py ADDED
@@ -0,0 +1,473 @@
1
+ import asyncio
2
+ import functools
3
+ import inspect
4
+ import pathlib
5
+ import time
6
+ import traceback
7
+ from asyncio.subprocess import Process
8
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
9
+ from typing import Any, Awaitable, Callable, Optional, Dict
10
+
11
+ from .models import (
12
+ RunStatus,
13
+ TaskRun,
14
+ ShellProcess,
15
+ CommandType,
16
+ TaskType,
17
+ )
18
+
19
+
20
+ class Run:
21
+ __slots__ = (
22
+ "run_id",
23
+ "status",
24
+ "error",
25
+ "trace",
26
+ "start",
27
+ "end",
28
+ "elapsed",
29
+ "timeout",
30
+ "call",
31
+ "result",
32
+ "task_type",
33
+ "_task",
34
+ "_process",
35
+ "_args",
36
+ "_env",
37
+ "_working_directory",
38
+ "_command_type",
39
+ "_buffer_size",
40
+ '_read_lock',
41
+ '_read_timeout',
42
+ "_loop",
43
+ "_executor",
44
+ "_semaphore",
45
+ )
46
+
47
+ def __init__(
48
+ self,
49
+ run_id: int,
50
+ call: Callable[..., Awaitable[Any]] | str,
51
+ task_type: TaskType,
52
+ executor: ProcessPoolExecutor | ThreadPoolExecutor,
53
+ semaphore: asyncio.Semaphore,
54
+ timeout: Optional[int] = None,
55
+ ) -> None:
56
+ self.run_id = run_id
57
+ self.status = RunStatus.CREATED
58
+
59
+ self._args: tuple[Any, ...] | None = None
60
+ self._env: dict[str, Any] | None = None
61
+ self._working_directory: str | None = None
62
+
63
+
64
+ self.error: Optional[str] = None
65
+ self.trace: Optional[str] = None
66
+ self.start = time.monotonic()
67
+ self.end = 0
68
+ self.elapsed = 0
69
+ self.timeout = timeout
70
+
71
+
72
+ self.call = call
73
+ self.task_type = task_type
74
+ self.result: Any | None = None
75
+ self._args: tuple[Any, ...] | None = None
76
+ self._env: dict[str, Any] | None = None
77
+ self._working_directory: str | None = None
78
+ self._read_lock = asyncio.Lock()
79
+
80
+ if not isinstance(self.call, str) and hasattr(call, '__self__'):
81
+ bound_instance = call.__self__
82
+ self.call = self.call.__get__(bound_instance, self.call.__class__)
83
+ setattr(bound_instance, self.call.__name__, self.call)
84
+
85
+ self._task: Optional[asyncio.Task] = None
86
+ self._process: Process | None = None
87
+ self._command_type: CommandType = 'subprocess'
88
+ self._buffer_size = 8192
89
+ self._read_timeout: int | float = 1
90
+ self._loop = asyncio.get_event_loop()
91
+ self._executor = executor
92
+ self._semaphore = semaphore
93
+
94
+ @property
95
+ def running(self):
96
+ return self.status == RunStatus.RUNNING
97
+
98
+ @property
99
+ def cancelled(self):
100
+ return self.status == RunStatus.CANCELLED
101
+
102
+ @property
103
+ def failed(self):
104
+ return self.status == RunStatus.FAILED
105
+
106
+ @property
107
+ def pending(self):
108
+ return self.status == RunStatus.PENDING
109
+
110
+ @property
111
+ def completed(self):
112
+ return self.status == RunStatus.COMPLETE
113
+
114
+ @property
115
+ def created(self):
116
+ return self.status == RunStatus.CREATED
117
+
118
+ @property
119
+ def pid(self):
120
+ if self._process:
121
+ return self._process.pid
122
+
123
+ @property
124
+ def return_code(self):
125
+ if self._process:
126
+ return self._process.returncode
127
+
128
+ async def get_stdout(self):
129
+ buffer = bytearray()
130
+
131
+ if self._process:
132
+ chunk = await self._read_stdout_with_timeout()
133
+ buffer.extend(chunk)
134
+
135
+ while chunk:
136
+ chunk = await self._read_stdout_with_timeout()
137
+ buffer.extend(chunk)
138
+
139
+ return bytes(buffer).decode()
140
+
141
+ async def get_stderr(self):
142
+ buffer = bytearray()
143
+ if self._process:
144
+ chunk = await self._read_stderr_with_timeout()
145
+ buffer.extend(chunk)
146
+
147
+ while chunk:
148
+ chunk = await self._read_stderr_with_timeout()
149
+ buffer.extend(chunk)
150
+
151
+ return bytes(buffer).decode()
152
+
153
+ async def _read_stderr_with_timeout(self):
154
+
155
+ await self._read_lock.acquire()
156
+
157
+ try:
158
+
159
+ chunk = await asyncio.wait_for(
160
+ self._process.stderr.read(self._buffer_size),
161
+ timeout=self._read_timeout,
162
+ )
163
+
164
+ except asyncio.TimeoutError:
165
+ chunk = b''
166
+
167
+ if self._read_lock.locked():
168
+ self._read_lock.release()
169
+
170
+ return chunk
171
+
172
+ async def _read_stdout_with_timeout(self):
173
+
174
+ await self._read_lock.acquire()
175
+
176
+ try:
177
+ chunk = await asyncio.wait_for(
178
+ self._process.stdout.read(self._buffer_size),
179
+ timeout=self._read_timeout,
180
+ )
181
+
182
+ except asyncio.TimeoutError:
183
+ chunk = b''
184
+
185
+ if self._read_lock.locked():
186
+ self._read_lock.release()
187
+
188
+ return chunk
189
+
190
+ @property
191
+ def task_running(self):
192
+ if self._process:
193
+ return self._process.returncode is None
194
+
195
+ return self._task and not self._task.done() and not self._task.cancelled()
196
+
197
+ async def get_run_update(self):
198
+ if self._process:
199
+ stderr = await self.get_stderr()
200
+ stdout = await self.get_stdout()
201
+
202
+ return ShellProcess(
203
+ run_id=self.run_id,
204
+ process_id=self._process.pid,
205
+ command=self.call,
206
+ args=self._args,
207
+ status=self.status,
208
+ return_code=self._process.returncode,
209
+ env=self._env,
210
+ working_directory=self._working_directory,
211
+ command_type=self._command_type,
212
+ error=stderr,
213
+ result=stdout,
214
+ trace=self.trace,
215
+ elapsed=time.monotonic() - self.start
216
+ )
217
+
218
+
219
+ return TaskRun(
220
+ run_id=self.run_id,
221
+ status=self.status,
222
+ error=self.error,
223
+ trace=self.trace,
224
+ start=self.start,
225
+ end=self.end,
226
+ elapsed=time.monotonic() - self.start,
227
+ result=self.result,
228
+ )
229
+
230
+ def update_status(self, status: RunStatus):
231
+ self.status = status
232
+ self.elapsed = time.monotonic() - self.start
233
+
234
+ async def complete(self):
235
+ completed = self.status in [RunStatus.COMPLETE, RunStatus.FAILED]
236
+
237
+ if completed:
238
+ try:
239
+ return await self._task
240
+
241
+ except (asyncio.InvalidStateError, asyncio.CancelledError):
242
+ pass
243
+
244
+ async def cancel(self):
245
+ if self._process:
246
+
247
+ try:
248
+ self._process.terminate()
249
+
250
+ except Exception:
251
+ pass
252
+
253
+ try:
254
+ self._task.set_result(None)
255
+
256
+ except Exception:
257
+ pass
258
+
259
+ self.status = RunStatus.CANCELLED
260
+
261
+ def abort(self):
262
+ if self._process:
263
+ self._process.kill()
264
+
265
+ try:
266
+ self._task.set_result(None)
267
+
268
+ except Exception:
269
+ pass
270
+
271
+ self.status = RunStatus.CANCELLED
272
+
273
+ def execute(self, *args, **kwargs):
274
+ self._task = asyncio.ensure_future(self._execute(*args, **kwargs))
275
+
276
+ def execute_shell(
277
+ self,
278
+ *args: tuple[Any, ...],
279
+ poll_interval: int | float = 0.5,
280
+ env: Dict[str, str] | None = None,
281
+ cwd: str | pathlib.Path | None = None,
282
+ shell: bool = False,
283
+ timeout: int | float | None = None
284
+ ):
285
+ self._args = args
286
+ self._env = env
287
+
288
+ if cwd:
289
+ self._working_directory = str(cwd)
290
+
291
+ self._task = asyncio.ensure_future(self._execute_shell(
292
+ *args,
293
+ env=env,
294
+ cwd=cwd,
295
+ shell=shell,
296
+ timeout=timeout,
297
+ poll_interval=poll_interval,
298
+ ))
299
+
300
+ async def _execute_shell(
301
+ self,
302
+ *args: tuple[Any, ...],
303
+ poll_interval: int | float = 0.5,
304
+ env: Dict[str, str] | None = None,
305
+ cwd: str | pathlib.Path | None = None,
306
+ shell: bool = False,
307
+ timeout: int | float | None = None,
308
+ ):
309
+ if shell:
310
+ self._command_type = 'shell'
311
+
312
+ working_directory: pathlib.Path | None = None
313
+ if cwd:
314
+ working_directory = pathlib.Path(cwd)
315
+
316
+ try:
317
+
318
+ if shell:
319
+ command = [self.call]
320
+ command.extend(args)
321
+
322
+ self._process = await asyncio.create_subprocess_shell(
323
+ ' '.join(command),
324
+ stdout=asyncio.subprocess.PIPE,
325
+ stderr=asyncio.subprocess.PIPE,
326
+ env=env,
327
+ cwd=working_directory if cwd else None,
328
+ )
329
+
330
+ else:
331
+ self._process = await asyncio.create_subprocess_exec(
332
+ self.call,
333
+ *args,
334
+ stdout=asyncio.subprocess.PIPE,
335
+ stderr=asyncio.subprocess.PIPE,
336
+ env=env,
337
+ cwd=working_directory if cwd else None
338
+ )
339
+
340
+ except Exception:
341
+ pass
342
+
343
+ self.status = RunStatus.RUNNING
344
+
345
+ try:
346
+ if timeout:
347
+ update =await asyncio.wait_for(
348
+ self._poll_for_shell_complete(poll_interval),
349
+ timeout=timeout,
350
+ )
351
+
352
+ else:
353
+ update = await self._poll_for_shell_complete(poll_interval)
354
+
355
+ except asyncio.TimeoutError:
356
+ error = f"Err. - Task Run - {self.run_id} - timed out. Exceeded deadline of - {self.timeout} - seconds."
357
+ self.status = RunStatus.FAILED
358
+
359
+ update = ShellProcess(
360
+ run_id=self.run_id,
361
+ process_id=self._process.pid,
362
+ command=self.call,
363
+ args=self._args,
364
+ status=self.status,
365
+ return_code=self._process.returncode,
366
+ env=self._env,
367
+ working_directory=self._working_directory,
368
+ command_type=self._command_type,
369
+ error=error,
370
+ trace=self.trace,
371
+ elapsed=self.start - time.monotonic()
372
+
373
+ )
374
+
375
+ error_message = ''
376
+ try:
377
+ error_message = update.error
378
+
379
+ except Exception:
380
+ error_message = 'Unknown exception - failed to decode stderr output'
381
+
382
+ self.error = error_message
383
+
384
+ if self.return_code != 0:
385
+ self.error = f"Err. - Task Run - {self.run_id} - failed. Encountered exception - {error_message}."
386
+ self.status = RunStatus.FAILED
387
+
388
+ else:
389
+ self.status = RunStatus.COMPLETE
390
+ try:
391
+ self.result = update.result.decode()
392
+
393
+ except Exception:
394
+ pass
395
+
396
+ return update
397
+
398
+ async def _poll_for_shell_complete(
399
+ self,
400
+ poll_interval: int | float
401
+ ):
402
+ result = await self.get_run_update()
403
+ while self._process.returncode is None:
404
+ await asyncio.sleep(poll_interval)
405
+ result = await self.get_run_update()
406
+
407
+ self.elapsed = time.monotonic() - self.start
408
+
409
+
410
+ return result
411
+
412
+ async def _execute(self, *args, **kwargs):
413
+ try:
414
+ self.status = RunStatus.RUNNING
415
+
416
+ is_coroutine = (
417
+ inspect.iscoroutine(self.call)
418
+ or inspect.isawaitable(self.call)
419
+ or inspect.iscoroutinefunction(self.call)
420
+ )
421
+
422
+ if self.timeout and is_coroutine:
423
+
424
+ self.result = await asyncio.wait_for(
425
+ self.call(*args, **kwargs), timeout=self.timeout
426
+ )
427
+
428
+ elif is_coroutine:
429
+ self.result = await self.call(*args, **kwargs)
430
+
431
+ elif self.timeout:
432
+ await self._semaphore.acquire()
433
+ self.result = await asyncio.wait_for(
434
+ self._loop.run_in_executor(
435
+ self._executor,
436
+ functools.partial(
437
+ self.call,
438
+ *args,
439
+ **kwargs
440
+ )
441
+ )
442
+ )
443
+
444
+ self._semaphore.release()
445
+
446
+ else:
447
+ await self._semaphore.acquire()
448
+ self.result = await self._loop.run_in_executor(
449
+ self._executor,
450
+ functools.partial(
451
+ self.call,
452
+ *args,
453
+ **kwargs
454
+ )
455
+ )
456
+
457
+ self._semaphore.release()
458
+
459
+ self.status = RunStatus.COMPLETE
460
+
461
+ except asyncio.TimeoutError:
462
+ self.error = f"Err. - Task Run - {self.run_id} - timed out. Exceeded deadline of - {self.timeout} - seconds."
463
+ self.status = RunStatus.FAILED
464
+
465
+ except Exception as e:
466
+ self.error = f"Err. - Task Run - {self.run_id} - failed. Encountered exception - {str(e)}."
467
+ self.trace = traceback.format_exc()
468
+ self.status = RunStatus.FAILED
469
+
470
+ self.end = time.monotonic()
471
+ self.elapsed = self.end - self.start
472
+
473
+ return self.result
@@ -0,0 +1 @@
1
+ from .snowflake_generator import SnowflakeGenerator as SnowflakeGenerator
@@ -0,0 +1,3 @@
1
+ MAX_TS = 0b11111111111111111111111111111111111111111
2
+ MAX_INSTANCE = 0b1111111111
3
+ MAX_SEQ = 0b111111111111
@@ -0,0 +1,47 @@
1
+ from dataclasses import dataclass
2
+ from datetime import datetime, tzinfo, timedelta
3
+ from typing import Optional
4
+ from .constants import MAX_INSTANCE, MAX_SEQ
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Snowflake:
9
+ timestamp: int
10
+ instance: int
11
+ epoch: int = 0
12
+ seq: int = 0
13
+
14
+ @classmethod
15
+ def parse(cls, snowflake: int, epoch: int = 0) -> "Snowflake":
16
+ return cls(
17
+ epoch=epoch,
18
+ timestamp=snowflake >> 22,
19
+ instance=snowflake >> 12 & MAX_INSTANCE,
20
+ seq=snowflake & MAX_SEQ,
21
+ )
22
+
23
+ @property
24
+ def milliseconds(self) -> int:
25
+ return self.timestamp + self.epoch
26
+
27
+ @property
28
+ def seconds(self) -> float:
29
+ return self.milliseconds / 1000
30
+
31
+ @property
32
+ def datetime(self) -> datetime:
33
+ return datetime.utcfromtimestamp(self.seconds)
34
+
35
+ def datetime_tz(self, tz: Optional[tzinfo] = None) -> datetime:
36
+ return datetime.fromtimestamp(self.seconds, tz=tz)
37
+
38
+ @property
39
+ def timedelta(self) -> timedelta:
40
+ return timedelta(milliseconds=self.epoch)
41
+
42
+ @property
43
+ def value(self) -> int:
44
+ return self.timestamp << 22 | self.instance << 12 | self.seq
45
+
46
+ def __int__(self) -> int:
47
+ return self.value